convert jQuery array to php array - javascript

This is my jQuery Array:
var IDs=[];
$("#tags").find('.suggested-tag').each(function(){IDs.push(this.id);});
and I want convert this array in php array what should I?

If your array is in JSON format, you could write its contents within a hidden form field.
Then, when the form is submitted, you are able to read the field contents (still in JSON format) and convert it to php array through:
$some_array = json_decode($var_containing_json_text);
You can read more about json_decode() here.

You can't do it directly.PHP works server-side and JQuery works client-side So You can't use Js varaibles in PHP
But there is a trick that you can use Ajax to send Js variables to PHP. This is the only way.

Related

Passing php array to javascript function from external php file

I'm working on autofilling an html form based on data from a sqlite database.
I'm using a modified version of the code from this site and in its basic feature it works as expected.
The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.
The script returns a string to update the input form:
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
The javascript function "fill" is as follows:
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
"#inputstring" is simply an input element.
What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html.
The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value.
I've tried:
$valuetopass = json_encode($query_result);
whithout
echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>';
and with quotes
echo ''.$query_result['text'].'';
And both fail.
I'm aware that similar question have been already asked 1, 2,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".
How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?
Or alternatively how can I rework the problem so that I don't need to do it at all?
Your JSON string is likely to contain ", so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.
Using PHP’s htmlspecialchars should be able to fix this in this instance.
In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.

Convert PHP-SQL Result variable to a Javascript object

I am making a simple web app, in one part of it, the result of SQL query is to be passed from PHP to JavaScript with AJAX.
This is the SQL Query:
$meta_query = mysql_fetch_row(mysql_query("SELECT * from meta WHERE user_id='$user_id'"));
This is how I pass it to JavaScript
var_dump($meta_query);
This is what I am getting at JavaScript (as a string):
array(30) {[0]=>string(1) "3"["id"]=>string(1) "3"[1]=>string(2) "14"["user_id"]=>string(2) "14"[2]=>string(10) "29-06-2014"["date"]=>string(10) "29-06-2014"[3]=>string(1) "0"["present"]=>string(1) "0"[4]=>string(1) "0"["future"]=>string(1) "0"}
How, how do I convert this into a proper JavaScript object so that the output is something like:
{"id":"3","user_id":"14","date":"29-06-2014","Present":0,"Future":0}
How do I convert data from the first format to the second in JavaScript? Or should I do something else entirely in PHP to get the data out in some other format? Or should I convert the data to the required format somehow in PHP?
You might want to use
echo json_encode($meta_query);
from php side toy should convert php array to json object using
<?php echo json_encode($array)
here is tutorial how to do this
Don't forget to put in your jquery request dataType: "json"

Pass multidimensional javascript array between pages

I need to transfer a multi-dimensional JavaScript array to another page, without using any library. What I can use is JavaScript, PHP and other languages that doesn't need a library.
I have a three-dimensional array which is build like this:
storage[category][field][multiple answers] and has a lot of values.
I need to transfer it to another page so I can get all the values like:
alert(storage[5][4][8]);
=======================================================================
Well, I can pass a normal variable to another page but I cant get the values from my array when I'm testing: storage[1][1][1] for example.The big question is how I can pass a multidimensional array to another page and still be able to get the values like this: storage[1][1][1]
As I get it I'm forced to pass all the 121 arrays you can se below to be able to access all dimensions in the array.
My array is built up like this:
storage = new Array();
for (var i1=1;i1<12;i1++){
storage[i1] = new Array();
for (var i2=1;i2<12;i2++){
storage[i1][i2] = new Array();
}
}
Without using a library like jQuery, you can convert your array to JSON, pass it via a URL and decode it on the target page. Converting it to JSON would look like:
var json_string = JSON.stringify(your_array);
Then pass it in a URL:
var your_url = "http://www.your_website.com/page.html?json_string=" + json_string;
And you could decode it back to an array like so:
var your_new_array = JSON.parse(getUrlVars()["json_string"]);
For some more reading, check out this JSON page: http://www.json.org/js.html
JSON.stringify() is supported by all major browsers. Send it to the server via a POST, then have your php retrieve the variable from $_POST and send it back.
As far as I can see there are two main ways to do what you want:
Pass the array to the webserver, and have it send it back on next request.
Store the data locally in the browser.
The first way could get pretty complicated. You would have to store the data in a database, file or cookie/session.
The second way would be the easiest. Use javascript to store the array in the browser. You can either use a cookie, or use the localStorage object.
Using a cookie would require you to serialize the data manually. It would also get passed to the server, so if you want to save bandwidth, you would want to avoid this.
The localStorage method would only store the data locally, and you also don't need to serialize anything, the browser takes care of this for you.
See the links below for more examples.
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp

How to make IF statement in Javascript based on the json result in PHP

Well, sorry for my bad grammar, but any help will be much appreciated..
Ok, here I'm trying to encode string by using json inside PHP then using JavaScript to read the json string. It will have 2 cases here.
The first one is, the application will running normally, so does the encode. The json string will be like this :
{"employee":
[{"id":"1","firstName":"aaa","lastName":"abc","timeIn":"08:00:00","timeOut":"17:00:00"},
{"id":"2","firstName":"bbb","lastName":"def","timeIn":"08:00:00","timeOut":"16:45:00"}]}
and the second one is, the PHP can't read the MySQL database, so in PHP the json encode will be like this :
{"errorProcess":{"text":SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. }}
The question is, in JavaScript how can I make an IF statement in JavaScript based on the result string in json?
Maybe it will be like this, but I don't know how to write it in JavaScript.
IF (in json string has employee){then result}
else if(in json string has errorProcess){then result}
Thanks for your help
You can check for errorProcess key using
if(json.hasOwnProperty('errorProcess')){
//do struff
}
JSON keys and values are accessed using dot (.) notation in Javascript. Assuming you already have the JSON as an object (not a string), you can simply write
if (json.employee) {
// do something
}
else if (json.error) {
// do something else
}
where json is a variable referencing your returned JSON from the php.
If your JSON is still in string format, you need to parse it into an object. This can be done with the built in JSON object.
var json = JSON.parse(jsonAsString);
First you need to parese JSON like this
var jsonObject= jQuery.parseJSON(yourJsonObj);
if(jsonObject.hasOwnProperty('employee')){
// Add your code
}else if(jsonObject.hasOwnProperty('errorProcess')){
// Add your code
}

Passing hashmap from javascript to servlet

I created a simplehashmap using the accepted solution in this question:
How to create a simple map using JavaScript/JQuery
I however need to send this var to a servlet and retrieve them onto a Java HashMap. How do I do that.
The key is a string while the value is an array, say like:
`[1,'apple,orange, banana'],[2,'apple,peach, banana']` ...
I need the keys 1,2 and the array loaded onto a Java HashMap.
I tried to post it using jquery. where selectedrows is my map
$.post(url, { id: selectedrows });
I creates a JSON string and then sent it via an ajax post to the servlet and build the HashMap there.

Categories