skip to Main Content

I am trying to pass some values using AJAX from one php page to another but I am not able to pass it correctly. The objective is also to load the next page after passing the value to it.
But I am not able to do it and the value is not getting passed to the next php page. I get the error

Notice: Undefined index: var1

Here is my java code of the first page

function next(){
    $.ajax({
         url: "next.php",
        data: { var1 : 123 },
        success: function( data ) {
            console.log( data );
        }
    }).done(function(data) { 
        $("#content").load("next.php");
    });
}

Here is the html code of the first page

<button onclick="next()">Click me</button>
<div id="content">

Now in my second page I am using this to get the variable

<?php echo $_GET['var1'];?>

I have tried solutions from other post in the Internet but till now not finding any solution. Hope someone gives the answer.
Thanks a lot

2

Answers


  1. Change next function code to this:

    function next(){
      $.ajax({
        url: "next.php",
        data: {var1 : 123},
      }).done(function(data) { 
          $("#content").html(data);
      });
    }
    

    .load() in jQuery will do another Ajax request with no data argument, that’s why you get the Notice. Also you are not inserting the data returned form the Ajax call in your content div .

    Login or Signup to reply.
  2. By running $('#content').load("next.php") you are essentially loading the page again with no query parameters. You’re already getting the response of the request to next.php in your success function – it’s stored in the variable data. So you can just do $('#content').html(data); in your success function.

    function next(){
        $.ajax({
            url: "next.php",
            data: {var1 : 123},
            success: function( data ) {
                $('#content').html(data);
            }
        });
    }
    

    Note that the success function only executes on a HTTP 200 so if you want to be really fancy you can do this:

    function next(){
        $.ajax({
            url: "next.php",
            data: {var1 : 123},
            success: function( data ) {
                $('#content').html(data);
            },
            error: function() {
                console.log("an error occurred");
            }
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search