0

The following JS code snippet:

    var data_JSON = {
        input: 'test',
        message: 'Sending...'
    };

    $.ajax({
        url: 'main_php.php',
        type: 'POST',
        data: data_JSON,
        dataType : 'json',
        contentType: 'application/json',        
        success: alert(data),       
        error: function (request, status, error) {      
            alert(error);
        }
    }); 

And the following associated PHP code (main_php.php):

if ($_POST){    
    $vals = array(
        'input'     => $input,
        'message'   => $message
    );
    header('Content-Type: application/json');
    echo json_encode($vals);        
}

Always result error (error runs in $.ajax), whatever I tried. In the browser's developer console, I could explore the complete length of the error message:

SyntaxError: Unexpected end of input at parse (native) at ajaxConvert ([...]/jquery-3.0.0.js:8544:19) at done ([...]/jquery-3.0.0.js:9011:15) at XMLHttpRequest. ([...]/jquery-3.0.0.js:9303:9)

Which is exactly the point where the JSON is failed to parse? What is the reason of this error and how can I solve it?

Note: JSON.stringify did not work, if that helps anything.

7
  • Is the JSON the only content you return, or does execution of the PHP code continue after the if statement? Try checking the exact response value in the console. Commented Jul 27, 2016 at 14:23
  • @RoryMcCrossan there's nothing else in the PHP file to execute, and in the JS file neither. I just want to make a "frame" to build on, currently. Commented Jul 27, 2016 at 14:24
  • How are you getting $input and $message directly ? Shouldn't it be $_POST['input'] and $_POST['message'] ? Commented Jul 27, 2016 at 14:27
  • data: data_JSON, should be data: JSON.stringify(data_JSON), Commented Jul 27, 2016 at 14:32
  • Could you try another version of jquery. say 2.1.1 and see if the error still persists Commented Jul 27, 2016 at 14:36

1 Answer 1

2

try with:

js:

var data_JSON = {
    input: 'test',
    message: 'Sending...'
 };

$.ajax({
  url: 'main_php.php',
  method: 'POST',
  data: data_JSON,
  dataType : 'json',
  success: function(data){
    alert(JSON.stringify(data)) ;
  } ,       
  error: function (request, status, error) {      
    alert(error);
  }
}); 

and php:

if ($_POST){    
    $vals = array(
      'input'     => $input,
      'message'   => $message
    );
    header('Content-Type: application/json');
    echo json_encode($vals);        
}
Sign up to request clarification or add additional context in comments.

1 Comment

I can't freakin' believe it! This was the problem! Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.