Abudayah
Abudayah

Reputation: 3875

Ajax send JSON and fetch data using PHP

I have jquery code output json data and I need to send this data to to url and fetch using php

Code:

JSON.stringify(showtimes)

Output:

[{"show_id":"1","movie_id":"20","cinema_id":"10","status":"0","times":"00:00"},{"show_id":"2","movie_id":"21","cinema_id":"11","status":"1","times":"01:00"}, ... etc]

I need to send this json data JSON.stringify(showtimes) via ajax to url and fetch json using php.

My ajax code:

$.ajax({
    type: 'POST',
    url: '/admin/save/',
    data: JSON.stringify(showtimes),  
    success: function(data){}
});

Question:

Upvotes: 1

Views: 1734

Answers (3)

Mike Mackintosh
Mike Mackintosh

Reputation: 14237

Firstly, you should assign a data key to your json object in the javascript:

$.ajax({
    type: 'POST',
    url: '/admin/save/',
    data: {json : JSON.stringify(showtimes)},  
    success: function(data){}
});

Within your PHP would would access the JSON string as:

$_POST['json'];

Secondly, within PHP you will want to gather your data using the following example:

$json = json_decode($_POST['json'], true);

You can then access your JSON array as an associative array:

foreach($json as $show_details){
    $show_id = $show_details['show_id'];
    ...
}

Upvotes: 3

px4n
px4n

Reputation: 416

You can check if the ajax response valid JSON by using something like below:

function isValidJSON($request_data)
{
  return (json_decode($request_data) != NULL) ? TRUE : FALSE;
}

You can then use json_decode() to decode the data.

Upvotes: 1

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

To decode json to php array use json_decode.

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

  //It is ajax

}

Upvotes: 0

Related Questions