JavaScript array from PHP string - php

I am developing an application having more than thousands of values. I am trying to make a dynamic array in JavaScript. I'm using AJAX to get my values. So I have to create a string from PHP ,it should able to convert from string to array in JavaScript.
How can I make a string in PHP that can be converted to array in JavaScript?

You are looking for JSON and json_encode():
$string = json_encode($array);
The content of the string will be the array written in valid javascript.

Use JSON notation to create a string of values and then read it from JS. The simplest way to do this is something like that:
<script type="text/javascript">
var myPHPData = <?php echo json_encode($myData); ?>;
alert myPHPData; // now you have access to it in JS
</script>

if you dont intend to use json , you can do something of this kind..
you can create a string of this kind in php (separate it by any delimiter)
$arr = "1;2;3;4;5;6;7" ;
in javascript you can convert this to array using split function
//make an ajax call and get this string (say str)
arr = str.split(";");
split() returns an array
arr[0] is 1
arr[1] is 2
and so on !!

Related

How to process different type of object returned from php in react native

I am getting this type of object from PHP. {"3":4} Starting array is another value which is encoded into json and echoed. And the rest is another array which is encoded into json and echoed.
How to process this in react native.
{"3":4}{"1":{"section":"8CSB","lecture_id":"24","subject_name":"MySQL","subject_code":"8CS2","date":"2020-04-29","lecture_no":"1"},"2":{"section":"8CSB","lecture_id":"25","subject_name":"Android","subject_code":"8CS3","date":"2020-04-29","lecture_no":"2"},"3":{"section":"8CSB","lecture_id":"26","subject_name":"Mobile Computing","subject_code":"8CS1","date":"2020-04-29","lecture_no":"3"},"4":{"section":"8CSB","lecture_id":"43","subject_name":"UNPS Lab","subject_code":"8CS5","date":"2020-04-29","lecture_no":"5"},"5":{"section":"8CSB","lecture_id":"45","subject_name":"UNPS Lab","subject_code":"8CS5","date":"2020-04-29","lecture_no":"6"}}
It's JavaScript at the end of the day and that's JSON - so you just parse it in JS.
var Object = JSON.parse(jsonstring);
For a more detailed explanation of what to do, try this which will go into the picker.
As for the first part, it's malformed, by the looks of things, so you cannot parse it.
To remove the first part, if it is consistently this, you can do it like so:
var Inputobject = <your input>;
var jsonstring = Inputobject.slice(7);
var Object = JSON.parse(jsonstring);

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.

How can I post a 2D JavaScript array to the server?

I have an array, myData=[[1,2,3],[4,5,6],....,[..,..,..]]
I want to post this to the server.
Usually, for a JS variable, I just put the variable into a textbox and then submit the form using JS. However, when I put the 2D array into a textbox, JS converts it to a string, such that it becomes a 1D array, which looks like:
[1,2,3,4,5,6....]
I want to be able to post the entire 2D array to the server and retrieve it on the next page using PHP. How do I do that?
Thanks!
You should use JSON to turn the array into a string with javascript and then parse the string back into an array in php.
for example:
var myData = var data = [['hooray',1],['test','meow'],[0,3,2]];
var myData_string = JSON.stringify(myData);
This will turn your object/array into a string which you can then POST and parse with php like so:
$myData = json_decode($input);
References:
JSON (javascript)
json_decode() (php)

JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code.
I want my json string to be embeded inside my JS, like this:
var params = dojo.fromJson('<?=json_encode($this->params); ?>');
dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.
It seems that json encoder ignores ' chars and only converts " to \". So when one of my variables inside $this->params contains a ' character there is a Javascript error.
For example:
var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');
What is the best way to approach this ?
Thanks for help.
Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.
var params = <?=json_encode($this->params); ?>;
PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.

zend php multiple array json_encoding

I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>

Categories