I want to seperate the PHP JSON string in jQuery [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a problem with separating the json array result. When I alert the json result in jquery it returns me the following array.
{"productid":"17","product_quantity":"2"}{"productid":"9","product_quantity":"1"}
Now I want to separate every value in a different variable.
Thanx in advance.

that is not a valid json string.
first, you can convert the input to json string.
then, you can use JSON.parse to get the js array.
e.g.
first you need to do this:
input = '[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]'
then:
input_array = JSON.parse(input)

It might be that your server returns a string that is not valid JSON. A valid example would be:
[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]
How are you creating the json? Since you tagged PHP, the correct way (if you have an array) is like this, and it will return valid JSON, that you JS can handle:
echo json_encode($array);

The json you gave is misformed. I assume that's a typo.
Use JSON.parse to convert to a javascript object.
var jsonString = [{"productid":"17","product_quantity":"2"}, {"productid":"9","product_quantity":"1"}];
var data = JSON.parse(jsonString);
console.log(data[1].productid); // 9
But I do not know what you mean by."Now I want to separate every value in different variable."
Why?
Anyways you could do this. Though I do say dont. But you asked.
data.forEach(function(item){
window["productid"+item.productid] = item.product_quantity;
});
will give you 2 vars in global scope
console.log(productid17); // "2"
console.log(productid9); // "1"

Related

value extraction from array in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
business=[0:{"name":{"en":'prateek'}},1:{"name":{"ar":'rahul'}}]
How I can extract the value of en and ar from this type of the repeted object in a array
The issue with your question is that you define business as an Array with the use of square brackets, but then proceed to use key value pairs directly within the array (via the usage ":"), which is reserved for objects and not arrays. I'd recommend researching both array and object datatypes, however simply put:
let myArray = [1, 2, 3, ...];
// only stores values which can be retrieved using the values index i.e. myArray[0]
let myObj = {"key1" : "value1", "key2" : "value2"};
// values are stored against keys, and can be accessed via the key i.e. myObj.key1
I think you've confused how objects and arrays should work. My guess is that you'd be better off with this structure:
let businesses = [];
businesses.push({enName: 'prateek', arName: 'rahul'});
console.log(businesses[0], businesses[0].enName, businesses[0].arName);
This way you're using an array to hold a collection of businesses and which are represented by objects. These objects in turn have attributes for enName and arName.
I think this would be a much clearer way of structuring your issue.

transmitting "[]" string to php driven backend [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So theres a function which calls to backend which fetches all reservations in a certain timeframe and returns them to front-end. If there are no reservations in the respective timeframe, backend returns the string "[]". This data is then transmitted to backend again where I evaluate whether reservations exist or not.
For this, I want to use the php function "empty()" in backend.
And the code there basically just looks like this
$allReservationsOrRequestsByUser = json_decode($allReservationsOrRequestsByUser);
if(empty($allReservationsOrRequestsByUser)){
$overlapExists = false;
}else{
$overlapExists =
checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;
Now, I tried the above code both with and without decoding it before the if-condition. In both cases, "empty()" function always returns false, which shouldn't be the case when the array actually was empty.
What am I doing wrong?
you are trying to check if "[]" as empty. So it isn't empty as a string... You can convert it to a proper array before checking with empty() like...
$a = "[]";
var_dump(empty($a));
var_dump(empty(json_decode($a)));
that returns,
bool(false) <- Without Json decode
bool(true) <- With Json decode
You need to check array data in array or object
e.g if fetched array contain
if(empty($allReservationsOrRequestsByUser[0]['name'])){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
if object then use this and name is your database table column name
if(empty($allReservationsOrRequestsByUser[0]->name)){
$overlapExists = false;
}else{
$overlapExists = checkForOverlapWithExistingRequestsOrReservations($todayDate,
$allReservationsOrRequestsByUser);
}
echo $overlapExists;

iterate over formatted JSON Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am querying an MS SQL Database, which is returning a formatted JSON Array. Below is an example of what is returned. I have used just about every JavaScript example I can find to iterate over the array, but nothing is working:
[
[
{"id":1,"Title":"Friday"},
{"id":2,"Title":"Saturday"},
{"id":3,"Title":"Sunday"}
]
]
There are two issues with your json array there that will need to be solved first
You have a " missing on Sunday
You have an array of arrays, not just an array.
When your array is correct the return from your SQL should look like this:
'[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]'
That isn't a json object yet, it's just a string that looks like one, to make use of that as a json object/array you need to parse it like this:
var jsonArray = JSON.parse('[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]');
If you can't get around the [[]] array within an array, you can handle it like this:
var jsonOuterArray = JSON.parse('[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]]');
var jsonArray = jsonOuterArray[0];
With that there are many ways to iterate over it in javascript, it all depends what libraries you use and what you want to get out of it, like how the jQuery example give not only the object but the position in the array for that object but the forEach will not.
For each example, jsonArray will be the parsed out json from your SQL, key will be the position in the array and value will be the object in the array.
JavaScript: (array prototype forEach)
jsonArray.forEach(function(value){
console.log(value.id, value.Title)
});
JavaScript: (for loop)
for (var key = 0; key < jsonArray.length; key++) {
var value = jsonArray[key];
console.log(value.id, value.Title)
};
jQuery:
$.each(jsonArray, function (key, value){
console.log(value.id, value.Title)
});
Using nodejs (ES5 syntax) :
> [[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]][0]
.forEach(function(elt){ console.log(elt.id, elt.Title)})
1 'Friday'
2 'Saturday'
3 'Sunday'
Note that a quote is missing before Sunday:
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":Sunday"}]]
therefore you will not be able to evaluate this JSON. Assuming that the JSON is corrected to
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]]
you will be able to iterate it in conventional manners, using a for cycle, for example.

