I am learning jQuery recently and trying to do an ajax call to a very simple PHP script, which just output 1 json text. When I just have 1 echo statement in my script, I was able to get the call working. I then tried to mimic a complex script by echo 4 json after sleep for 3 seconds each time, but this time I could not be able to make it work.
Here is my index.html:
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script src="app.js"></script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
Here is my app.js:
$(function() {
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
var req = $.ajax({
url: "x.php",
dataType: "json"
});
req.done(function(data) {
setTimeout(function () {
$('#loading').html(data.text);
}, 1000);
});
});
Here is my x.php:
<?php
sleep(3);
echo json_encode(array("text"=>"you got me1"));
sleep(3);
echo json_encode(array("text"=>"you got me2"));
sleep(3);
echo json_encode(array("text"=>"you got me3"));
sleep(3);
echo json_encode(array("text"=>"you got me4"));
?>
My purpose is trying to show 'you got me1', 'you got me2'...one by one after few seconds. Could anyone please help and tell me where I am doing wrong? Thanks a lot in advance.
JSON must be a monolithic string. You cannot output four separate JSON constructs in a single response. e.g.
$x = array('foo');
$y = array('bar');
$z = array('baz');
echo json_encode($x);
echo json_encode($y);
echo json_encode($z);
Will send
['foo']['bar']['baz']
across the wire. That is NOT syntactically valid JSON and will simplyl produce a parse error on the receiving end.
If you want to send 4 different chunks of data over as JSON, you'll either have to do four separate requests, or embed each response in a sub-array, e.g.
$response = array(
'x' => array('foo'),
'y' => array('bar'),
'z' => array('baz')
);
echo json_encode($response);
Remember that JSON is (almost exactly) the same as the "right-hand side" of a variable assignment in Javascript:
var foo = XXX;
^^^---json goes here
If you want your output to be accepted, you have to generate something that you could literally paste into that assignment operation and have the JS engine parse/execute it properly, so
var response = ['foo']['bar']['baz']; // syntax error
var response = [['foo'],['bar'],['baz']]; // syntactically valid
Related
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
EDIT: SOLVED. Use any of the solutions below, but document.onload needs to be changed to window.onload. Also works without needing window.onload function anyway.
Here is the test.php file that i'm working with
<?php
include("conn.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script type="text/javascript">
document.onload = function (){
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
console.log(jsonObj);
alert( jsonObj.Auckland );
};
</script>
</body>
</html>
I have verified in Chrome Developer tools the value of jsonString to be
'{"Auckland":37616,"Wellington":35357,"Christchurch":29818}'
After that I don't get any log on the console or any alert box. I have also tried JSON.parse method instead of jQuery.parseJSON to no avail.
I'm trying to get this JSON into a datatable format used for google charts geo chart which looks like this bit of code
var data = google.visualization.arrayToDataTable([
['City', 'Population', 'Area'],
['Rome', 2761477, 1285.31],
['Milan', 1324110, 181.76],
['Naples', 959574, 117.27],
['Turin', 907563, 130.17],
['Palermo', 655875, 158.9],
['Genoa', 607906, 243.60],
['Bologna', 380181, 140.7],
['Florence', 371282, 102.41],
['Fiumicino', 67370, 213.44],
['Anzio', 52192, 43.43],
['Ciampino', 38262, 11]
]);
If you don't put it as a string it would be an object and you would not have to parse it
var jsonObj = <?php echo json_encode($rowarr); ?>;
instead of
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
It looks like document.onload doesn't fire/already fired? you should use window.onload or $(document).ready() instead.
Since you are actually inserting the JSON with a php echo right inside the script tag in the actual html page, it technically becomes an object literal. There is no need to go through the extra parsing step in JavaScript.
So in your case, the value you assign to jsonString is actually already an object.
You need to parse JSON only if it really is in the form of a string. So the actual script part sent to the browser should look like this:
var cities = {"Auckland":37616,"Wellington":35357,"Christchurch":29818};
console.log(cities);
alert( cities.Auckland );
You don't get the alert box because most likely your code throws a JavaScript error and simply stops executing after you try to parse the object.
I guess the handler function is never fired: There is no load event on the document object (see window.onload vs document.onload). You don't need to wait for that anyway, because you have nothing in the handler that interacts with the DOM - and you execute it in the bottom of your <body> tag (see Is the 'onload' necessary when the code is at the bottom?).
As JSON is a subset of JavaScript, you can directly output it into a script as a object literal:
var jsonObj = <?php echo json_encode($rowarr); ?>;
console.log(jsonObj);
alert( jsonObj.Auckland );
No need to parse it. Especially, when your JSON had contained an unescaped apostrohe, this would have broken your string literal.
I've got a JSON value that has been converted from a JavaScript object using JSON.stringify. I'm trying to parse the contents of the JSON using PHP, but I haven't had any luck. I'm sure I'm doing something really basic wrong.
In file1.php, I've got something like:
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src='/json2.js'></script>
<script>
var irxmlnewsreleases = new Array();
irxmlnewsreleases[0]={
"attachmentfileid":12039
};
var news_release = JSON.stringify(irxmlnewsreleases);
$(document).ready(function () {
$("#response").text(news_release);
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
I'm then trying to read this data from file1.php using json_decode in file2.php.
I tried first (wrongly) using file_get_contents and have been bashing at this for a while without success. I guess the issue is obviously that the JSON value doesn't exist until the JavaScript is run, so PHP is of course never able to read the value of the jQuery-generated div content. What I don't know is how to get that value.
The JSON is being generated successfully in file1.php and is valid JSON (I've run it through jsonlint).
What's a better way of getting the value of that dynamically-generated JSON into PHP?
$(document).ready(function () {
$("#response").text(news_release);
$.post('file2.php', { php_post_var1: news_release }, function (data) {
//do something with the PHP script output here if you want
});
});
Then in your PHP script file2.php do something like
<?php
$news_release = $_POST['php_post_var1'];
echo 'PHP received ' . $news_release;
?>