JAN
JAN

Reputation: 21855

How to pass a variable to HTML page from JS code , after ajax success?

Consider the ajax request :

var idNumber = $("#Field_1").val();
var servletUrl = "someURL"; // some url goes here

$.ajax({ 
    url: servletUrl,
    type: 'POST',
    cache: false, 
    data: { }, 
    success: function(data){
        alert(data);
        window.location = "./replyToYou.html";
    }
    , error: function(jqXHR, textStatus, err){
        alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR));
    }
});

How can I pass , on success idNumber to replyToYou.html , and how can I grab it in replyToYou.html ?

Much appreciated

Upvotes: 0

Views: 119

Answers (2)

Mehran Hatami
Mehran Hatami

Reputation: 12961

you have to different solution:

1- first is using queryString:

success: function(data){
    alert(data);
    window.location = "./replyToYou.html?idNumber=" + idNumber;
}

then read it from querystring using this function (I use it as a querystring helper which is originally created in this POST):

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
getParameterByName("idNumber");

2- the other option is using localStorage:

success: function(data){
    alert(data);
    localStorage.setItem("idNumber",idNumber);
    window.location = "./replyToYou.html";
}

and get it at the other page like:

localStorage.getItem("idNumber")

Upvotes: 1

evergreen
evergreen

Reputation: 8165

edit code js in success section :

success: function(data){
    alert(data);
   window.location.href = "./replyToYou.html?idNumber=" + idNumber;
}

Upvotes: 1

Related Questions