Pass Javascript array to PHP using AJAX

Asked
Active3 hr before
Viewed126 times

7 Answers

usingjavascriptarray
90%

Stringify your javascript object (json) with var st = JSON.stringify(your_object);,Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... });,Electrical Engineering, Formal way of saying "I'm not going to kiss your a**"

data: {
   activitiesArray: activities
},

That's it! Now you can access it in PHP:

< ? php $myArray = $_REQUEST['activitiesArray']; ? >
load more v
88%

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.,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., Passing JavaScript Array To PHP Through JQuery $.AJAX ,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.

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");
   }
});
load more v
72%

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL),If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.,Understand that English isn't everyone's first language so be lenient of bad spelling and grammar., featuresstuff Competitions Conferences News The Insider Newsletter The Daily Build Newsletter Newsletter archive Surveys Product Showcase CodeProject Stuff

0
65%

An Array is used to store multiple values in a single variable.,This can be used to pass the group of related values as data to the $.ajax for processing and get the response.,Here, name and email are string type variables and lang is an Array variable.,Passing the initialized variables as data in AJAX request.

I am using userinfo table in the example.

CREATE TABLE `userinfo`(
   `id`
   int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
   `name`
   varchar(100) NOT NULL,
   `email`
   varchar(100) NOT NULL,
   `lang`
   varchar(100) NOT NULL,
   `timestamp`
   timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
load more v
75%

I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.,Let's say I have a javascript array with a bunch of elements (anywhere from 50-200)., php 7 - Pass the array to the varargs function in PHP

Let's say I have a javascript array with a bunch of elements (anywhere from 50-200).

I want to send that to PHP (prepared statement) using ajax. Currently, I .load a php file many times inside of a loop, but I want to convert that into an array and send the array once, loading the PHP file once instead of 50-200 times.

.load
load more v
40%

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).on('click','#save',function(e) {
    	var vehicle = [];
		/*Initializing array with Checkbox checked values*/
        $("input[name='vehicle']:checked").each(function(){
            vehicle.push(this.value);
        });
    $.ajax({
         data:  {
			 vehicle:vehicle
		 },
         type: "post",
         url: "save.php",
         success: function(data){
              alert(data);
         }
	});
});
</script>
</head>
<body>
	<form action="" id="form-search">
	  	<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
		<input type="checkbox" name="vehicle" value="Car"> I have a car<br>
		<input type="checkbox" name="vehicle" value="Boat"> I have a boat<br>
	</form>
	<button id="save" name="save">Serialize form values</button>
</body>
</html>
  
load more v
22%

This is what I’ve tried so far.
HTML:

<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

</head>

<body>
	<h3>Pass JavaScript array into PHP.</h3>
	<form method="POST">
		<input type="hidden" id="jsarray" name="jsarray" value="" />
		<input type="submit" id="#btn" value="Sumbit" />
	</form>
	<br>
	<div id="response"></div>
</body>

<script type="text/javascript">
	$(document).ready(function(){
	    //attach to the button a click event
	    $('#btn').click(function(){
	        //get the value from the textbox
	        //var jsarray = $('#jsarray').val();
	
	        var jsarray = new Array();
			jsarray[0] = "Saab";
			jsarray[1] = "Volvo";
			jsarray[2] = "BMW";
			
			$('#jsarray').val() = jsarray;
	
	        if(typeof jsarray !== 'undefined') {
				//send txt to the server
	            //notice the function at the end. this gets called after the data has been sent
	            $.post('<?php echo base_url('admin/js2php_proc'); ?>', {'text':jsarray}, function(data){
	            	//Now data is an object, so put the message in the div
	                $('#response').text(data.message);
	            }, 'json');
	        }
	    });
	});
</script>
</html>

PHP:

//Capture data array from AJAX and process it...
function js2php_proc() {
   if (!empty($_POST)) {
      //start an output var
      $output = array();

      //do any processing here.
      //$output['message'] = "Array successfully sent!";
      $output['message'] = $_POST['jsarray'];

      //send the output back to the client
      echo json_encode($output);
   }
}
load more v

Other "using-javascript" queries related to "Pass Javascript array to PHP using AJAX"