Iman Yasmin
Iman Yasmin

Reputation: 447

Uncaught SyntaxError: Unexpected token in JSON at position 0

With some help, I have managed to make a form that validates and confirms user password before adding the user to the database. I have encountered some problem as the data of the user is not sent and giving me the following error :

Uncaught SyntaxError: Unexpected token in JSON at position 0
at JSON.parse ()
at Object.success (confirm3.php:29)
at i (jquery.min.js:2)
at at A (jquery.min.js:4)
at XMLHttpRequest. (jquery.min.js:4)

The error

at Object.success (confirm3.php:29)

is referring to this following line

var data = JSON && JSON.parse(response) || $.parseJSON(response);

The POST variable

$UserNm=$_POST["UserNm"];
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];

To make things clear, the data that should be returned is $ReturnMessage which is retrieved from stored procedure. $ReturnMessage will display the status of the operation for both successful and fail operation.

An example of $ReturnMessage :

"USER ID EXIST. (011 CODE)."
"USER ID MINT20 ADDED."

POST method is used : if(isset($_POST['Submit'])) {

$ReturnMessage :

 if(isset($ReturnStatus) && $ReturnStatus==1) {
 $ReturnMessage=odbc_result($stmt,'ReturnMessage');
 }
 }

 $ReturnMessage = utf8_encode ($ReturnMessage);
 echo json_encode($ReturnMessage);
 }

Script :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
  $("#myForm").on("submit", function(e) {
    e.preventDefault(); 
    var password = $("#UserPwd").val();
    var confirmPassword = $("#ConfirmPassword").val();
    console.log(password,confirmPassword)  
    if ($.trim(password) === password && 
      password !== "" && 
      password === confirmPassword) { 
      $.ajax({
        url: "confirm3.php",
        method: "POST",
        data: { Submit: "true" },
        success: function(response) {
          var data = JSON && JSON.parse(response) || $.parseJSON(response);
          alert(data);
        }
        });
        } else {
          alert("Please Enter Password Correctly");
        }
      });
});
<script>

I'm kind of confuse. Please guide me. Thank you.

Upvotes: 0

Views: 8267

Answers (3)

Joseph
Joseph

Reputation: 74

Use this in my case there was some null bytes so this i figured out and it fixed my issues.

var data3 = data.substring(data.lastIndexOf("{")+1,data.lastIndexOf("}"));
      count = $.parseJSON("{"+data3+"}");
      alert( count.firstname ); // firstname is the key so you can use anything to test it.

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146390

First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.

All the phases where you can do so, in chronological order:

  1. Report data type from web server. If you happen to be using Apache:

    <Files "confirm3.php">
        ForceType application/json
    </Files>
    
  2. Report data type from PHP:

    header('Content-Type: application/json');
    
  3. Tell jQuery that you expect JSON:

    url: "confirm3.php",
    method: "POST",
    dataType: "json",
    data: { Submit: "true" },
    success: function(response) {
        console.log(data); // Already decoded (don't use alert to debug!)
    }
    

You can certainly omit almost any step, but not all.

Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.

Upvotes: 1

Konda
Konda

Reputation: 78

Have you set your content-type in your php?

header('Content-Type: application/json');

Also you don't need to put "true" in quote marks, when the json gets to your php script, once you run json_decode, php will recognise it as a boolean.

Upvotes: 1

Related Questions