I have this code:
var temp = 'tag1,tag2'.split(','),
tags = [];
if (temp.length > 0) {
for (i = 0; i < temp.length; ++i) {
tags.push(temp[i]);
}
}
Now I want to send this array as an Ajax request:
var data = {
action: 'my_wp_ajax',
ajax_req: JSON.stringify(tags)
};
$.post(
ajaxurl,
data,
function (data) {
console.log('this is data: '+data);
}
);
On the other side I have these codes:
echo $_POST['ajax_req'];
$temp = json_decode($_POST['ajax_req']);
$error = json_last_error();
echo $error;
The result I see in browser console is:
this is data: "[\\\"tag1\\\",\\\"tag2\\\"]4"
As you can see in above result, last json error is 4 which means invalid json syntax. I don't know what is wrong in above codes. If I try
foreach (json_decode($_POST['ajax_req']) as $hi)
echo $hi;
In console it only shows me
this is data: ""
What am I doing wrong?
Edit:
I tried var_dump(get_magic_quotes_gpc(), $_POST); and the result in console:
"bool(false)\narray(2) {\n [\"action\"]=>\n string(8) \"my_wp_ajax\"\n [\"ajax_req\"]=>\n string(19) \"[\\\"tag1\\\",\\\"tag2\\\"]\"\n}\n0"
No need to double stringify array, data passed to array is going to be properly handled by jQuery:
var tags = 'tag1,tag2'.split(',');
var data = {
action: 'my_wp_ajax',
ajax_req: tags
};
Related
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.
I'm echoing json with php like so:
$jsonarray= array();
while($rs = mysqli_fetch_assoc($result)) {
$jsonarray["userName"]= $rs["userName"];
$jsonarray["UserGender"]= $rs["UserGender"];
$jsonarray["channel"]= $rs["channel"];
$jsonarray["channelName"]= $rs["channelName"];
$jsonarray["camonoff"]= $rs["camonoff"];
$jsonarray["rtccam"]= $rs["rtccam"];
$jsonarray["iswatching"]= $rs["iswatching"];
$jsonarray["iswatchingembed"] = $rs["iswatchingembed"];
$jsonarray["islisteningtoradio"]= $rs["islisteningtoradio"];
$jsonarray["statusmsg"] = $rs["statusmsg"];
$jsonarray["activity"]= $rs["activity"];
echo json_encode($jsonarray);
}
With an ajax call i get the string like:
$.get('lib/class/json.php', data, function(returnData) {
jsondata= returnData;
jsonupdateregion(jsondata);
});
I pass the received data to a function like:
function jsonupdateregion(jsondata) {
var regions = ["Lobby", "Noord-Brabant", "Groningen", "Friesland", "Gelderland", "Limburg", "Zeeland", "Overijssel", "Drenthe", "Noord-Holland", "Zuid-Holland", "Utrecht", "Belgie", "Duitsland"];
var i;
str= "";
for (i = 0; i < regions.length; i++) {
str += regions[i]
+ getCount(regions[i], jsondata);
}
console.log(str);
}
The above fuction has to call the following function for every region in the array regions and return the number of occurrences
function getCount(regions, jsondata) {
var count = 0;
for (var i = 0; i < jsondata.length; i++) {
if (jsondata.channelName[i] == regions) {
count++;
}
}
return count;
}
The above result in a " Uncaught TypeError: Cannot read property '0' of undefined"
When i use the json.parse on the data i get an error like: " Uncaught SyntaxError: Unexpected token {
The php file itself sends a header with: "header('Content-Type: text/html; charset=utf-8');"
What am i doing wrong here?
When i use the json.parse i get an error stating an unexpectit token
I've altered the query on the server and it's now definitly outputting valid Json according to http://jsonlint.com/ .
if(isset($test)){
$sql = 'SELECT
userName,
UserGender,
UserRegion,
channel,
channelName,
camonoff,
rtccam,
iswatching,
iswatchingembed,
islisteningtoradio,
statusmsg,
activity
FROM
users';
$result=mysqli_query($conn,$sql);
$json = array();
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$json[]=json_encode($row);
}
}
mysqli_close($mysqli);
echo json_encode($json);
}
UPDATE:
The fault was in the javascript:
Had to change:
for (i = 0; i < obj.length; i++) {
if (obj.channelName[i] == regions) {
count++;
}
TO:
for (i = 0; i < obj.length; i++) {
if (obj[i].channelName == regions) {
count++;
}
And in php revert back to echoing
echo json_encode($json);
At first, try to give jquery a hint, that json is sent and see, what it receives in your browser console
(http://api.jquery.com/jquery.get/)
$.get('lib/class/json.php', data, function(returnData) {
var jsondata = returnData;
console.log(jsondata);
jsonupdateregion(jsondata);
}, 'json);
it should output an object or just a string.... eventually your php echoes some new lines or other craty things before or after the answer.
What about the charset? Is your server maybe answering in iso-something? Then js would fail decoding your jsonstring if there are some crazy chars (ü, ß, ç)
Last thing
$jsonarray = array();
while($rs = mysqli_fetch_assoc($result)) {
$jsonarray[] = $rs; //add an element.. do not overwrite it
}
echo json_encode($jsonarray);
I have a JQuery AJAX request send off some JSON data to a PHP script, however, when it comes to manipulating the data or even trying to access it, it behaves like a string but I need it to behave like an associative array.
JavaScript
var all_data = [];
$.each($("[id*=card]"), function(i, value) {
var name_a = $(value).find('#story_name_div').text();
var text_a = $(value).find('#story_text_div').text();
var point_a = $(value).find('#story_point_div').text();
var phase_a = $(value).find('#story_phase').val();
var date_a = $(value).find('#story_date').val();
var author_a = $(value).find('#username_div').text();
var story_data = {
"name": name_a ,
"text": text_a ,
"point": point_a ,
"data": phase_a ,
"date": date_a ,
"author": author_a
};
all_data.push(story_data);
});
$.ajax({
url: 'save_server_script.php',
type: 'POST',
processData:false,
dataType: "json",
data: "json=" + JSON.stringify(all_data),
success: function(res){
var json_a = $.parseJSON(res);
console.log(json_a);
},
error: function(err){
console.log("error");
}
});
JSON that is created
[json] => [{"name":"jhb","text":"gjh","point":"jhv","phase":"planning","date":"21/9/2013 - 4:23:16","author":"Created by - ljhlkjhb"}]
PHP
print_r($_POST); // prints out entire JSON
print($_POST["json"][0]["story_name"]);
// Warning : Illegal string offset 'story_name' in C:\xampp\htdocs\save_server_script.php on line 15
print($_POST["json"][0]); // prints out a '['
foreach($_POST["json"] as $hello) { // invalid argument supplied for foreach
print $hello["story_name"];
}
I have also tried decoding via PHP but to no avail.
Try
$json = json_decode($_POST['json']);
echo $json[0]->author;
In your snippet you're referring to story_name, but that's not an element in your JSON string.
You have to decode the json into array in php first:
$arr = json_decode($_POST["json"]);
//now you can use foreach on the array it returned
foreach($arr as $key => $value){
//now you can use $value["text"] , $value["author"] etc
}
The data received by php is in json format that needed to be converted into array format in order to use foreach on it.
PS There is not "story_name" in your json data.
I'm trying to retrieve data in a javascript file from a php file using json.
$items = array();
while($r = mysql_fetch_array($result)) {
$rows = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
array_push($items, array("item" => $rows));
}
ECHO json_encode($items);
and in the javascript file I try to recover the data using an ajax call:
$.ajax({
type:"POST",
url:"Locali.php",
success:function(data){
alert("1");
//var obj = jQuery.parseJSON(idata);
var json = JSON.parse(data);
alert("2");
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
The first alert is printed, the latter does not, it gives me error: Unexpected token <.... but I do not understand what it is.
Anyone have any idea where am I wrong?
I also tried to recover the data with jquery but with no positive results.
This should do it.
$.post("Locali.php",{
// any parameters you want to pass
},function(d){
alert("1");
for (var i=0; i<d.length; i++) {
point = new google.maps.LatLng(d[i].item.latitudine,d[i].item.longitudine);
alert(point);
}
}, 'json');
the PHP is fine if it is giving the response you mentioned above.
I think u should look more for the data you are getting from the php file. Definitely this is a parse error and must be missing some bracket/something else, ultimately not making the data returned to be a json parseable string.
You should be Ok with this slight modifications:
$items = array();
while($r = mysql_fetch_array($result)) {
$items[] = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
}
echo json_encode($items);
And the jQuery:
$.ajax({
type:"POST",
dataType: 'json',
url:"Locali.php",
success:function(data){
console.log(data);
for (var i=0; i<data.length; i++) {
point = new google.maps.LatLng(data[i].item.latitudine,data[i].item.longitudine);
alert(point);
}
}
})
data $.ajax({
type:"POST",
dataType: json,
url:"Locali.php",
success:function(data){
for (i in data) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
Try it like that.
yeah just try
for (var i=0; i<json[0].length; i++) {
cause you have an object there..
i've got a simple ajax call:
function message(){
$.ajax({
type: "GET",
url: "/file/timestamp="+ timestamp,
async: true,
cache: false,
success: function(data){
var json = eval('('+data+')');
console.log(json);
}
});
}
and i get an error Uncaught SyntaxError: Unexpected token < at this line: var json = eval('('+data+')');
any ideas?
thanks.
edit:
some more details from the error:
$.ajax.successajax.js:9
f.Callbacks.njquery.js:2
f.Callbacks.o.fireWithjquery.js:2
wjquery.js:4
f.support.ajax.f.ajaxTransport.send.d
here is some php if is helping
public function fileAction()
{
$this->getHelper('viewRenderer')->setNoRender();
$filename = '/test/text.txt';
$front = Zend_Controller_Front::getInstance();
$data = $front->getRequest()->getParams();
$lastModif = !empty($data['timestamp']) ? $data['timestamp'] : 0;
$currentModif = filemtime($filename);
while($currentModif <= $lastModif){
usleep(10000);
clearstatcache();
$currentModif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentModif;
echo json_encode($response);
}
if i run this action i get json: {"msg":"message","timestamp":1331599879} but for some reason the response is not this but some html
It depends on what's inside data. You're running eval, so whatever's in data is being run. Please post the data here,.
What are you expecting to be returned in as data? Running eval will try to execute (data) which doesn't seem like it will be proper javascript. If you just want to store a string you can do:
var json = "(" + data + ")";
jholloman almost had it...
var json = eval("(" + data.responseText + ")");