pull a table from SQL to create javascript array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have data like this in a SQL table:
ID | Word | Count
1 word1 10
2 word2 5
I'd like to request this data from javascript (or an aJax call I guess?) and have it create an array. I also don't care about the ID#, but just the word and it's 'count.' Then I guess it would be a 2d array to store this info? Ie, word[0][0] would return "word1" and word[0][1] would return 10. Maybe there's a better way to do that last part, though. And then I'd like to sort these by count.
Thoughts?
EDIT:
It would seem as though I have the data getting piped back via PHP to JSON. However, how the heck do I get the data out of JSON and into a JS array?
$.getJSON('php_file.php', function(response) {
// response is a JSON object that contains all the info from de sql query
/* do your JS stuff here */
})
It's saying that response is false, and no more. What's the deal?
Have a look at PHP's json_encode in the manual. It will allow you to convert a PHP array (which you'll populate from a database query) to a JSON object, which you will then output to the Ajax call from your Javascript.
Process:
Javascript calls e.g. results.php
results.php calls database and gets array
results.php uses json_encode on said array and outputs it to the browser (echo)
Javascript receives nice JSON array to use.
There's a nice example here:
https://stackoverflow.com/a/383664/2812842
The PHP file should look like this:
PHP_FILE.PHP
$sql = "SELECT * FROM table ORDER BY count [ASC|DESC]";
$result = execute_query($sql);
while($array = mysql_fetch_assoc($result));
echo json_encode($array);
And, then you have to make the AJAX call (for example, using JQuery)
$.getJSON('php_file.php', function(response) {
// response is a JSON object that contains all the info from de sql query
/* do your JS stuff here */
})

how to manipulate json objects in javascripts/jquery? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wanted to add delete update elements in json using jquery/javascript and when the file submit is done to the server wanted to consider the latest json object.
Can you suggest and approach i am stuck.
I use JSON.parse and JSON.stringify to manipulate.
json_flat = '{"page":"1","total":"2","ids":[{"id":"3085"},{"id":"3086"}]}'; // your flat json
json_object = JSON.parse(json_flat); //convert to an object
//Manipulation
json_object.page = "6"; //change values
delete json_object.total; //delete a value
json_flat = JSON.stringify(json_object); //convert back to flat
EDIT: Fixed some typos: JSFiddle
As mentioned, you can use jQuery's json functions to edit the object. Let me demonstrate how you might do this, with a little code:
let's take this JSON object:
{
"people":[
{"name":"Bob","score":9},
{"name":"Joe","score":6},
{"name":"Tom","score":7}
],
"projects":[
{"id":2347,"entries":5},
{"id":8563,"entries":3}
],
"lastUser":"Bob"
}
Now, let's say your server is storing that as a flat JSON file somewhere...what we'd do is load it on the client with jQuery's ajax methods, and edit it using a callback. After manipulating the object, we'll (for demonstration purposes) immediately send it back to a server-side script, which will presumably overwrite the current flat file:
$.getJSON(/*path to JSON file here*/,function(response){
response.lastUser="Tom"; //This is where the sample manipulation occurs.
$.post(/* path to server-side script*/,response,function(){
alert("Object Saved");
});
});
Hope that helps in understanding the pattern involved!
JSON data can be directly manipulated in javascript after parsing. (See Brad's comment on your question). To send the updated data back to server you can use $.post. Now, doesn't this solve your problem? If not, then please explain your problem in more detail.

Categories

Resources