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);
Related
I am trying to get the string "Name n" out of the php array $F[], which is randomised inside the function DataInit1(), and put it in a div inside my html file. However, the PHP file cannot be changed because the arrays are randomised and used to plot a series of graphs.
PHP file:
<?php
$Return = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return[] = $P[$i];
$Return[] = $S[$i];
$Return[] = $F[$i];
}
die(json_encode($Return));
?>
HTML file:
<div id="GRAPH">
<div id="title"><h1 id='graphtitle'></h1></div>
<h1 id='GraphNum'></h1>
<div id="chart"></div>
<h1 id='PointNum'></h1>
</div>
The string should be placed in the "ARRAY $F" as shown below in the JS file:
function DataInit1()
{
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(Data1)
{
SeriesList = [];
CurrentGraph.Series = 0;
for(var i=0; i<Data1.length; i+=3)
{
var P = Data1[i+0];
var S = Data1[i+1];
var F = Data1[i+2];
var NewSeries = new SeriesClass(P,S,F);
NewSeries.SeriesNumber = (i/3)+1;
SeriesList.push(NewSeries);
}
}
);
for(var i=SeriesList.length-1; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
}
........
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = ARRAY $F;
});
$("#graphtitle").html(name);
}
Any other idea or suggestion on this issue will be very welcome. Thank you.
UPDATE:
Based on the suggestion by ironpilot. Could the solution be something like this?:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("CurrentGraph.Series",
function(data)
{
var titleGraph = (json_decode($F, true));
var name = data.titleGraph[0];
$("#graphtitle").html(name);
});
}
You have a few issues in your code that you would need to correct before this is possible. First let's look at your PHP code. It appears that you want to create a few parallel arrays and then return them to your front-end code. However, the way that you add each array into the $Return array makes predicting where the elements are nearly impossible.
Let's start by converting the $Return variable to an object of stdClass. This will allow you to specify arbitrary properties on the object and make them accessible via a JavaScript object.
<?php
$Return = new stdClass();
$Return->P = array();
$Return->S = array();
$Return->F = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return->P = $P[$i];
$Return->S = $S[$i];
$Return->F = $F[$i];
}
die(json_encode($Return));
?>
Now that we have a little more predictable object to work with we can correct the jQuery code:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = data.F[0]; //Select the first element of the $F array.
$("#graphtitle").html(name);
});
}
Now that we have an object that is returned from PHP you can access the array of names specifically to get the value that you need with var name = data.F[0];. Additional since this variable was declared with the var keyword inside the success function it's value would not be accessible outside of that function where it was set.
We also needed to move your selector for #graphtitle inside the jQuery success method. Since this method is actually a promise and doesn't execute until the AJAX request completes, what would have happened is that the function to set the html content of the element you were selecting would have executed before you received a response from the server with the content to place. This is called a Race Condition: https://en.wikipedia.org/wiki/Race_condition.
I hope that helps!
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
};
I am having an issue displaying json data. I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" comes back as undefined.
Why is object undefined? From everything I can see I am doing it right.
My json that is returned.
{
"data":[
{
"NumberOfAnswers":25,
"Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":54.35
},
{
"NumberOfAnswers":21,
"Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":45.65
}
]
}
And here is the function to display it. (With some debugging code as well)
function format(notes) {
console.log(notes); //this displays the json
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
Here is the ajax function:
$.ajax({
type: 'post',
url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
success: function(result) {
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
detailsrows.splice(RowID, 1);
} else {
row.child(format(result)).show();
tr.addClass('shown');
if (RowID === -1) {
detailsrows.push(tr.attr('id'));
}
}
}
});
Most likely, the response is still in string format. You can add JSON.parse to convert it to an object and then be able too access the data property.
Try modifying your function like this to see if it fixes the problem.
function format(notes) {
console.log(notes); //this displays the json
// The following converts the response to a javascript object
// and catches the exception if the response is not valid JSON
try {
notes = JSON.parse(notes);
} catch(e) {
console.log('notes is not valid JSON: ' + e);
}
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .
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..