Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery AJAX Call to PHP Script with JSON Return
<div class="the-return">
[HTML is replaced when successful.]
</div>
<script type="text/javascript">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
<!--Put the following in the <head>-->
<script type="text/javascript">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
<!--Put the following in the <body>-->
<form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="favorite_restaurant" value="" placeholder="Favorite restaurant" />
<input type="text" name="favorite_beverage" value="" placeholder="Favorite beverage" />
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="the-return">
[HTML is replaced when successful.]
</div>
<form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="favorite_restaurant" value="" placeholder="Favorite restaurant" />
<input type="text" name="favorite_beverage" value="" placeholder="Favorite beverage" />
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="submit" name="submit" value="Submit form" />
</form>
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
//Do what you need to do with the info. The following are some examples.
//if ($return["favorite_beverage"] == ""){
// $return["favorite_beverage"] = "Coke";
//}
//$return["favorite_restaurant"] = "McDonald's";
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
@hahaw

This comment has been minimized.

Copy link

hahaw commented May 10, 2014

what is the "return.php"?
In html form, the from's action is "return.php".

@dwlamb

This comment has been minimized.

Copy link

dwlamb commented May 29, 2014

Thank you for wasting an hour of my time trying to get a tutorial with a bug to work. Not explaining anything about 'return,php' makes this useless.
Have a nice day.

@wolfika

This comment has been minimized.

Copy link

wolfika commented Jul 15, 2014

You don't actually have to do anything with the return.php file. In fact, your form doesn't even need to have an action or method attribute if you're using AJAX, because your form is processed through JavaScript. To be honest, I'd rather use a simple clickable button instead of a submit button, so your browser doesn't actually route the request to the URL specified in the action attribute. You can check if a button is clicked like this:

<script>
    $(document).ready(function(){
        $("#button").on("click", function(){
            // Data serialization and AJAX request here
        });
    });
</script>
@AsifAliZaman

This comment has been minimized.

Copy link

AsifAliZaman commented Mar 31, 2015

create two files
1.index.php

<!doctype html>

<title>ajax-exam</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript"> $("document").ready(function() { $(".js-ajax-php-json").submit(function() { var data = {"action": "test"}; data = $(this).serialize() + "&" + $.param(data); $.ajax({ type: "POST", dataType: "json", url: "response.php", //Relative or absolute path to response.php file data: data, success: function(data) { $(".the-return").html( "Favorite beverage: " + data["favorite_beverage"] + "
Favorite restaurant: " + data["favorite_restaurant"] + "
Gender: " + data["gender"] + "
JSON: " + data["json"] ); alert("Form submitted successfully.\nReturned json: " + data["json"]); } }); return false; }); }); </script> Male Female
[HTML is replaced when successful.]

2.response.php

define("BASE_URL", "http://" . $_SERVER['HTTP_HOST'] . "/" . "ajax/ajax-exam/");

define your response.php file path

run the index.php file

@technosmarter

This comment has been minimized.

Copy link

technosmarter commented Jan 1, 2019

Is thi working code. I think this is very complex return JSON.
We can use this imple code .

<?php
//fetch.php
include("config.php");
$column = array("fname", "lname");
$query = "
 SELECT * FROM persons WHERE 
";

if(isset($_POST["is_days"]))
{
 $query .= "date BETWEEN CURDATE() - INTERVAL ".$_POST["is_days"]." DAY AND CURDATE() AND ";
}

if(isset($_POST["search"]["value"]))
{
 $query .= '(fname LIKE "%'.$_POST["search"]["value"].'%" ';

 $query .= 'OR fname LIKE "%'.$_POST["search"]["value"].'%") ';




}

if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['7']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}

$query1 = '';

if($_POST["length"] != -1)
{
 $query1 .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$number_filter_row = mysqli_num_rows(mysqli_query($mysqli, $query));

$result = mysqli_query($mysqli, $query . $query1);

$data = array();

while($row = mysqli_fetch_array($result))
{
 $sub_array = array();

 $sub_array[] = $row["fname"].'&nbsp'.$row["lname"];

 $data[] = $sub_array;
}

function get_all_data($mysqli)
{
 $query = "SELECT * FROM persons";
 $result = mysqli_query($mysqli, $query);
 return mysqli_num_rows($result);
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  get_all_data($mysqli),
 "recordsFiltered" => $number_filter_row,
 "data"    => $data
);

echo json_encode($output);



?>(

`url`

)

for reference -

jQuery AJAX Call to PHP Script with JSON Return

@nguaki

This comment has been minimized.

Copy link

nguaki commented Jan 17, 2020

$return["json"] = json_encode($return);
echo json_encode($return);

Don't need to assign anything to $return['json'].

@pavanyogi

This comment has been minimized.

Copy link

pavanyogi commented Mar 17, 2020

Here is a git repository ( https://github.com/pavanyogi/return-json-response-to-ajax-call-php ), which I forked from the above gist with minimum code and simplified instructions. Feel free to use and suggestions (if you have any).

@Alexander-Pop

This comment has been minimized.

Copy link

Alexander-Pop commented May 24, 2020

just remove |action="return.php"| from form's markup as it doesn't effect anything (because of "return false;" in "$(".js-ajax-php-json").submit(function(){")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.