0

I am attempting to figure out this error I have been getting tonight with a php script I am working on. So far this is the only one of my scripts, all set up in the same fashion, that is generating a failure on an Ajax POST request where a JSON string is returned to the html page for further processing.

First, here is the php script:

<?PHP
header('Content-Type: application/json');
include_once 'functions.php';

/*if(empty($_POST['uname']))
{
    $data = array("error" => "un_empty");
    echo json_encode($data);
    exit();
}

if (empty($_POST['pword']))
{
    $data = array("error" => "pw_empty");
    echo json_encode($data);
    exit();
}

if (empty($_POST['pword2']))
{
    $data = array("error_2" => "pw2_empty");
    echo json_encode($data);
    exit();
}

if ($_POST['pword'] <> $_POST['pword2'])
{
    $data = array("error" => "pw_nm");
    echo json_encode($data);
    exit();
}

if (empty($_POST['em']))
{
    $data = array("error" => "em_empty");
    echo json_encode($data);
    exit();
}


if (empty($_POST['em2']))
{
    $data = array("error" => "em2_empty");
    echo json_encode($data);
    exit(); 
}

if ($_POST['em'] <> $_POST['em2'])
{
    $data = array("error" => "em_nm");
    echo json_encode($data);
    exit();
}

$username = $_POST['uname'];
$password = $_POST['pword'];
$email = $_POST['em'];*/

$username = "TestUser";
$password = "maS_t!@";
$email = "geowil11@gmail.com";

//echo $username."|".$email."\n";

$returnedData = register($username,$password,$email);

if ($returnedData === "true")
{
    $returnedData = "noerror";
    $data = array("success" => $returnedData);
    echo json_encode($data);
    //var_dump($data);
    exit();
}

else
{
    $data = array("error" => $returnedData);
    echo json_encode($data);
    //var_dump($data);
    exit();
}

?>

Using var_dump on the "else" json return generates an array with the following elements: "error" => "exists1"

Which is what is expected as the account information being passed to the registration function already exists in my database.

Here is the actual AJax call from the html file:

        var dataStr = $('#reg').serialize();

        alert(dataStr);
        $.ajax(
        {
            url: "php/register.php",
            type: "post",
            data: dataStr,
            success: function(jsonstr)
            {
                onSuccess(jsonstr);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            { 
                alert("Status: " + textStatus);
                alert("Error: " + errorThrown); 
            }                       
        });
    });
});

The serialized object is a form that normally passes data to the registration.php file which I added above but for now I have the checks and setting of the POST data to the php vars used commented out for testing.

I have tried a variety of things to try and fix the issue including messing around with the form and the data being returned to the html page. So far all I have gotten back is JSON.parse yelling at me about unexpected characters.

Edit:

For clarity here are the exact errors:

Status: parsererror

Error: SyntaxError: JSON.parse: unexpected character

And for further problem solving, here is an alert of an example serialization of the form on the HTML page:

uname=TestUser&pword=12qwE!&pword2=12qwE!&em=geowil11%40gmail.com&em2=geowil11%40gmail.com

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Geowil
  • 624
  • 1
  • 12
  • 36
  • 1
    Please add `console.log(jsonstr)` before `onSuccess(jsonstr);` to get the output. – Junle Li Aug 12 '14 at 05:08
  • @LiJunLe It never reaches that area of the call. Instead it lands in the error: handler for the Ajax call. – Geowil Aug 12 '14 at 05:11
  • So, which line of code throws that exception? how about the output of `alter(dataStr)`? – Junle Li Aug 12 '14 at 05:14
  • @LiJunLe the two lines in the error handler: alert("Status: " + textStatus); alert("Error: " + errorThrown); As for the alert you suggested it produces this: uname=TestUser&pword=12qwE!&pword2=12qwE!&em=geowil11%40gmail.com&em2=geowil11%40gmail.com – Geowil Aug 12 '14 at 05:17
  • 1
    OK, I get it. First, comment out `header('Content-Type: application/json');` in PHP code, this should bring you to `onSuccess` line, then `console.log` to output what is going here. – Junle Li Aug 12 '14 at 05:21
  • @LiJunLe Ah, it seems that PHPMailer's $mail->Send() function is echoing out a bunch of text that is making it into the JSON return. – Geowil Aug 12 '14 at 05:25
  • OK, so you resolve it? – Junle Li Aug 12 '14 at 05:29
  • @LiJunLe Yeah, I forgot to disable SMTPDebug in PHPMailer *facepalm*. Thanks for the suggestions. – Geowil Aug 12 '14 at 05:30
  • just try to use dataType:"json" in your jquery ajax call and let me know of it help! – developerCK Aug 12 '14 at 05:45

3 Answers3

0

I figured it out with some help from Junle Li. PHPMailer was echoing out text into the JSON, polluting it, as I had SMTPDebug turned on from when I was still testing somethings out within my functions.php file.

Turned that off and commented out some other echoes and now it is working correctly again.

Geowil
  • 624
  • 1
  • 12
  • 36
0

I've just faced the similar problem. So, try to deal with ajax json response string in the "complete" callback function because the "success" might be never called in some cases. And I advise you to check your ajax response string for invalid format first before using it as a json object. So try to put the following code into your AJAX complete callback function and you will avoid a lot of problems in future:

    complete: function(data) {
        var jsonRes = null;
        try {
            jsonRes = JSON.parse(data.responseText);
        }
        catch(e) {
            jAlert('Invalid JSON object);
        }
        if (jsonRes===null || jsonRes.result===undefined) {
            jAlert('Invalid Ajax response structure');
        }
    }
Anton G
  • 129
  • 1
  • 12
-1

Dude you can try this one, well i'm not really sure what's inside your included file "function.php".. it seems, error => exist1 came from a trapping from your php code...

Well, for a successful POST try this below:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
$.ajax({
type: 'POST',
url: 'https://to.com/register.php',
crossDomain: false,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
    var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
    alert('POST failed.');

</script>
i am ArbZ
  • 1
  • 2
  • You've made all sorts of changes to that JavaScript, and none of them make any sense at all. – Quentin Aug 12 '14 at 05:46
  • No, I mean, the "register.php" has it's header set to application/json so its better to post for its own accepted datatype... you know what i mean here.. – i am ArbZ Aug 12 '14 at 05:49
  • That means that `register.php` is **responding** with JSON, not that it expects JSON as the input. The only code that tries to read submitted data in there is commented out, but it uses `$_POST` so the data can't be JSON encoded. `$_POST` only gets populated for `application/x-www-form-urlencoded` and `multipart/form-data` encoded data. You have to use [other methods](http://stackoverflow.com/questions/19004783/reading-json-post-using-php) to get data encoded as JSON from a request, and the code isn't doing that. – Quentin Aug 12 '14 at 05:53
  • well, thats part of the POST request isn't it???... So its like, uploading a text file for an image type php uploader???... why dont try it please... anyway, you can handle the above problem with pure jquery/ajax though but that's not the solution he's asking for. – i am ArbZ Aug 12 '14 at 05:58
  • No, it is nothing like uploading a text file for an image type uploader. Imagine a PHP script which takes a picture of some clouds (always the same picture, one that is stored on the server) and then edits it by adding some custom text across the clouds. You are suggesting that, because it generates an image, the browser must give the server an image. This is nonsense, the server needs to know the text that should be written on the image so the browser needs to send text. – Quentin Aug 12 '14 at 06:02