Pass javascript variable to PHP array using AJAX - javascript

I have a variable named var abc=5 and I want to pass that variable via AJAX so each time AJAX runs it I want to store that variable's value in a PHP array variable. Something like this:
$abc=$_request['abc'];
$xyz=array();
array_push($xyz,$abc);
when AJAX runs then I want output something like this:
$xyz[0]=1;
$xyz[1]=2;
.
.
.
.
$xyz[9]=10;
So I can use that array in JPGraph?

Instead of thinking about passing javascript "variables", think about passing modulus data that can be interpreted by Javascript and stored into whatever variables the client side script cares to use.
One easy and popular way to pass data between client and server is to use JSON. The JSON can be created on the PHP side and then sent to the client in response to the request which passes each individual number via Ajax.
It's easy enough to pass numeric data as delimited values, but when you start wanting to pass back and forth more complex data structures, JSON makes the most sense - it closely mirrors the basic data structures of Javascript as well as most modern languages: key/value pairs, arrays (lists of data), true, false, null, modulus strings and numbers.
Your JSON response payload might look like:
"[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]"
You can easily parse it in Javascript like so:
var data = JSON.parse( ajax_response )
See the Fiddle for a mock-up

Don't use multiple AJAX-requests. Just use 1 after you're done. Build the array you want to use in PHP in JSON format.
var string_to_send_with_ajax = JSON.stringify(['1','4','8']);
in php you can then use this in your PHP:
$array = JSON_decode($_POST['string_to_send_with_ajax']);
If you are positive you want to save the variables on the server with PHP, You define an array the first time. Make it a session variable so it will be on the server as long as the browser isn't closed by the user.
$_SESSION['plotArray'] = array();
use array_push to add a value to the array:
array_push( $_SESSION['plotArray'],$_POST['string_to_send_with_ajax']);

Related

send array of Javascript constructors from PHP to Javascript

I am trying to send an array back to Javascript from PHP. I'm using Ajax to do this. I know how to send arrays to Javascript, but this time I'm trying to send an array that contains some Javascript constructors. For example I want to be able to send this: [new Date(2017,06,03), 25, 33] Is there a way to send this array to Javascript? If so, how will Javascript be able to use this array in a way where a new Date is created in the first index of the array?
Can not you just simply send value of new Date() instead of constructor? Will be more effective i assume.
Short answer: No, there is no direct way.
Long answer: When you say that you send arrays to Javascript from PHP, you need to understand that PHP is a server side language, and Javascript is what runs in the browser.
So, in between them, u have the network layer and all the things that transfers on that layer should be serializable, usually means strings.
So the data that you pass to the browser via Ajax usually is JSON.
It can contain only primitive values, like: string, number, boolean, null.
new Date(2017,06,03) is an javascript object, that is not part of JSON spec.
You can serialize the Date with some PHP func like date, send it via Ajax, and then deserialize it on Javascript world.
Something like that:
<?php
/* your Ajax return */
echo json_encode(array(date('c', mktime(0, 0, 0, 7, 1, 2000)), 25, 33)); // will return ["2000-07-01T00:00:00-07:00",25,33]
?>
Then on the JavaScript part u can parse it with Date constructor.
// Javascript
const response = ...
const myData = new Data(response[0]); // Will be Date obj.

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

Passing JavaScript array to input in PHP

I'm trying to pass an array from JavaScript to a PHP input. I want to pass my array as an array inside my input, not a string.
My array is this:
["0_1","0_2"]
And this is how I pass my array to my input:
$('#movefile_id').val(JSON.stringify(allfiledata));
Can I pass the array to the input file without making it a string?
read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
you can convert your array to JSON
var arrayJavascript = JSON.stringify(["0_1","0_2"]);
and with PHP, read this:
http://php.net/manual/es/function.json-decode.php
$arrayPHP = json_decode($_POST["arrayJavascript"]);
Here is the step by step process given below
1- Covert the Javascript Array to JSON
2- Post that JSON string to PHP using jquery post or jquery get
This is possible through only using Ajax. Because javscript is a Client side language and PHP is a server side language.We can only connect both using Ajax.

How to create JSon object and store data in it

