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

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

Related

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;

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"

Filter out JSON for only columns I need using jQuery/javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm using this to parse out the JSON coming from PHP (age_get.php) and it's working great.
$.getJSON('age_get.php', function(data) {
var ticks1=[]
$.each(data, function(key, val) {
ticks1.push("["+val.index+",'"+val.value+"']");
});
var ticks6 =[(ticks1.join())]
The output is this, which as I said is fine.
["[90,'18-24'],[91,'25-29'],[92,'30-34'],[93,'35-39'…'60-64'],[99,'65-69'],[100,'70-74'],[101,'75-99']"]
In my PHP file, the mySQL query part is this:
$sql = "select * from advanced_data where category like 'age range'";
So, basically, I have the PHP already "filtering" the JSON from a much larger table (i.e., with many more columns).
There has to be a better way than creating individual PHP files for each time I need something out of this database, but I'm pretty new to this.
So, the question is, can I have a single PHP file with a query more like this:
$sql = "select * from advanced_data;
And then in my HTML file/jQuery have something that essentially filters out the JSON for what I need similar to how "where category like 'age range'" works in my PHP file.
Hope that's clear. Any thoughts would be appreciated.
Yes you can do that technically, but it is not a good idea. When using ajax, it is good to keep the data small.
Instead of get everything from php and search it with js loop, you can improve your php script to let it accept queries.
In your php:
<?php
$whereCategory = isset($_GET['category'])? "where category like '{$_GET['category']}'" : '';
$sql = "select * from advanced_data {$whereCategory};";
...
In your ajax:
$.getJSON('age_get.php?category=testCategory', function(data) {
...
});

PHP calling with Jquery [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 a jquery file in which i have the following code:
var QUESTIONS = ["Q11", "Q22", "Q33", "Q44", "Q55"];
var ANSWERS = [["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"], ["Si", "No"]];
Now i want to load the questions and answers from the PHP.
Trolling ahead!
If you want to load javascript into the PHP Userspace, you will need to lex and parse it, then read it into your own PHP userspace.
Create a javascript lexer to read the content of the file
From the token list, create a parser that will validate and construct and complex expression tree
Then you can analyse the expression tree and extract the different values into model classes you will have created.
Or, you could simply, just copy the content over to PHP and use it normally!
You have three choices here.
Inline PHP
In the .PHP file that generates your web-page, directly write the text for your JavaScript arrays as if they were HTML or plain-text.
AJAX
Use an XMLHttpRequest object to call a separate a .PHP page that returns an XML response containing your entries. (You could also have it return JSON instead of XML.)
JSON-P
Have your PHP return JSON to a <script> tag, which gets automatically parsed and executed on the client. (usually as a single global variable.)
dataServer.php
$response = array();
$response['questions'] = array("Q11", "Q22", "Q33", "Q44", "Q55");
$response['answers'] = array(array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"), array("Si", "No"));
print json_encode($response);
dataClient.js
$.ajax({
url: "dataServer.php",
dataType: "json",
type: "GET",
success: function(data, stat, xhr) {
alert(data.questions.toSource());
alert(data.answers.toSource());
}
});

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