How to avoid automatic page reload after XMLHttpRequest call? - javascript

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...

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.

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

Related

Window.onUnload inconsistently sends results to server

I am trying to have the user get an alert when they try to leave the page, and make a post request if they leave, if not, do nothing. Here is my code (using JQuery):
$(window).on("unload", function() {
$.post("/delete-room", {
roomID: roomId
});
});
$(window).on("beforeunload", function() {
return true
})
I (my servers) sometimes get the post request, but only about 1/5 times when I close the tab/unload the page. Is there a reason for this inconsistency? Thanks
Unfortunately making ajax call in an unload or onBeforenUnload event handler is not reliable. Most of the calls never reach the backend. Consider using sendBeacon instead.
$(window).on("unload", function() {
var formData = new FormData();
formData.append('roomID', roomId);
navigator.sendBeacon("/delete-room", formdata);
});
The browser will POST the data without preventing or delaying, whatever is happening (closing tab or window, moving to a new page, etc.).

Ajax reloads page instead of submitting the request

I have an Ajax script that causes the entire page to reload without ever submitting the URL for the request in the script. The server logs show the page URL as being re-submitted. Adding an alert demonstrates that the function is being run, but the embedded URL seems to be ignored. When used by itself, the request URL in the script returns the correct data.
Why isn't the embedded URL applied?
Another Ajax script on the same page works fine using a var named xhttp instead of xfiles so there's no conflict in that.
function rlist() {
var xfiles = new XMLHttpRequest();
xfiles.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("filelist").innerHTML =
this.responseText;
}
};
xfiles.open("GET", "/cgi-bin/cnc.cgi?precert~patients~rlist~813527153~0975184859230735~~6306919737~622156596S", true);
xfiles.send();
}
The objective is to refresh a small table of uploaded files. The responseText contains the table html with links. That can't be the issue here though since the URL is never submitted in the first place.
Swetank Poddar actually had the right idea... As it turns out, it was user error. I had left out the colon in javascript:void(0) and continuously overlooked it. So the Ajax was running correctly but the typo in the link was causing the page to subsequently reload. It was all so fast that it wasn't obvious and the database on the server showed the last processed hit as the link to load the page in the first place, which was the link to reload it as well.

HTTP Request effects URL

