Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  132] [ 4]  / answers: 1 / hits: 15449  / 7 Years ago, tue, may 9, 2017, 12:00:00

I am doing a ajax call from java script and Im trying to get json response from php, if I set dataType as JSON, ajax error block is getting executed if not success block is getting executed, without specifying dataType if I try to console.log the response in success block I am getting nothing



JS



let CurrentDate = Date();
console.log(CurrentDate);

jsonObject = {
'TrackName' : 'Material Science',
'TrackDesc' : 'Test Text Test Text Test Text Test Text Test Text Test Text Test Text ',
'Timestamp' : CurrentDate
}
console.log(jsonObject);
$.ajax({
type:'post',
url:'../../../../PHP/adminScripts/addNewTrack.php',
contentType: application/json,
data: {trackDetails:jsonObject},
dataType: json,
success: function(response) {
console.log('SUCCESS BLOCK');
console.log(response);
},
error: function(response) {
console.log('ERROR BLOCK');
console.log(response);
}
});


PHP



<?php
header('Content-type: application/json');
include('../connection.php');

if($_POST) {
$obj = $_POST['trackDetails'];

$TrackName = mysql_real_escape_string($obj['TrackName']);
$TrackDesc = mysql_real_escape_string($obj['TrackDesc']);
$TrackAdderID = 'Admin '; //$_SESSION[userID];
$Timestamp = mysql_real_escape_string($obj['Timestamp']);

$response_array['status'] = 'status123';
echo json_encode($response_array);


please help me figure out how to get json response to an ajax call in PHP


More From » php

 Answers
29

  • In your JS file, remove contentType: application/json,

  • In your php file, check include file url and

  • Close if statement block properly



JS File:



let CurrentDate = Date();
jsonObject = {
'TrackName' : 'Material Science',
'TrackDesc' : 'Test Text Test Text Test Text Test Text Test Text Test Text Test Text ',
'Timestamp' : CurrentDate
}
$.ajax({
type:'post',
url:'addNewTrack.php',
data: {trackDetails:jsonObject},
dataType: json,
success: function(response) {
console.log('SUCCESS BLOCK');
console.log(response);
},
error: function(response) {
console.log('ERROR BLOCK');
console.log(response);
}
});


PHP File:



<?php
header('Content-type: application/json');
include('../connection.php');

if($_POST) {
$obj = $_POST['trackDetails'];

$TrackName = mysql_real_escape_string($obj['TrackName']);
$TrackDesc = mysql_real_escape_string($obj['TrackDesc']);
$TrackAdderID = 'Admin '; //$_SESSION[userID];
$Timestamp = mysql_real_escape_string($obj['Timestamp']);

$response_array['status'] = 'status123';
echo json_encode($response_array);
}
?>

[#57846] Saturday, May 6, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;