Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables with POST to another page with Jquery

I am relatively new to Jquery and I was wondering how would one post variables to another page and then redirect? I used ajax function, the redirect works fine, but no variables are captured in POST (they are empty)

function linkWO() {

    $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "LinkTagOut.aspx",
            dataType: "json",
            data: "{id=1}",
            complete:
            function () {
                window.location = "LinkTagOut.aspx";
            }

    });
}

in my aspx file

<a href="javascript:void(0);" onclick="return linkWO();"><span>Link</span></a>
like image 850
sarsnake Avatar asked Dec 03 '10 22:12

sarsnake


People also ask

How do you pass a value to another page in Javascript?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

How do you send a variable to another page in Ajax?

ajax({ type: 'POST', url: '../portal/curriculum. php', data: 'studentNumber='+$('#StudentID'). val(), success: function(data) { $('#curriculum'). html(data); } }); });


2 Answers

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "LinkTagOut.aspx",
        dataType: "json",
        data: { id: 1 }, // or the string: 'id=1'
        complete:
        function () {
            window.location = "LinkTagOut.aspx";
        }

});

From the $.ajax documentation (data option):

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

Also, make sure to return false from the end of the submit handler (or whatever fires the ajax call) to ensure that a 'normal' redirect is not happening.

like image 74
karim79 Avatar answered Oct 21 '22 13:10

karim79


This answer is just for a quick fix

why don't you just pass as query string here

window.location = "LinkTagOut.aspx?variabletopass=test"; 
<form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>

$('#target').submit(function() {
$.post('ajax/test.html', function(data) {      
});
  return false;
});
like image 45
kobe Avatar answered Oct 21 '22 12:10

kobe