Passing JavaScript Array To PHP Through JQuery $.AJAX
X

Congrats, You are Subscribed to Receive Updates.

Passing JavaScript Array To PHP Through JQuery $.AJAX


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.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts