send array using jquery - php

i have a variable $visitRecord->getReferallist() which get the list of doctors in an array . i need to send the array to a php file and do foreach action in php file.. how do i send this array variable in the jquery . This code did not work.
function seekOpinion()
{
var queryUrl = "<?php echo $this->url(array('controller' => 'consultant', 'action' =>'opiniondoclist'));?>";
$.post(queryUrl,{referal:'<?php echo $gotreferal; ?>',visitId:'<?php echo $gotvisitId; ?>',referalList:'<?php echo $visitRecord->getReferallist(); ?>'},function(data)
{
$('.opiniondoclistData').html(data);
});
document.getElementById('opiniondoclistDiv').style.display = "";
}

Your problem is that you're working with an Array in PHP.
echo $visitRecord->getReferallist(); // Returns array of referrals.
When you cast the array to a string by echo'ing it (because echo outputs strings) then you get the text "Array".
In order to send this over the wire(from javascript via AJAX ($.post)) you will need to convert your referral list into a string. One method is serialization. You can convert your array into a "stringable format" using the serialize() function. www.php.net/serialize.
When this is received from PHP in the AJAX request you can convert your "stringable formatted" array back into a pure array using the unserialize() function. www.php.net/unserialize.
Your code should change from
$visitRecord->getReferallist();
to
serialize($visitRecord->getReferallist());
Then when it's received you should change your code from
$referrals = $_POST['referalList']; // Stringable version of the array
to
$referrals = unserialize($_POST['referalList']); // Pure PHP array

Use Serialize() to transform your array into a string, send it , then use unserialize() to get it back into an array in php;
Serialize()

I think you can use json_encode() to encode the array as a string that jquery will be able to read back as a javascript array
EDIT: sorry I didn't read your question properly, I see that you don't want to read the array in javascript, but in PHP so probably serialize() and unserialize() is better than json_encode() assuming that it escapes properly for use with javascript.

var sendData = 'referal=<?php echo $gotreferal; ?>&visitId=<?php echo $gotvisitId; ?>&referalList=<?php echo implode('-', $visitRecord->getReferallist()); ?>';
$.post(queryUrl, sendData,function(data) { //etc
Then the receiving script can (in addition to any necessary sanitization):
$referalList = explode('-', $_POST['referalList']);
Don't forget to addslashes to all the variables you are echoing if necessary

PHP will automatically create an array variable from a query string, or posted data, which contains a "[]" at the end of the name. For example, you can do a jQuery load call as follows to pass an array to PHP.
$('#target').load('index.php?foo[]=a&foo[]=b');
On the PHP side, you will have an array called foo in $_GET
<?php
echo 'I have ' . $_GET['foo'][0] . ' and ' . $_GET['foo'][1];
?>
jQuery's AJAX functions, e.g. $.post, $.get and $.ajax can pass javascript arrays like this in their data sections - just be sure to name the variable with a "[]" at the end so that PHP knows how to handle it.

I found a solution on this problem...
Use this function in your javascript...
function js_array_to_php_array (a)
{
var a_php = "";
var total = 0;
for (var key in a)
{
++ total;
a_php = a_php + "s:" +
String(key).length + ":\"" + String(key) + "\";s:" +
String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}
a is the array you passed in this function
then.. on your php where you get the return array of this function write this code...
$my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
// print_r ($my_array);
Hope it helps...

Related

Populate JS array from returned PHP/JSON

I have a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

How to get data from json array in JavaScript?

I have php function, that returns array to JavaScript like this:
$data['first'] = 10;
$data['second'] = 20;
echo json_enocde($data);
In JavaScript the returned value is named response. I need to display the values and tried like this after reading about json:
alert("First: " + response.first + " Second: " + response.second);
But this code only shows undefined values in places of response.first and response.second.
If I write alert(response), then I get answer:
{"first":"10","second":"20"}
This means, that JavaScript is getting the information.
How can I get the values separately from the json encoded array?
Regards
Use JSON.parse() to turn the JSON string into a JavaScript object.
Looks like you still have the JSON string, and not parsed it to an JS object. Use JSON.parse:
var jsonString = '{"first":"10","second":"20"}'; // from whereever
var obj = JSON.parse(jsonString);
alert("First: " + response.first + " Second: " + response.second);
alert(obj); // should now be "[object Object]"
use eval like (NOT RECOMMENDED)
var res = eval(response); //as you can see people are against it so I am editing the answer
USE
JSON.parse()
OR if you use jquery
jQuery.parseJSON(response);

How to pass arrays through JSON php

I'd like to pass arrays through JSON like this:
<?php
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
echo json_encode($arrayA,$arrayB);
?>
I know it's not possible, but is there other way to pass dynamicly loaded arrays and read them in javascript after that?
Just put both array in another array.
$returnArr = array($arrayA,$arrayB);
echo json_encode($returnArr);
On JS side just decode with a library of your choice and access the returned array like any normal array.
echo json_encode(array('arrayA' => $arrayA, 'arrayB' => $arrayA));
Just create wrapper for your arrays:
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
$arrayC = array($arrayA,$arrayB);
echo json_encode($arrayC);
On jQuery side:
$.getJSON('ajax/yourPhpFile.php', function(data) {
$.each(data, function(key, val) {
// each `val` is one of the arrays you passed from php
});
});
You can use AJAX to load up a script that will return a PHP generated array. If you're using jQuery, you call it using either $.get() or $.getJSON(). You can read up on PHP JSON manual here http://php.net/manual/en/book.json.php and on jQuery .getJson() function here http://api.jquery.com/jQuery.getJSON/

Parsing a JSON string to array, not object

I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.

Categories