transmitting "[]" string to php driven backend [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 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;

Related

Why JSON.stringify() don't work correctly [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 1 year ago.
Improve this question
I'm actually creating a JSON file with nodejs but when i use the JSON.stringify.
My Json Object work correctly when i print it :
My code
But when i stringify my json object i get that :
What i receive when i print my json object
A big part of my json information don't want to be save i don't know why
Here's the code :
What i receive when i print my stringified json object
You are attempting to use a 'sparse array' to store your data. Arrays do not have a clear way to be instantiated with elements at a specified index.
An object (or a Map) would suit your requirements better. To use an object, I modified your 'accounts' initation code that was commented:
// replace this:
dataObj["accounts"] = [];
// with this:
dataObj["accounts"] = {};
The other code you are using (e.g. accessing elements using the square brackets) will work the same. You should probably make the same adjustments to the other arrays you are using.
Sparse arrays can get ugly in some notations if you have large blank spaces (which your UUID methodology would certainly have). An object or a Map will not suffer that shortcoming.
An example of similar code, using objects instead of arrays:
let dataObj = {};
dataObj["accounts"] = {};
let uuid = 'abcdefghij12344';
dataObj["accounts"][uuid] = {}
dataObj["accounts"][uuid]['active'] = true;
dataObj["accounts"][uuid]['someotherval'] = true;
console.log(dataObj);
//outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }
let stringified = JSON.stringify(dataObj);
console.log(stringified);
// Outputs:
{"accounts":{"abcdefghij12344":{"active":true,"someotherval":true}}}
let parsed = JSON.parse(stringified);
console.log(parsed);
//Outputs:
{ accounts: { abcdefghij12344: { active: true, someotherval: true } } }

I want to seperate the PHP JSON string in 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 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"

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 */
})

save array values on reload and retrieve it back [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 am pushing some random values into an array every minute.
On reloading I want to retrieve back this pushed content and keep pushing some random data every minute?
I am using local storage.
MyCODE--:
localStorage.setItem("test",Myarray.push(JSON.stringify(data)));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2); //var test is now re-loaded!
console.log(test);
This is not working.
Push the data to the array, then store it in the localStorage as JSON:
// Set
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));
Parse the JSON when you get the data back out (put this at the top of your script, or in your onload method):
// Get
if (localStorage.getItem("test")) {
Myarray = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
Myarray = [];
}
console.log(Myarray);
Local Storage works with strings only. Also, push returns the new length of the array, so the code you posted wont work as intended. Try this:
Myarray.push(data);
localStorage.setItem("test", JSON.stringify(Myarray));
The problem is you're storing the return value from .push() to local storage (which is the length of the array), instead of the actual data.
You should push to the array as required, then stringify the array and store.
var Myarray = [];
Myarray.push(....);
localStorage.setItem("test", JSON.stringify(Myarray);

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