I'm having an issue returning a value from PHP to Javascript. I have encoded the PHP array like so :
echo json_encode($myArray);
And on the Javascript side i do this within the $.ajax method:
success:function (data) {
alert(data);
}
This works and it alerts the returned array, however when i try to then set my Javascript array to the value of data :
success:function (data) {
myArray = data;
}
This completely breaks my looping operation and so instead of printing out for example:
This is a test
It will print:
t,h,i,s,i,s,a,t,e,s,t
and the length of the array rather than being 4, for 4 words it is 16+ including the square brackets etc. How can i reuse the json encoded array once it has been recieved by javascript and maintain its structure?
Related: Parse JSON in JavaScript?
What you are looking for:
myArray = JSON.parse(data);
Related
I'm writing a simple delete function. This function deletes entries in a list that is being outputted by PHP. This is what happens:
The javascript selects the checked boxes in this list and gets its ID 1,2,3etc.
The created array is converted to JSON using JSON.stringify
PHP gets the POST and decodes it using json_decode() (this fails)
$(document).ready(function(){
$('.action_trash').on('click', function(){
//Select items to trash
var TrashItems = [];
$('input:checked').each(function() {
TrashItems.push($(this).attr("id"));
});
//Convert to JSON
var TrashJSON = JSON.stringify(TrashItems);
alert (TrashJSON);
$.ajax({
type: "POST",
url: "pages/forms_intake/actions/trash/model_trash.php",
data: {TrashItems:TrashItems},
cache: false,
success: function(){
// do stuff to remove trashed elements from list.
}
});
});
});
I'm trying to convert the simple Javascript array to JSON. But I think the JSON is invalid. When I alert the TrashJSON variable, this is the output: ["31","32"]
<?php
session_start();
include "../../../../php/config.php";
$TrashJSON = $_POST['TrashItems'];
var_dump(json_decode($TrashJSON));
//Trash items
//$TrashQuery = mysqli_query ($mysqli, "UPDATE forms_intake SET item_trashed=1 WHERE formid='$TrashInt'");
//Close connection
mysqli_close($mysqli);
?>
When I run this, I'm getting this error:
<br />
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in <b>/home/nickvmf103/domains/a-training.nl/public_html/sotwebapp/pages/forms_intake/actions/trash/model_trash.php</b> on line <b>7</b><br />
NULL
According to the PHP manual on json_decode, null gets outputted if the JSON is invalid.
So my question is: How to correctly format the JSON in my javascript? So that it can be passed to PHP and converted to a PHP array.
Additional info:
When successfully converted to PHP array, I will use implode to put " OR " between the array values, convert it to a string and use it in my SQL query WHERE statement to trash the items that were checked on my page.
In order for the existing PHP to function how you expect, you need to send TrashJSON instead of TrashItems. TrashItems is the array you've populated, while TrashJson is the JSON encoded version of TrashItems.
Change
data: {TrashItems:TrashItems},
to..
data: {TrashItems:TrashJSON},
jQuery is correctly interpreting TrashItems as an array, and thus sending it as an array of values to the PHP script.
Alternatively, as Barmar has inferred in the comments, you could simply loop over the values array currently posted as TrashItems. You could do this using the following code.
foreach ($_POST['TrashItems'] as $TrashItem) {
echo "$TrashItem\n";
}
This would output each item of the TrashItems array you originally passed in on a separate line, and provide the output of..
31
32
I am passing an array from php to javascript but it seems to be picking up a extra " at the start and finish of the array.
My array being sent from the PHP file
json_encode($CheckItems."|".$CheckUserItems."|".$CheckUserMessages."|".$CheckCommentsForproducts."|".$CheckComments);
My File reciving the array.
url: 'CheckServer.php',
success: function(data) {
var DataBaseCheck = (data)
DataBaseCheck = data.split("|");
console.info(DataBaseCheck);
Console.info prints ""0","1","2","3""
When checking if Database[0] matches with anther variable it fails due to the extra " when i console log each array i get "0,1,2,3"
How can i solve this i have tried
DataBaseCheck.replace('""','"')
DataBaseCheck.replace('"','')
Array1 = parseInt(DataBaseCheck[0])
I cannot think of any other way to remove them ??
The "extra double quotes" are there because you have a JSON encoded string. You are getting JSON from your PHP code, so in your JavaScript the first step should be to decode it:
function(data) {
data = JSON.parse(data);
data = data.split("|");
# data is now an array of strings, e.g. ["0", "1", "2", "3"]
}
Really though, if you are trying to pass an array of integers from your PHP code to your JavaScript code, rather than using your own delimiter you are better off just creating an array in PHP and JSON encoding that, then your JavaScript would just be JSON decoding and you would have the correct data.
How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);
is there anyway to import a javaScript array from a PHP return value?
Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.
$.get(makeArray.php, function(data){
var responseArray = new Array(data);
alert(responseArray[1]);
...
However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.
Thanks!
You can use JSON.
In PHP
$myarray = array('first','second','third');
return json_encode($myarray);
In JavaScript:
$.get(makeArray.php, function(data){
console.log(data[1]); //=> "second"
}, 'json');
Edit
If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:
PHP:
echo join('%',$myarray);
JS:
var array = data.split('%');
Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.
What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.
I'm trying to figure out on how to access data in JSON format and have gone a whole day searching for ways but I still can't find a solution to fit my needs. The closest relative question to my problem is this question but to no avail.
Basically I am retrieving data from $.ajax() which returns in JSON format.
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
My problem is how can I access the elements inside the JSON, say I want to get all values of "nv" or all values of "date" on the second bracket, in javascript? I Am new at things like these so am not familiar with the terminologies, sorry for that.
Below is my code:
var Data = $.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false
}).responseText;
console.log(Data);
url is a variable that is passed inside my function in case you might ask.
Update: See Anthony Grist's comment on your question, I missed the fact that your JSON is invalid. Since he hasn't posted an answer, I'll pick it up.
Your JSON is invalid because you're returning two separate arrays, this one:
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}]
and this one:
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}]
You can't do that, because the top level of a JSON document must be one thing (an object or an array).
You could return an object with properties for each array:
{
"vdata":
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
"datedata":
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
}
After parsing (see below), you can access that data like this:
console.log(data.vdata[0].v); // "233"
console.log(data.datedata[0].date); // "2013-02-01"
Or an array with two slots, with each slot having one of your arrays in it:
[
[{"v":"233","pv":"1.83","avd":"00:01:58","nv":"82.83%","br":"75.11%"},
{"v":"17","pv":"3.65","avd":"00:08:31","nv":"70.59%","br":"58.82%"},
{"v":"9","pv":"2.22","avd":"00:01:51","nv":"0.00%","br":"44.44%"}
],
[{"date":"2013-02-01","visits":63},
{"date":"2013-02-02","visits":30}
]
]
After parsing (see below), you can access that data like this:
console.log(data[0][0].v); // "233"
console.log(data[1][0].date); // "2013-02-01"
Personally, I prefer using an object, since then it's clear which array I'm accessing.
Original answer:
jQuery will parse the JSON into an object for you and pass that to the success function, which you can then access just like any other object. In your case, the top level is an array. So:
$.ajax({
url: url,
type: 'POST',
dataType:"json",
async: false,
success: function(data) {
// Use the line from above that suits the way
// you updated your JSON structure
}
});
Side note: async: false is deprecated and will be removed at some point. It's generally not a good idea to do synchronous ajax requests, it tends to lock up the UI of the browser during the request. Instead, just structure your code to continue processing when the success callback is triggered.
If I understand your problem you need to access the same key for all objects in this array.
There is no direct method to do that, you have to iterate through all objects in this array and then find the desired key in each of those objects.
JSON.parse() will convert this string into a Javascript Object (JSON)
var myData = JSON.parse(Data);
for(var i = 0; i < myData.length; i++) {
console.log("This is the nv value of the " + i + " object: " + myData[i].nv);
}