Everything works fine, it submits the data to the url, and the data gets put into the database just fine. The only problem I am having is the below code is on my index.php page, it submits the data to the submitusername.php page and everything works however after it submits the data to the submitusername page the url turns into "/index.php?username=blahblahblah" this isn't a major issue but it is something I would like to learn how to fix/what is causing it.
function submitUsername(){
var submitData = new XMLHttpRequest();
var username = document.getElementById('username').value;
submitData.onreadystatechange = function() {
if(submitData.readyState == 4 && submitData.status == 200) {
callback(submitData.responseText);
}
},
submitData.open("GET", "submitusername.php?username="+encodeURIComponent(username), true);
submitData.send();
}
Nothing in the code you've provided would have the effect you describe.
It sounds like you are trying to trigger the JavaScript when a form is submitted, but the form is submitting normally and loading a new page.
You need to prevent the default behaviour of the form submission.
Change your event handler function to capture the Event object and prevent the default behaviour, then make sure you are binding the event handler appropriately.
function submitUsername(evt){
evt.preventDefault
var submitData = new XMLHttpRequest();
and
document.getElementById('myform').addEventListener('submit', submitUsername);

Refresh form after save and close

I have some custom script that adds the latest note value to a hidden text field, and the hidden text field is subsequently displayed in one of my views for the entity. When I click save and close after adding a new note, the view does not update with the newest note since the form was not refreshed. What can I do so that the form will be refreshed if the user clicks on save and close?
EDIT: #Arthur For some reason, I cannot add a comment to your post.
Anyhow, I tried as you have suggested. When I tried to click on "save" alone, the form refreshed and the value returned was true, so the flag was tripped. However, when I tried the same with "save and close" the form did not refresh, and consequently the flag was not tripped. This is leading me to assume that I must refresh the form in order for the view to update.
EDIT 2: Here is the code that retrieves the information.
function GetLatestNote() {
var req = new XMLHttpRequest();
req.open("GET", encodeURI(Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/AnnotationSet?" + "$select=NoteText&$filter=ObjectId/Id eq guid'" + Xrm.Page.data.entity.getId() + "'&$orderby=CreatedOn desc&$top=1"), true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var note = JSON.parse(req.responseText).d;
var results = note.results;
var NoteText = results[0].NoteText;
var newnote = Xrm.Page.getAttribute("new_lastcomment").setValue(NoteText);
}
}
};
req.send();
}
new_lastcomment is the hidden field. What I am trying to do now is that if the user clicks on save and close, to stop the save event, reload the page, and use the script to close the form. Here is the code for that function:
function save(executionObj) {
var savestate = executionObj.getEventArgs.getsavemode();
if (savestate == 2) {
executionObj.getEventArgs().preventDefault();
window.location.reload(true);
Xrm.Page.data.entity.save("saveandclose");
}
}
What happens when I test this code however is that I get the following message when I attempt to save and close :
There was an error with this field's customized event.Field: crmForm, Event: onsave, Error: Object does not support property or method 'getsavemode'
However, once I click ok, the script closes and the view is updated as I want it! But now there is a problem because I do not want this error message popping up every time I hit save and close. To add more depth here, I run both of these function as an onsave event, and for the save function, I have "Pass execution context as first parameter" checked. I tried to run it without checking this box, and got an error that the value was undefined, but once again, after I clicked ok, the form would close and the view updated. Why is this error coming up now?
EDIT: #Arthur The form is now refreshing, but I am still getting the same error message that I was getting before.
Typically a "isdirty" flag gets triggered whenever there is a change to the form.
This flag lets CRM know that there have been modifications to the form in question, and to make sure to display the "There are unsaved changes" dialog box.
My guess is that this flag is not being tripped when you update the textbox.
if you put
console.log(Xrm.Page.data.entity.getIsDirty())
in your javascript and check out the resulting code, does it say true or false?
If it's false you'll need to set the dirty flag using
Xrm.Page.data.setFormDirty()
EDIT: I don't think this is the issue any more. refer to below.
After you set the value of the text box try executing this:
Xrm.Page.data.refresh(save);
That should save it, that way the save and close button doesn't have to.
After doing some research, I have found out what the issue was.
In my function GetLatestNote(), I was retrieving the data from the note field asynchronously. This may have resulted in the control returning to the user before the code was executed and the field was populated on the form. Therefore, this resulted in the information not being brought over when I clicked save and close.
Here is the code with the JSON code being executed synchronously, for those who may need it in the future. Works like a charm :)
function GetLatestNote() {
var req = new XMLHttpRequest();
req.open("GET", encodeURI( Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/AnnotationSet?" + "$select=NoteText&$filter=ObjectId/Id eq guid'"+Xrm.Page.data.entity.getId()+"'&$orderby=CreatedOn desc&$top=1"), false);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
req.send(null);
var note = JSON.parse(req.responseText).d;
var results = note.results;
var NoteText = results[0].NoteText;
var newnote = Xrm.Page.getAttribute("new_lastcomment").setValue(NoteText);
}
#Arthur thank you very much for trying to help me out. I truly appreciated it!

Call to xmlhttprequest from page onload event is not working OK when Back from another page

After going from my page to anther page by pressing a link, and than back to current page, than in call to xmlhttprequest from onload event, The js code of xhr.open and xhr.send is working, but the sever side code called by xhr is not running, and in xhr.onreadystatechange function the xhr.responseText is returning his old value.
In this scenario off comming back from another page, call to xmlhttprequest from document.onreadystatechange event is also not working OK.
The same code works OK when I call it from onload in the first page loading (before going to another page and returning), or when I call it from a button click.
Why the call to xmlhttprequest from onload event is not working OK when Back from another page?
I'm using Chrome.
Here is my code:
<script type="text/javascript">
function CallAJAX() {
xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = AJAX_onreadystatechange;
xhr.open("GET", '/MyPage.aspx', true);
xhr.send(null);
}
function AJAX_onreadystatechange() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('xhr.responseText=' + xhr.responseText);
}
}
window.onload = function () {
//alert is working also after going to link and than back to current page
alert('alert')
//Call to xmlhttprequest from page onload event - is Not working OK - after going to link and than back to current page
CallAJAX();
}
</script>
<!--here is the "link" mentioned in the above comment-->
link
<!--Call to xmlhttprequest from button onclick event - is working OK-->
<input id="Button1" type="button" value="button" onclick="CallAJAX();" />
Update
I found the problem:
In some browsers, and in some circumstances, xhr brought the xhr.responseText
value from browser cache, instead to call server.
Here is the solution:
This problem solved by adding unique query string param to url param of xhr.open. This guaranty that the ajax will avoid using the cache, and always hit the server, because with the unique param, the url is turned to unique in every call to xhr.open.
The unique value is produced by "new Date().getTime()" which returns the number of milliseconds between midnight of January 1, 1970 and now.
This is the solution code:
xhr.open("GET", '/MyPage.aspx?uniqueParamVal=' + new Date().getTime(), true);

Categories

Resources