0

When a reigster clicks to register I call a php script via an ajax request which creates the user and emails a notifcation:

$.ajax({
    type: "POST",
    dataType: "json",
    data: dataString,
    url: "includes/register-user.php", 
    success:function(result){
         console.log('Success!);
    }
});

MY php has an if statement on the mail send:

if($mail->Send()){
     $reply = ['response'=> true, 'message' => 'User successfully registered'];
}     
else{
     $reply = ['response' => false, 'message' => 'An error has occurred'];
}

echo json_encode($reply);

The email is sent and received but the success function in the jQuery doesn't fire. There is no other output in the PHP and no errors, all I see is a JSON object:

{"response":true,"message":"User successfully registered"}

I've been dubugging this for 4 hours and it makes no sense whatsoever!

Update:

General:

Request URL:http://foo.bar/includes/email-register-confirm.php Request Method:POST Status Code:200 OK Remote Address:127.0.0.1:80 Referrer Policy:no-referrer-when-downgrade

Repsonse headers:

Connection:Keep-Alive Content-Length:85 Content-Type:text/html; charset=UTF-8 Date:Fri, 23 Jun 2017 14:12:43 GMT Keep-Alive:timeout=5, max=94 Server:Apache/2.4.23 (Win64) PHP/7.0.10 X-Powered-By:PHP/7.0.10

Update and Solution

I found that my phpmailer class was saved with BOM file settings which was adding a rougue\ufeff char to the beginning of my json reply!

Alan A
  • 2,557
  • 6
  • 32
  • 54

1 Answers1

0

The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.

$.ajax({
  type: "POST",
  data: dataString,
  url: "includes/register-user.php", 
  success:function(result){
     var result=JSON.parse(result);
     if(result.response==true){
       console.log("Success");
    }else{
      console.log("Failed!");
     }

  }, error : function(request, status, error) {

    alert("error"+ request.responseText);
}
});
Sarath Kumar
  • 1,136
  • 1
  • 18
  • 41
  • By removing the json type in the request the 'success' function fires, but jQuery compalins on an illegal char in the json repsonse, when I inspect I see *{"response":true,"message":"User successfully registered"} - note the star in front of the object which is red and when I hover I see \ufeff – Alan A Jun 23 '17 at 14:46
  • how is this possible: console.log(result.responseText); {"response":true,"message":"User successfully} so then console.log(result.responseText.message); 'undefined'. How is that even possible? – Alan A Jun 23 '17 at 15:05
  • refer this link:https://stackoverflow.com/questions/18029992/how-do-i-remove-a-ufeff-character-in-my-webpage-scripts for that * symbol – Sarath Kumar Jun 23 '17 at 16:07
  • @AlanA `console.log(result.responseText);`. It's `request.responseText` not response. – Sarath Kumar Jun 23 '17 at 16:09