Search code examples
jqueryajax

Passing response from an AJAX call to another page


I am getting a Json array as response from an ajax call, I want to post this Json array data immediately to another page and redirect to that page. Does anyone know how I can do that

 $.post("flightsearch/searchhome.php",{
                    fromairport2  : fromairport1,
                    toairport2    : toairport1
                }, function(data){
                       alert(data);
                       //var response = data;
                       //window.location.replace("flight-detail.php");
                });

I want to post the response data i am getting to that page and redirecting to that page at the same time


Solution

  • Once you've captured your JSON, create a jQuery object of a form with the associated input fields. Once the form is created, submit it. I'm only removing it to prevent it from showing on the users screen during the load.

    /* Bind Click Event to Button */
    $('button').on('click', function() {
        /* Set Empty jQuery Form Object */
        var formObject = $('<form/>', { method: 'POST' });
        
        /* Fetch JSON */
        $.get('https://jsonplaceholder.typicode.com/posts/1', function(response) {
            /* Itererate Through Response */
            $.each(response, function(key, value) {
                /* Append jQuery Input Object w/ Associated Name/Value to Form Object */
                $('<input/>', { name: key, value: value }).appendTo(formObject);
            });
            
            /* Append Form Object to Body, Submit, and Remove */
            formObject.appendTo('body').submit().remove();
        });
    });
    
    /* Delegating Form Submission on Body to Prevent Submission to Show Console Log */
    $('body').on('submit', 'form', function(event) {
      event.preventDefault();
      console.log($(this).serializeArray());
    });
    <body>
        <button>Fetch JSON and POST</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </body>