0

When I want to send data as datatype json it response this error: SyntaxError: Unexpected token < in JSON at position 0

When I tried to send the data as datatype text, it sends the data to php successfully but my php wont respond.

ajax/js as datatype json:

let form = $("#form");

$("#form").on("submit", function(e) {
                          
  e.preventDefault();
                          

  $.ajax({
    url: "test.php",
    method: "POST",
    dataType: "json",
    data: {
       test: 1
    },
  success: function (r) {
    console.log("!!!");
  },
  error: function(jqXHR, textStatus, errorMessage) {
    console.log(errorMessage);
  }
  });

});

ajax/js as datatype normal:

let form = $("#form");

$("#form").on("submit", function(e) {
                          
   e.preventDefault();
                     
   $.ajax({
      url: "test.php",
      method: "POST",
      data: form.serialize(),
      success: function (r) {
        console.log("!!!");
      },
      error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage);
      }
   });

});

php code:

if(isset($_POST["test"])){
   echo "<script>console.log('works');</script>";
}
7
  • 2
    Well <script>console.log('works');</script> is simply not valid JSON. Commented Oct 1, 2020 at 8:58
  • I deleted this echo script. The error is the same, but now "at position 2". Commented Oct 1, 2020 at 9:05
  • 1
    Well then your script must still be responding with something, that isn’t valid JSON. First of all, check what the response actually was, using your browser dev tools (network panel.) Commented Oct 1, 2020 at 9:09
  • damn, why is the content-type: text/html... any solution? or is this not the issue? Commented Oct 1, 2020 at 9:11
  • 2
    dataType sets the Data Type for the response Object, so your ajax call expects a json object back from your PHP, but you echo some <script> String. try something like echo json_encode(['myVar' => 'myValue']); Commented Oct 1, 2020 at 9:27

1 Answer 1

1

Try this

var ob = {
       test: 1
    };
$.ajax({
    url: "test.php",
    method: "POST",
    dataType: "json",
    contentType: 'application/json',
    data:JSON.stringify(ob),
  success: function (r) {
    console.log("!!!");
  },
  error: function(jqXHR, textStatus, errorMessage) {
    console.log(errorMessage);
  }
  });

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.