Hriju
Hriju

Reputation: 738

how to use ajax response data in php

I am having problem with response data. I want to use response data in my php file. I want to assign them to a php variable.

here is the ajax code in insert.php file.

function change(){
    var tp=$('#choose').val();
    var country_val=$('#country_filter').val();
    //alert(country_val);
    //var country_val=$('#country_filter').val();
        $.ajax({
            type: "POST",
            url: "filter.php",
            data: { name: tp, country:"test"},

        success:function( data ) {
          alert(data);
            }

        });
     }

here is php code in filter.php

if($_REQUEST["name"]){
 $lvl = $_REQUEST["name"];
 //global $lvl;
echo $lvl;
}

Now I want to use the response data to be assigned to a php variable in insert.php file. How may I do that? Please help.

Upvotes: 4

Views: 6433

Answers (2)

Karlton
Karlton

Reputation: 116

If insert.php calls filter.php with ajax and then returns a value. you cannot apply that javascript var to a php var in the insert.php. That is because the Php script runs on the server when the page is loaded, and the javascript runs locally on the users computer. To apply anything to a php variable you will have to reload the page.

Upvotes: 0

Optimus Prime
Optimus Prime

Reputation: 6907

Send the data to insert.php file using ajax, instead of alerting it.

change success function to

$.ajax({
 type: "POST",
 url: "filter.php",
 data: { name: tp, country:"test"},


  success:function(response) {
    var res = response;
    $.ajax({
        type: "POST",
        url: "insert.php",
        data: { res: res },

    success:function(data){
      alert(data);
      }
   });
});

In insert.php,

use this to get the variable.

$var = $_POST['res'];

Upvotes: 1

Related Questions