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>";
}
DevNewbie
  • 69
  • 5
  • 2
    Well `` is simply _not_ valid JSON. – 04FS Oct 01 '20 at 08:58
  • I deleted this echo script. The error is the same, but now "at position 2". – DevNewbie Oct 01 '20 at 09: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.) – 04FS Oct 01 '20 at 09:09
  • damn, why is the content-type: text/html... any solution? or is this not the issue? – DevNewbie Oct 01 '20 at 09:11
  • _“damn, why is the content-type: text/html”_ - did you even say it should be anything else anywhere to begin with? And what is the actual content of the response body you got? – 04FS Oct 01 '20 at 09:15
  • 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 ` – Lapskaus Oct 01 '20 at 09:27
  • Does this answer your question? [Returning JSON from a PHP Script](https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script) – Dharman Oct 01 '20 at 11:04

1 Answers1

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);
  }
  });

RJCoder
  • 53
  • 9