I am trying to consume data from an API using REST call . I've succeeded to get data from the API .
I am having different rest call , I created different function for everyone .
I would like to know if I can store these data using JSon
it works perfect and gets all the Rest call but I would like to store them in JSon objects data to get it as a result in order to show it .
What I have done .
- I created a new object called Json
- I looped to consume data using REST call .
- but whenever I got this data , I have problems to store them .
var jsonObj = []; //declare object
$.each(data.results, function(i,item){ // on this line
jsonObj.push({id:item.conceptUuid ,
MedicalImage: item.dataURI ,
title: item.title ,
description: item.description ,
});
$htmlstring.append($('<li/>').append($('<img/>').attr('src',jsonObj.MedicalImage) ));
$htmlstring.append("<div class='title'> title: " + jsonObj.title
+ "<br> description : "+ jsonObj.description +
"</div>")
});
$('#result').html($htmlstring);
The function should take a query string as an argument, and the server returns data as JSON.
Can you show me an example how to do this using jQuery Storing data in JSON object to avoid multiple calls ?
JSON stands for "JavaScript Object Notation". It is a format designed for serialized network transport, not for runtime memory storage. Inside JavaScript a JSON object is simply an object. The "Object Notation" part describes the fact that even though JSON is transferred as a string over the network, it's structure can still be read — both by software and humans — as a regular, plain JS object.
In example, JSON.stringify({foo:'one', bar:'two'}) would return '{"foo":"one", "bar":"two"}', a string representation of the JavaScript object ready for HTTP transfer. Likewise, calling JSON.parse('{"foo":"one", "bar":"two"}') on receiving end would convert it back to the original object structure with datatypes intact. Read more about JSON here.
Other than this suspected misunderstanding of what JSON is and isn't, I'm not really sure what you mean by save. I take it you are haveing trouble reading the data and not getting anything on screen. This could be due to a number of things, primarily:
You might not be working with a de-serialized JSON string. In this case the data or data.results argument above might still be JSON, in which case you need to call JSON.parse(data) on it first in order to iterate over the properties of the data object.
You might be trying to use out-of-scope variables since you are dealing with already existing variables ($htmlstring) inside of the success callback. If so you should read up on the JavaScript scope model
If none of this helps, I recommend you open up the JavaScript console in your browser, run the code and check for error messages. If any, you should post them here to better your chances of a good answer.
Good luck!

JavaScript associativea array - passing a string as array key: value pairs

I know that I can create an associative array like this:
var MyAssocArray = {'sky':'blue', 'grass':'green'};
And I am very fond of using this method.
What I would like to do and am having trouble with is this:
I have strings saved like this:
var MyString = "'sky':'blue', 'grass':'green'";
And I want to be able to do this now:
var MyAssocArray = {MyString};
When I try that - I get this error:
invalid object initializer
What am I doing wrong?
How can I achieve this?
I found a different solution using PHP and JavaScript. The associative array string is echoed in the JavaScript code:
var Multidimensional_Arr[Multidimensional_Array_Key_Name] = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
// The same can be done for a one-dimensional array
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
Use JSON -- it's serialized JavaScript Object Notation and is pretty close to what you're doing.
You'd need to do
var MyAssocArray = JSON.parse(MyString);
Also, JSON uses double quotes, not single quotes; if you use simple objects, you can probably write code to just replace ' with "" in your strings, but it's tricky if the strings contain double-quotes.
If you are using a browser that doesn't implement JSON.parse(), you can either use the implementation on the JSON website (see links at bottom of this page) or if you're using jQuery, there's jQuery.parseJSON().
Warning: Your solution has a security risk, unless you are sure the data in the database has been sanitized:
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}
This is equivalent to a call to eval(); if your database string has any malicious code it can do bad things. This is one reason why JSON was invented -- it's easy to ensure that its contents are valid (and hence safe) before evaluated.
Your overall architecture, as you have presented it to us, is [data in database] -> server-side PHP -> client-side JavaScript. This is a classic example of serialized data. I realize you may have constraints to keep your system running without interruption, but a strict serialization format would make your system more secure.
If you are sure the data is safe, then you could do:
var MyAssocArray = eval('{' + MyString + '}');
You can't do that.
To achieve what you want, use the split() function to split your string into comma-separated tokens first. Then each token should further be split by the ':' character.
Then push the two tokens obtained by the last split as the key and the value of your associative array.

Categories

Resources