Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid automatic page reload after XMLHttpRequest call?

I know this is a bit paradoxal because XMLHttpRequest shouldn't be reloading the page, and it's the whole point of it.

Tried in Chrome latest version, Safari on iOS and on an Android. All same result.

I am sending a form through it, with files. Works great, the destination site receive correctly the data, and displays it. Sends back a 200, "OK". (It's facebook)

But then my page reloads automatically. Just like if I submitted the form using HTML form and a submit button. (Which was my original problem)

Here is how I do it, from Javascript

// Get the form element
var formData = new FormData(document.getElementById("photosubmitform")); 

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/' + facebookWallId + '/photos', false);
xhr.onload = function(event)
{
    var json = xhr.responseText; // Response, yay!
}
xhr.send(formData); // Sending it, will reload the page on success...
like image 244
daivuk Avatar asked Jan 08 '13 21:01

daivuk


2 Answers

Any chance you're triggering this by submitting a form? If you don't return false in the onsubmit handler, the form will still be submitted.

like image 169
James Mason Avatar answered Oct 14 '22 17:10

James Mason


Use event.preventDefault() when observing button click in your form.

like image 24
oleq Avatar answered Oct 14 '22 16:10

oleq