PlayerWet
PlayerWet

Reputation: 419

I can not post content to php through ajax with javascript

I have a problem when sending post content to a php file via ajax. My intention is to send an object that contains the data that will be used in the file save.php and it has to process the response so that it appears in an alert window.

var iden = true;

var object = {

    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

var xhr = new XMLHttpRequest();
xhr.open('POST', "save.php", false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send( object);

if (xhr.status == 200) {
    xhr.onload = function () {
        alert(this.responseText);
    };
} else {
    alert('error');
}

The problem is that when trying to send the data I get this message in console:

Test.js: 56 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Line 56 corresponds to:

Xhr.open ('POST', 'save.php', false);

If I set the async parameter to true, it jumps the else from the conditional if (xhr.status == 200) and displays the error alert.

Where could the problem be?

Also say that with jquery it works perfectly, but I would like to do it with Javascript.

With jquery:

$.ajax({
    url: "save.php",
    type: "post",   
    data: object
}).done(function(data) {
    alert(data);
});

EDIT:

console.log(xhr);

XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: function…} onabort : null onerror : null onload : null onloadend : null onloadstart : null onprogress : null onreadystatechange : function () ontimeout : null readyState : 4 response : "" responseText : "" responseType : "" responseURL : "http://localhost/save.php" responseXML : null status : 200 statusText : "OK" timeout : 0

Upvotes: 0

Views: 176

Answers (1)

xsami
xsami

Reputation: 1330

Try changing this line of code: xhttp.open("POST", "save.php", false); and set the third parameter to true. And follow this example if it can work.

var object = {
    'titulo': 'In the mountain',
    'dest': 'Single of',
    'edit': true,
    'previ': 'yes',
    'iden': iden
};

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("POST", "save.php", true);
  xhttp.send(object);
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

Upvotes: 3

Related Questions