开发者

Passing PHP variables through Jquery AJAX

I am trying to learn the Jquery AJAX function but am struggling to work out how to pass PHP variables into my main document.

This is what I currently have:

<script>
  var refreshId = setInterval(function() {
开发者_JS百科    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        $('#testdiv').html(data.test1);
        $('#testdiv').append(html(data.test2));
        //parse the json data
      }
    });

}, 1000);
</script>


You should use json or xml format and parse it, and get the variable.

<script src="jquery.js"></script>
<script>
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        alert(data.test1);
        //parse the json data
      }
    });
</script>

on test.php

<?php

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html


use dataType='json' in ajax option on index.php

and on test.php use json_encode

$ret_array= array ($test1, $test2 and $test3);
echo json_encode($ret_array);

again on index.php

now if u want to use it in your *J*S file then access via object navigation or using getJSON method

and if u want to use that data directly in php then use json_decode

json_decode($ret_array,true);

References

json_encode
getJSON
json_decode


Another approach (with ajax but hidden field) would be:

$.ajax({
    type: 'POST',
    url: "test.php",
    dataType: "json", //the return type data is jsonn
    success: function(data){ // <--- (data) is in json format
        $('#testdiv').html('<input type="hidden" value="' + data.test1 + '" />');
    }
    error: ajaxError,
    dataType: "html"
});

With that inside of your form you can even use your value in the next Postback without passing it directly.


You don't pass them into index.php, but you can add them as content that is loaded by your ajax something like this:

$test1 = '1';
$test2 = '2';
$test3 = '3';

echo $test1 . "<br/>" . $test2 . "<br/>" . $test3 . "<br/>";


Unless im greatly mistaken its as simple as:

<?php
  include 'test.php';
?>

To include the test.php file in index.php

Then you can call them as if they were variables set in index.php, i would then do the following to get them into jQuery:

$("#test1") etc...

Update

The problem I have is that the variables in test.php will be changing constantly, and then these need to be updated on index.php. I only set them as 1, 2 and 3 to test it out. – user683526 1 min ago

In that case set them in a function and return the values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