Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Send multiple data with ajax in PHP
In PHP web applications, you often need to send multiple data values through AJAX requests. This can be accomplished using different data formats and methods depending on your requirements.
Method 1: Sending JSON Data
You can send multiple values as a JSON object by specifying the content type and structuring your data accordingly −
var value_1 = 1;
var value_2 = 2;
var value_3 = 3;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "your_url_goes_here",
data: { data_1: value_1, data_2: value_2, data_3: value_3 },
success: function (result) {
// perform operations here
}
});
Method 2: Using Form Serialization
For form data, you can serialize the entire form and send it via POST −
$.ajax({
type: "POST",
url: $('form').attr("action"),
data: $('#form0').serialize(),
success: function (result) {
// perform operations here
}
});
Method 3: Direct Object Notation
You can also pass data directly as an object, which is cleaner than string concatenation −
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = 10;
var USERID = 1;
$('.show_more').hide();
$('.loading').show();
$.ajax({
type: 'POST',
url: '/ajaxload.php',
data: {id: ID, user_id: USERID},
success: function(html){
$('#show_more_main' + ID).remove();
$('.post_list').append(html);
}
});
});
});
PHP Server Side Handling
On the PHP side, you can receive the data using $_POST superglobal −
<?php
// ajaxload.php
if ($_POST) {
$id = $_POST['id'];
$user_id = $_POST['user_id'];
// Process the data
echo "Received ID: " . $id . " and User ID: " . $user_id;
}
?>
Conclusion
Use object notation for cleaner code, form serialization for complete forms, and JSON format when you need structured data transfer. Always validate and sanitize received data on the server side.
