skip to Main Content

To sum up what I’m trying to achieve here:

  • Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>
  • This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data
  • The PHP page is displayed inside a div on the page

Here is the function, using jQuery:

function displayData(str){
  $.ajax({
    url: "target.php",
    type: "POST",
    data: {"value": str.value},
    success: function(data){
      console.log(data);
    }
  });

  $('#my-div').load('target.php');
}

To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>

When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:

Notice: Undefined index: value

Sorry if it seems kind of dumb, but I can’t figure out what I’m doing wrong… So I thought of asking the community. Thank you for your help guys! Cheers.


3

Answers


  1. Please try this.
    and you need to return the result from target.php page

    function displayData(str){
      $.ajax({
        url: "target.php",
        type: "POST",
        data: {"value": str.value},
        success: function(data){
          $('#my-div').html(data);
        }
      });
    
    }
    
    Login or Signup to reply.
  2. If you use .load() your browser will make another GET request to target.php and display it, so your $_POST will be empty.
    You can use $('#my-div').html(data) inside success: of ajax or you can use $_GET instead of $_POST in your php and pass variable in url like this

    $('#my-div').load('target.php?value='str.value);

    Login or Signup to reply.
  3. hey the problem is quite simple, if you are posting the data value getting from ajax to target.php then the $(‘#my-div’).load(‘target.php’) should be inside the ajax success function and you have to put the data using html function like this $(“#my-div”).html(data). it will directly load the data in html format inside the div.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search