Json showing undefined or unexpected character

This is driving me mad.
I have done plenty of ajax calls but this one I can’t get working.
(jquery/1.9.1)


$("#myfile").change(function(){
    var $regform = $("#imgform");
    var iData = $regform.serialize();
    $.ajax({
        url: 'upload-pic.php',
        type: 'POST',
        data: iData,
        beforeSend: function() {
          status.empty();
          var percentVal = '0%';
          bar.width(percentVal);
          percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
          var percentVal = percentComplete + '%';
          bar.width(percentVal);
          percent.html(percentVal);
        },
        success: function() {
          var percentVal = '100%';
          bar.width(percentVal);
          percent.html(percentVal);
        },
	        complete: function(data) {
   	  $('imgstatus').html(data.msg);
        }
    })
});

The following php contains the test Json;

<?php
$result = array("msg"=>"Image Uploaded");
echo json_encode($result);

exit();
?>

The complete: function() shows the data as undefined and if I parse the data using: var obj = JSON.parse(data);
It throws this error, unexpected character at line 1 column 2 of the JSON data.

Don’t understand why.

Hi Exphor,

The $.ajax ‘complete’ callback fires whether the request was successful or not, and if data is showing as undefined then it looks like the problem is on the server side. Have you checked that your PHP script is returning the response you expect?

Hi fretburner.

I added dataType and forced text and it started working, setting the dataType to json did change the error though, so need to look at why json is a problem on the server. But forcing text makes the json work now though.

If you want JSON you need to send JSON not default text/html. i.e.

<?php
header('Content-type: application/json');
$result = array("msg"=>"Image Uploaded");
echo json_encode($result);
exit();
?>

I have tried the header also, but still presents the same error.
Undefined character - line 1, character 2