...

View Full Version : How do I send Javascript/jQuery array to PHP?



JustBob
09-30-2011, 01:33 AM
Hi

How do I send an array created in jQuery or Javascript to PHP? (page will be redirected to PHP)

I'm thinking of URL parameters right now, but wont that result to a long URL? Is there another optimized way of sending the array?


Here's my script. Which doesn't work.

Here's my script, this works fine...

send_array_to_other_page.html

$(function(){
//DECLARE ARRAY
var arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#send').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});

This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list=


<?php
$arr = $_GET['list'];
echo 'The contents of the array are still... <br/>';
if(isset($arr)){
print_r($arr);
} else {
echo 'Array content lost';
}
?>

Old Pedant
09-30-2011, 02:10 AM
Only two ways: Query string or post data. And neither way allows you to actually send an array. The best you can do is convert the array to a delimited string and send the string.

So the easy way to do this is to have a <form> with a (possibly hidden) field that you put the array (converted to a delimited string, of course) into that field and then submit the form.

I don't use jQuery, so I don't understand WHAT is building the array in that code.

It looks like each time the user hits the submit button you tack on another value to the array and then when he/she hits the send button you send the entire array?

Is this that same page where you have many <form>s??? How do you prevent them from submitting the same <form> more than once?

By the way:

Here's my script. Which doesn't work.

Here's my script, this works fine...

Ummm...okay... so which is it?

DanInMa
09-30-2011, 03:53 AM
i had to read it about 5 times but i think i get it. I have a question, do you have more than one element with an id of #box by chance?

I also suspect you are trying to send general form data, why not use .serialize()?

JustBob
09-30-2011, 12:00 PM
i had to read it about 5 times but i think i get it. I have a question, do you have more than one element with an id of #box by chance?

I also suspect you are trying to send general form data, why not use .serialize()?

I can have different elements with different indexes.

How do I use serialize()?




It looks like each time the user hits the submit button you tack on another value to the array and then when he/she hits the send button you send the entire array?

Thats what the script does.



By the way:
Ummm...okay... so which is it?
Sorry about that. What I meant is the HTML works fine but the PHP doesn't

Kor
09-30-2011, 01:20 PM
Only two ways: Query string or post data. And neither way allows you to actually send an array.
Not exactly.

Data can be sent as a JSON object, via AJAX
http://ditio.net/2008/07/17/php-json-and-javascript-usage/
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php

There is also a possibility to send data which will be interpreted as an array by PHP: using a common squared names like

?name[]=value1&name[]=value2&name[]=value3 ... and so on

coiner
09-30-2011, 02:30 PM
This is quite simply done using jQuery. You will convert the array to a JSON string, POST the string to your PHP page using ajax, then PHP will convert it back to an array. You can also return a JSON response back to the client if you wish. Example follows:

JavaScript/jQuery:


//convert array to json
var jsonArray = JSON.stringify(theArray);
//prepare POST data
var dataToPost = { 'jsonArray':jsonArray };

//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: 'http://www.example.com/example.php',
data: dataToPost,
success: function (data) {
//function to handle the response
var response = eval( '(' + data + ')' );
//response is now an object!
}
});


example.php:


//create object/array from json data
$theArray = json_decode($_POST['jsonArray']);

//$theArray is now the array you had on the client side!

$some_object = doSomething($theArray);

//prepare the response object/array to the client
$response = json_encode($some_object);

echo $response;

JustBob
09-30-2011, 03:16 PM
This is quite simply done using jQuery. You will convert the array to a JSON string, POST the string to your PHP page using ajax, then PHP will convert it back to an array. You can also return a JSON response back to the client if you wish. Example follows:

JavaScript/jQuery:


//convert array to json
var jsonArray = JSON.stringify(theArray);
//prepare POST data
var dataToPost = { 'jsonArray':jsonArray };

//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: 'http://www.example.com/example.php',
data: dataToPost,
success: function (data) {
//function to handle the response
var response = eval( '(' + data + ')' );
//response is now an object!
}
});


example.php:


//create object/array from json data
$theArray = json_decode($_POST['jsonArray']);

//$theArray is now the array you had on the client side!

$some_object = doSomething($theArray);

//prepare the response object/array to the client
$response = json_encode($some_object);

echo $response;


I actually saw some example of JSON.stringify but was unable to test because most of the examples I saw require additional scripts that need to be included but their links were broken. Do you have the link to the required additional script?

coiner
09-30-2011, 03:34 PM
the JSON functions are included in all modern browsers, no external script is required. If you require support for IE6 and the like, the script is available on json.org.

Kor
09-30-2011, 03:44 PM
the JSON functions are included in all modern browsers, no external script is required.
Unfortunately, not all the users have modern browsers. We must wait till at least IE6 and IE7 will be extinct :)

JustBob
09-30-2011, 04:07 PM
the JSON functions are included in all modern browsers, no external script is required. If you require support for IE6 and the like, the script is available on json.org.

I see...I guess the thread I saw was quite old. I'll try this and post back.

niralsoni
09-30-2011, 06:29 PM
$('#send').click(function(){
alert(('send_array_to_other_page_2.php?list='+arr).length); // added by me
window.location = 'send_array_to_other_page_2.php?list='+arr;
});

can you please check the length of the string you are passing to window.location ??

This check is required because this will create "GET" request rather then "POST", and the maximum possible size of the "GET" query request is 2048 characters.

So, if your url length exceeds this, then definitely you will get the "Array contents lost" error.

Its better to use form.submit() (and method=POST) to send large data to server side.

Hope this may resolve your problem

Thanks & Regards,
Niral Soni

JustBob
10-01-2011, 07:11 AM
@coiner

JSON.stringify works perfectly! Thanks


@niralsoni

It is possible that the length of the variable would be long. It will depend on how many items are added to the cart.


How do I incorporate form.submit() to my script? As I understand, using submit in jQuery/Javascript would work if I intend to refresh a div in the same page, but it wont work if I redirect to another page.

niralsoni
10-01-2011, 02:53 PM
How do I incorporate form.submit() to my script? As I understand, using submit in jQuery/Javascript would work if I intend to refresh a div in the same page, but it wont work if I redirect to another page.

form.submit() is used for both of the above quoted sentences, i.e., refreshing same page or redirecting to another page.

The change between both these requirement lies in the action attribute of the form.

Old Pedant
10-01-2011, 11:13 PM
Totally silly post deleted.

Though I still don't know how you could meaningfully use XMLHTTP to do fully binary transfers. For that matter, I don't know how you get the *binary* representation of JavaScript data in the first place.

coiner
10-02-2011, 03:10 AM
@Old Pedant - Actually http does support binary data transfer, how else would you transfer pics and other files between the client/server? In addition, the JavaScript Object Notation implies plain text anyway. Ranting doesn't answer the question either...

@JustBot - As for updating a <div> on your page, I already showed you how to do that in my example. Use jQuery's built in AJAX functions.

coiner
10-02-2011, 08:59 AM
Though I still don't know how you could meaningfully use XMLHTTP to do fully binary transfers. For that matter, I don't know how you get the *binary* representation of JavaScript data in the first place.

Why would you need a binary transfer for JSON? I am suggesting he POST this to a PHP page and handle the response by using jQuery's ajax functions..

ironboy
10-02-2011, 09:46 AM
:)
Binary cross-browser AJAX:
http://nagoon97.wordpress.com/2008/04/06/reading-binary-files-using-ajax/



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum