PHP calling with Jquery [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 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());
}
});

Related

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

Best way to store data on page for Ajax requests [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a page been generated that comes with an array of data generated by php. I need to use some of this data for an ajax request.
I just wondered what the best way is to store the data on the page, it's not sensitive and the page doesn't involve a form. At the moment I've been using data- attributes in a hidden div but just seems a bit messey?
eg.
<div id="data" class="hidden" data-question="<?= $blah ?>" data-another="<?= $blahblah ?>"></div>
Although there is no "best" way, I would recommend JSON -- a format for storing and exchanging data, and would seem to fit your situation well.
Instead of storing arbitrary data in data-attributes on an html element, like this:
<div data-name="bob" data-age="27" data-gender="male" />
Json allows you to store them like this:
people = {
"bob" : {"age":"27", "gender":"male"},
"alice" {"age":"31", "gender":"female"}
}
You can access this data programatically through native or library calls in almost any language, especially PHP and JavaScript.
In JavaScript, JSON is accessed like this:
BobsAge = people['bob'].age;
This format allows for other programmatic access, such as looping over objects or keys, that may be difficult to perform on data-attributes of html elements.
In your case, JSON could be generated like so (although there are better ways):
<script>
var data = {
<? foreach ($data as $d){ ?>
{
"question" : "<? $d['question'] ?>",
"answer" : "<? $d['answer'] ?>"
},
<?}?>
};
</script>
There are three possibilities:
attributes: this is your approach
This is probably best for simple strings, e.g. parameters, and data that is descriptive - e.g data-popover for an element which contains popover contents. Many JS plugins are built that way.
PHP echo in <script> tag
No "additional markup" for the cost of having <script> tag in the same file (and, probably, the use of global JS variables). I wouldn't recommend that.
additional AJAX call fetching JSON with data from PHP
Best for more complicated data structures, such as nested arrays or objects.

PHP alternative of Javascript's pop() method [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
Is there any PHP method to do:
var filename = $_POST["filename"];
filename = filename.split(".").pop();
How can I do the same above thing in PHP?
Something like this, perhaps?
$filetype = array_pop(explode('.',$filename));
It will generate an Only variables should be passed by reference notice. If you want to get rid of that, you'd need:
$fileparts = explode('.',$filename);
$filetype = array_pop($fileparts);
However, the best way to get a file's extension is by using pathinfo():
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
You can do unset($filename[count($filename) - 1]);. Which will remove the last element in the array.
You'd want to do this:
$filename = $_POST['filename'];
$file_arr = explode(".",$filename); // may need to escape '.' here, can't remember
$filename = array_pop($file_arr);
In PHP, you probably don't need to convert to an array and pop; get the position of the last character, then get the rest of the string. From http://davidwalsh.name/php-file-extension:
substr(strrchr($file_name,'.'),1);

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