Reputation: 404
I would like to know how to get get a PHP variable value from another PHP file using jquery. In fact I have to files: test.html and moslem.php . the code of test.html file is as below:
<html>
<head>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
setTimeout( "test()", 1000);
function test() {
$.ajax({
url: 'moslem.php',
type: 'POST',
data: ,
success: function(data) {
document.write(data);
}
});
setTimeout ( "test()", 1000);
}
</script>
</body>
</html>
And the code of moslem.php file is as below:
<?php
$chaine = "hello!";
?>
I would like to know how can I get the value of the variable $chaine using the jquery code above, then what should I put at the line :
data: ,
of that jquery code.
Thanks in advance.
Upvotes: 1
Views: 4268
Reputation: 147
Please try with this
<script type="text/javascript">
function test() {
$.ajax({
url: 'moslem.php',
type: 'POST',
success: function(data) {
document.write(data);
}
});
}
$(document).ready(function() {
setTimeout( test, 1000);
});
</script>
No Need to pass the data parameter into ajax. And php file will remain same as before post.
<?php
$chaine = "hello!";
echo $chaine;
?>
Upvotes: 0
Reputation: 12621
You don't need to change your JQuery to make that happen; you just need to change your PHP a bit. If you set a variable in PHP, JavaScript isn't going to recognise this. If you make your PHP code output the text instead of putting it in a variable, Javascript will see this output and can do whatever you want with it.
Just change $chaine = "hello!";
to echo "hello!";
Edit: I'd just like to add that when you start passing a lot of data through AJAX you should consider using JSON to keep things organised. If you have an array of data you want to pass to JavaScript, for example, just call json_encode
on the data and output that, then you can parse it in your JS code.
Bottom line here, though, is that your front-end code won't 'recognise' variables set in PHP, it can only read output from your server-side code.
Upvotes: 1
Reputation: 34416
Put your code in a document ready handler -
<script type="text/javascript">
$(document).ready(function() {
setTimeout( "test()", 1000);
function test() {
$.ajax({
url: 'moslem.php',
type: 'POST',
data: ,
success: function(data) {
document.write(data);
}
});
setTimeout ( "test()", 1000);
}
});
</script>
And then fix your PHP -
<?php
$chaine = "hello!";
echo $chaine;
?>
Upvotes: 0