jquery ajax calls are causing a page refresh - javascript

I have a button in my HTML page which is not part of any form.
<input type='button' id='submitter' value='add'/>
I have a click handler on it:
$('#submitter').click(function(e) {
e.preventDefault();
e.stopPropagation();
var args={}
$.get('notexists.php', args, function() {alert('what?');}, 'json')
.error(function(){ alert('error'); });
return false;
}
Now, notexists.php does not exist, so the click should alert error. But for some reason, The page refreshes with I click the button!
Some experiments I've tried to identify the problem:
removed everything from the handler (no return false, no prevent default, no stop prop, no jquery post call - nothing) - the page did not refresh on click, and it should not. the button is not a submit button, and it dont belong to no form.
removed teh $.post call - no refresh
enabled the firebug's "break on error" feature and tried clicking - refreshed again. so there is no error.
changed the post URL to something that exists and works - still refreshing
added an "alert" after the $.post call - it did not get called. Seems like the execution breaks at $.post, but there's no error (experiment 3).
changed the input to a "div" with the same id. Same results - page gets refreshed.
Can anyone help?
PS: I'm using $.post in MANY other parts of this app, and its working as expected everywhere.

Have you checked $('#submitter').length when you attempt to bind the event? Maybe you have duplicate id's in the dom? Have you got your script running before the closing body tag or inside a jquery doc ready block?
Posting a fuller code sample would help to eliminate the questions I pose.

I believe your selector isn't selecting the button, so the event handler is not being applied.
Test your selector by doing something like:
$("#submitter").val('Test');

Related

JavaScript code not waiting til page loads after button click

I am trying to fill out a form and click submit and then I need to wait until the next page loads and continue working with elements. It seems like the code after the button click happens before the next page appears and the DOM has loaded. I've tried to use a while loop to check the readyState but that doesn't seem to work either. Any suggestions? Here is an example of what I'm trying to do assuming I have the submit button element in variable submitButton.
I've tried to use a while loop to check the readyState but that doesn't seem to work either. Any suggestions? Here is an example of what I'm trying to do assuming I have the submit button element in variable submitButton.
submitButton.click();
var errors = document.getElementsByClassName('error'); // Should be done after new page load
if (errors.length > 0)
{
console.log("There are some errors");
}
Assuming there will be some errors on the next page, there should be a message printed out, but this doesn't happen.
You can use window.onload()
Just pass a function thaz does what your script is currently meant to be doing
The function will be called when the page is loaded so you can use it to implement the functionality you want
encapsulate the whole code inside function i write but for this you would need the jquery
$( document ).ready(function() {
//Your code here
});
For refrence
Document Ready function jquery

jQuery only ignoring a click trigger during a trigger chain

I have the following code:
$( "#check-button" ).on( "click", function() {
$("#button_cart").click();
$('.checkout-button').click();
});
I have this jQuery click event. What I want to do is, on clicking the check-button, the first line inside the function is updating the cart (which reloads the page) and then the second line inside the function is the checkout button, which takes me to the next (checkout) page.
But here only the first event is firing. Is this because the page is reloaded on "button-cart" clicking? How do I solve it?
That's correct. The second click actually could be working but in some kind of limbo between the click and the load and you wont see it.
The solution is to "handle" the reload event, I put it between "" because this event can't be handled ( as far as I know) but you can make some hacks.
First, why is reloading the page? Are you adding new content?
In this case just call the click in the content added with a load handler like $(document).ready();
Here is how i did it: Using localstorage.
Just saved the value of someVariable on check-button click ( along with button-cart click) and on page reload i checked if the value is set. If it is set, i unset it and clicked the next button.
Here is the link
This was really great help from SO. Thank u SO

Session can't be updated when trigger button used jquery and ajax

when i click on a button that tries to modify the session's value on serverside, it runs very well:
$('#btn1').click(function() {
update_session('session.php?session=1');
});
But when i tried to trigger this button from another button:
$('#btn2').click(function() {
$('#btn1').click();
});
At that moment, the session isn't changed. I really don't understand because i saw in firebug that there was a POST to server by ajax with the correct arguments.
The problem may be caused by the fact that .click() does not execute the href attribute of an anchor tag.
Having it this way should work:
var clicked = function() {
update_session('session.php?session=1');
};
$('#btn1').click(clicked);
$('#btn2').click(clicked);
If it didn't work it is very likely a server side problem (as suggested by Oriol).

Javascript function does not complete

I am writing a JavaScript function to close a fancybox on the submission of the form located in the fancybox. Here it is:
function closeFancyBox() {
$.fancybox.close();
$('#calendar').fullCalendar('refetchEvents');
}
It's triggered in this way inside the fancybox:
$('form').submit(function() {
parent.closeFancyBox();
});
Here's the thing: the fancybox is closing correctly, but fullcalendar is not refreshing the display. When I call closeFancyBox(); from the console, though, it works and fullCalendar refreshes. I'm stumped here.
EDIT:
Per danronmoon's suggestion, I added a breakpoint after the $.fancybox.close(); call and checked what $('#calendar') returned... it returned a div element, as expected.
You are submitting the form so obviously it will redirect to another page so unless you stop the redirect from happening you will not see all your code work.
$('form').submit(function(e) {
parent.closeFancyBox();
// run either of the following.
e.preventDefault();
return false;
});
I am still not sure what caused this, but I did manage to 'fix' it by moving the call to fullCalendar's refetchEvents to the fancybox afterClose hook.
So in short, this fixed the symptoms, but I don't know what was causing the underlying problem.

Add data from form field to table on page without refreshing whole page

Most of the stuff I see on this site refers to adding information to a div from php. I just want to take a user's input, add it to a table dynamically and have it displayed in the div as the click the submit button.
I'm not doing anything where the data gets posted to a database, no php, etc, at this point.
I have the JQuery to run the dynamic add to the database as well. It works, but I have to use a breakpoint in the javascript to step through and see the entered data added to the row....issue is when that function is done, the page refreshes, and all data is gone.
I need a way to add the data to the table in the div without the page refreshing and clearing all of the other data each time.
Imagine parent information in one div, and child information being added in another div. As I add each child piece, I don't want the parent information to be removed, and in fact want it to remain as "editable" information.
------------------------------------------ Edit ----------------------------------------------
Below is the code I'm now using based on suggestions, but I obviously don't understand completely, because it hits the event handler for the click, but then doesn't get inside the function, just jumps back out, and never hits my other breakpoints inside there.
---------------------------------------Final Edit ----------------------------------------------
I finally pulled my head out of my backside and paid attention to what Charlie was telling me, and got this...and it works when I call the function from the onClick event. I couldn't get the event to bind to the button click, but that may be because I was using the tag instead of the setup.
function(addNoteRow){
event.prevent.Default();
var noteTxt = $('#noteEntry').val();
var noteEntBy = 'BGM'
noteEntDate = (Date());
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("TBODY").item(0);
row=document.createElement("TR");
cell1=document.createElement("TD");
cell2=document.createElement("TD");
cell3=document.createElement("TD");
textnode1=document.createTextNode(noteEntDate);
textnode2=document.createTextNode(noteEntBy);
textnode3=document.createTextNode(noteTxt);
cell1.appendChild(textnode1);
cell2.appendChild(textnode2);
cell3.appendChild(textnode3);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
tabBody.appendChild(row);
}
You mentioned you're using jQuery, so I will in my example to make this easier.
$('#submit_button').click( // Bind an event handler to the submit button
function(event){
event.preventDefualt(); //This is necessary if you are using a an submit button input element as normal behavior is to submit the form without ajax causing the page location to change. Event is automatically passed in, and we can call preventDefault() on this object to stop the browser from navigating away from our page.
$.ajax({
url:'http://youserver.com/script_that_will_respond.php', //Give the ajax call a target url
data: $('#user_input').val(), //Supply some data to send with the request,
success: function(data){ //Supply an anonymous function to execute on success. The parameter will be the response text.
$('#your_result_div').html(data); //On success of the ajax call, put the response text into an html element on your page
}
});
}
);
jQuery's ajax method has a lot of settings. This is a pretty bare-bones example.
You can read more about the various options here: http://api.jquery.com/jQuery.ajax/
Edit: I may have misunderstood. If you do not need to reach a server, and want to do this all locally, it is simpler.
$('#submit_button').click( // Bind an event handler to the submit button
function(event){
event.preventDefault();
/*
We have to call this method on the event object bacause deafult behavior
of a subnmit button is to submit the form, causing the browser to go to a new page.
*/
var text = $('#some_input_element').val(); //Store the value of a text input in the variable text
$('#your_div').html(text); //put the contents of the variable text into the "your_div" elemnt.
}
);
try AJAX for partially refreshing portions of page like div etc.
http://api.jquery.com/jQuery.ajax/

Categories