I am trying to append php to a div using
<script>
var values = {var1: 2, var2:"Hello"};
$('#id').append($.get("phpfile.php", values));
</script>
However it doesnt seem to append the basic echo in the php file
<?php
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
echo "var1= " . $var1 . " " . "var2= " . $var2;
?>
any help would be appreciated.
Ajax calls are asynchronous. This means that the return value of the $.get()
function will not be the result of the request, as the request has not yet executed. You need to use the $.get()
call's success handler which will be called when the request comes back successful, or make use of the jQuery deferred object (A promise) that is returned by the $.get
function.
Correct syntax #1:
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values, function(data) {
$('#id').append(data);
});
</script>
Here is an alternative syntax using promises :
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values).done(function(data) {
$('#id').append(data);
});
</script>
use this, jQuery :
<script>
$.get("phpfile.php", { 'var1': 1, 'var2' : 2},
function(data){ $('#id').append(data); }, "json");
});
</script>
php :
<?php
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];
$data = "var1= " . $var1 . " " . "var2= " . $var2;
echo json_encode($data);
exit;
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.