简体   繁体   中英

Ajax can't send data to php as json without error

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM