norbidrak
norbidrak

Reputation: 473

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:

$.ajax({
                type: 'POST',
                data: ({p:2,ank : ankieta,wybrane:wybrane}),
                url: 'zestawienia_db.php',
                success: function(data) {

                     $('#results').html(data);
  }
        });

and it works fine by printing my results. My php file is echoing data that should be printed in my results div. Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??

Upvotes: 1

Views: 277

Answers (4)

R3tep
R3tep

Reputation: 12864

Use json format, and in this json add your data variables :

PHP :

$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);

echo json_encode($arr);

Javascript :

$.ajax({
    type: 'POST',
    data: ({p:2,ank : ankieta,wybrane:wybrane}),
    url: 'zestawienia_db.php',
    success: function(data) {
      data = JSON && JSON.parse(data) || $.parseJSON(data);
      $('#results1').html(data.var1);
      $('#results2').html(data.var2);
    }
});

Upvotes: 1

user2806061
user2806061

Reputation:

write this type of code in ajax file

var data =array('name'=>'steve', date=>'18-3-2014');

echo jsonencode(data);

//ajax call in this manner

$.ajax({ type: 'POST',

data:  pass data array,

url: ajaxfile url,

success: function(data) {

 var data = $.parseJSON(data);

 $('#name').html(data.name);
 $('#date').html(data.date);
}

});

Upvotes: 1

frikinside
frikinside

Reputation: 1244

Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.

<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>

And you could use those values accessing PHPVariables.VariableName1 on the javascript.

Upvotes: 5

Jack Price-Burns
Jack Price-Burns

Reputation: 190

You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.

the explode function is used like this

explode('§', $somestringofinfoyouwanttoturnintoanarray);

you can then echo the relevent data like so echo data[0]; which in this case wiill echo the text peiceofdata.

Upvotes: 1

Related Questions