Passing JavaScript Array To PHP Through JQuery $.AJAX
- Article
- Comment (2)
Passing JavaScript Array To PHP Through JQuery $.AJAX. Sometimes you need to process an array of data through php. But we have the Array in JavaScript. So we need to pass the whole array in a variable. We have two options.
- JSON String
- Direct array
Direct Array :
This one is simplest method to pass the data’s from JavaScript to php. Just add the Array directly on data and pass it through AJAX. When you receive the Array through php there you can process it as like normal array in php.
No need to work on decoding process.
$.ajax({ type: "POST", url: "yourFunctions.php", data: { kvcArray : arrayfromjs}, success: function() { alert("Success"); } });
And your php file you Can get it directly as like the following code.
$myArray = $_POST['kvcArray'];
That’s it.
JSON String :
This method you need to convert the JavaScript array to JSON String. And than we will pass it to Ajax than we will receive it on php than decode the JSON there. So it’s extra task to compile the JSON string and decode it again. But it’s a classic method to work on arrays from JavaScript to php.
var myJSONText = JSON.stringify( arrayfromjs ); $.ajax({ type: "POST", url: "yourFunctions.php", data: { kvcArray : myJSONText }, success: function() { alert("Success"); } });
And your php will be like this.
$myArray = json_decode($_POST['kvcArray']);
That’s it.
Hi Thank you for this.
Good One,
Nice and simple !