Skip to main content

Non-ajax GET/POST using jQuery (plugin?)



This is one of those situations where I feel like I'm missing a crucial keyword to find the answer on Google...





I have a bag of parameters and I want to make the browser navigate to a GET URL with the parameters. Being a jQuery user, I know that if I wanted to make an ajax request, I would simply do:







$.getJSON(url, params, fn_handle_result);







But sometimes I don't want to use ajax. I just want to submit the parameters and get a page back.





Now, I know I can loop the parameters and manually construct a GET URL. For POST, I can dynamically create a form, populate it with fields and submit. But I'm sure somebody has written a plugin that does this already. Or maybe I missed something and you can do it with core jQuery.





So, does anybody know of such a plugin?





EDIT: Basically, what I want is to write:







$.goTo(url, params);







And optionally







$.goTo(url, params, "POST");





Source: Tips4all

Comments

  1. jQuery Plugin seemed to work great until I tried it on IE8. I had to make this slight modification to get it to work on IE:

    (function($) {
    $.extend({
    getGo: function(url, params) {
    document.location = url + '?' + $.param(params);
    },
    postGo: function(url, params) {
    var $form = $("<form>")
    .attr("method", "post")
    .attr("action", url);
    $.each(params, function(name, value) {
    $("<input type='hidden'>")
    .attr("name", name)
    .attr("value", value)
    .appendTo($form);
    });
    $form.appendTo("body");
    $form.submit();
    }
    });
    })(jQuery);

    ReplyDelete
  2. It is not clear from the question if you have a random bunch of values you want to pass on the querystring or is it form values.

    For form values just use the .serialize function to construct the querystring.

    e.g

    var qString = $('#formid').serialize();
    document.location = 'someUrl' + '?' + serializedForm


    If you have a random bunch of values you can construct an object and use the .param utility method.

    e.g

    var params = { width:1680, height:1050 };
    var str = jQuery.param( params );
    console.log( str )
    // prints width=1680&height=1050
    // document.location = 'someUrl' + '?' + str

    ReplyDelete
  3. Here's what I ended up doing, using the tip from redsquare:

    (function($) {
    $.extend({
    doGet: function(url, params) {
    document.location = url + '?' + $.param(params);
    },
    doPost: function(url, params) {
    var $form = $("<form method='POST'>").attr("action", url);
    $.each(params, function(name, value) {
    $("<input type='hidden'>")
    .attr("name", name)
    .attr("value", value)
    .appendTo($form);
    });
    $form.appendTo("body");
    $form.submit();
    }
    });
    })(jQuery);


    Usage:

    $.doPost("/mail/send.php", {
    subject: "test email",
    body: "This is a test email sent with $.doPost"
    });


    Any feedback would be welcome.

    Update: see dustin's answer for a version that works in IE8

    ReplyDelete
  4. FYI for anyone doing the doPost for rails 3, you need to add in the CSRF token, Adding the following to the answer should do that...

    var token = $('meta[name="csrf-token"]').attr('content');
    $("<input name='authenticity_token' type='hidden' value='" + token + "'/>").appendTo($form);

    ReplyDelete
  5. Yes. Excellent itsadok! That's just what I was looking for. I think that this non-ajax get and post functionality should be officially included in jquery. Thanks.

    ReplyDelete
  6. Good job itsadok! If you want a invisible form put it into hidden DIV:

    (function($) {
    $.extend({
    doGet: function(url, params) {
    document.location = url + '?' + $.param(params);
    },
    doPost: function(url, params) {
    var $div = $("<div>").css("display", "none");
    var $form = $("<form method='POST'>").attr("action", url);
    $.each(params, function(name, value) {
    $("<input type='hidden'>")
    .attr("name", name)
    .attr("value", value)
    .appendTo($form);
    });
    $form.appendTo($div);
    $div.appendTo("body");
    $form.submit();
    }
    });
    })(jQuery);

    ReplyDelete
  7. The accepted answer doesn't seem to cover your POST requirement, as setting document.location will always result in a GET request. Here's a possible solution, although I'm not sure jQuery permits loading the entire contents of the page like this:

    $.post(url, params, function(data) {
    $(document).html(data);
    }, "html");

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.