Ajax with Jquery - Callback not executing - javascript

I have tried so many things, cannot figure this out, I am using this code, and I know that the start is working, because the script it connects to sticks some info in the db, but the callback never runs.
<script type="text/javascript">
$(document).ready(function() {
$(document.body).on('click', "#reply_submit", function() {
var formData = $('#reply').serialize();
$.post("newpost.php",formData, function(data){
alert("hi");
}, "json");
});
});
My form's id is "reply" and the button I am using to submit it is "reply-submit", just to make sure those things are clear.
It also doesn't work if I remove that last "json" thing btw.

If you read the docs for jQuery.post(), it says this about the callback:
success(data, textStatus, jqXHR)
A callback function that is executed if the request succeeds.
If it's not getting called, it means that request did not succeed. There is probably an error in newpost.php (sometime after the data insert, but before it would normally exit).
You can also catch error conditions by using the long-form jQuery.ajax() instead of the post shorthand:
$.ajax({
url: 'newpost.php',
data: formData,
type: 'post',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error!');
}
});

When you click, the form is also being submitted the standard way. Modify your click handler like this:
$(document).on('click', "#reply_submit", function(e) {
e.preventDefault(); // prevent the default submit event
var formData = $('#reply').serialize();
// ...
});
Although I think document.body should be a valid node to wrap in jQuery, I've also modified it to the more commonly used document.
On that note, if the form is never destroyed by an Ajax event or other DOM modification, you could bind to #reply instead of document (or body).

I'm simply assuming that you want to submit a form without reloading the whole page.
Based on that assumption, following code will serve the purpose.
$(document).ready(function(){
//on form submit event
$('form#reply').submit(function(){
$.post('newpost.php',$(this).serialize(),function(){
alert("Message or do something with the response data if you are expecting one");
});
//prevent default action
return false;
});
});
Please ignore the post if this is not the functionality you are looking for in your project.

Related

Autosaving textarea field in jQuery [duplicate]

This question already has an answer here:
JavaScript jQuery delay oninput
(1 answer)
Closed 3 years ago.
I would like to request some help in saving data from a "notepad" using Ajax. The notepad in my case is a simple textarea for which we can capture an onchange event.
HTML
<textarea id="notepad"></textarea>
jQuery
$('#notepad').on('change paste keyup', function(event) {
var formData = $(this).serialize();
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function(data, status) {
console.log('Something worked');
},
error: function(xhr, desc, err) {
console.log('Something went wrong');
}
});
}
The above code works perfect for what I need to do. However, in practice I found that the above code is not perfect for this scenario, since a lot of content would go through this textarea having an ajax call for every keyup / change is a lot of Ajax and MySQL calls.
I wanted help in figuring out how I could somehow trigger the Ajax call only after the change in text is completed. My first instinct was to add a delay to the ajax call, but that would still mean many many ajax calls after a set number of time.
Is there any way for me to completely hold of Ajax calls until the very end? That is maybe 5 seconds after the user has finished adding content to the textarea?
Note: Adding a submit button is not an option sadly.
Try changing which events you're listening for via jQuery. 'change paste keyup' are all different events. Try taking 'keyup' out and leave the other two.
That's the simplest answer.
Another more complicated option is to add a timer that delays the ajax until a certain amount of time has passed.
$('#notepad').on('change paste keyup', function(event) {
var formData = $(this).serialize();
setTimeout(function(){
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function(data, status) {
console.log('Something worked');
},
error: function(xhr, desc, err) {
console.log('Something went wrong');
}
});
}, 3000);
}
Two notes: I left the formData variable outside the timeout because "this" will not function the same inside an anonymous function. (Another option would be to save "this" to a different variable, then serialize your form data inside the timeout.)
var thisForm = $(this)
setTimeout(function(){
var formData = thisForm.serialize()
Finally, the "3000" is the time in MS after the event fires that the timeout will take to trigger.
Also--use const or let instead of var. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)

Firing click event before ajax call

I have an ajax call on click of anchor tag in WordPress and I have not control over this. But before this ajax call I want to fire click event.
This click event is firing sometime but not every time. So I am not getting consistent results. Is there any way so that I can get correct results and get this click event fire before ajax call. I have tried putting my code in header and in footer as well.
Here is my code that i am using for click event.
jQuery(document).ready(function(){
jQuery("#addbtn").click(function(){
});
});
Any suggestion about this will be much appreciated.
you can use befor beforeSend
This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
source: https://api.jquery.com/Ajax_Events/
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
/*using a loader while waiting or fire an event or execute a function */
},
success: function(data) {
//execute a function on request sucess
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
},
complete: function() {
//execute a function once the call completed
}
});
I hope this will help you slove the issue

event.preventDefault(); not working in ajax

I am firing an ajax call on a signup form wherein i am checking whether the email id entered by the user has already been used or not.
Ajax Function :
<script>
$( "#becomesignup" ).submit(function( event ) {
$.ajax({
url : 'login', // Your Servlet mapping or JSP(not suggested)
data : {"email":$("#becomeemail").val()},
type : 'GET',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
if(response == "true"){
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
event.preventDefault();
}else{
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
}
$('.black-screen').hide();
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
</script>
In the above ajax function, if the response is true then the email id is already been used and i need to show an error div($('#emailerrorbecome').slideUp();) and then prevent the form to get submitted. But even event.preventDefault() is not working causing the emaild id to be registered again.
Please help me with this. TIA
You should submit the form programatically and always preventing default behaviour in jq submit handler. E.g, using context and calling submit() DOM API method:
$("#becomesignup").submit(function(event) {
event.preventDefault(); /* prevent form submiting here */
$.ajax({
context: this, /* setting context for ajax callbacks*/
url: 'login', // Your Servlet mapping or JSP(not suggested)
data: {
"email": $("#becomeemail").val()
},
type: 'GET',
dataType: 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success: function(response) {
if (response == "true") {
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
$('.black-screen').hide(); /* hide it here */
} else {
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
this.submit(); /* 'this' refers to the FORM, and calling submit() DOM native method doesn't fire again jq handler */
}
},
error: function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
For explanation of the why, see Quentin's answer
You cannot prevent the submit long after the submit function has returned. The Ajax result occurs much later.
You can instead flag the submit (e.g. use a sentinel variable) and cancel it unless allowed. Then trigger a submit from code in the Ajax callback.
Example:
var allowSubmit = false;
$( "#becomesignup" ).submit(function( event ) {
if (!allowSubmit){
$.ajax({
url : 'login', // Your Servlet mapping or JSP(not suggested)
data : {"email":$("#becomeemail").val()},
type : 'GET',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
if(response == "true"){
$('#emailerrorbecome').slideDown();
$('#become-submit').prop('disabled', true);
// Enable next submit to proceed
allowSubmit = true;
// And trigger a submit
$( "#becomesignup" ).submit();
}else{
$('#emailerrorbecome').slideUp();
$('#become-submit').prop('disabled', false);
}
$('.black-screen').hide();
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
// return false does e.preventDefault(), and true allows it to proceed
return allowSubmit;
});
You are calling preventDefault to late.
Order of execution is this:
Event handler fires
HTTP request is sent
Event handler finishes
Prevent Default was not called so the default behaviour occurs
HTTP response is recieved
Success handler fires
Prevent Default is called … too late to have any effect
You can't wait for the HTTP response to come back before preventing the default behaviour.
You either need to always prevent the default behaviour and then conditionally resubmit the form with JS in the submit handler, or move the logic for when you use Ajax to perform your tests so it doesn't depend on the form submission event in the first place (e.g. run it as soon as the data has been entered and be prepared for the possibility that the form might get submitted before your JS has finished running).
you can make use of return false instead of eventPreventDefault.
I had been using the location.reload() as a dirty hack to refresh the page to prevent submission, but return false works well even without a refresh, it doesn't submit the form.

jQuery: ajax call not executed on form submit event unless I have a alert call after it?

I'm doing some modifications to an existing form on web application. I can't have access to the form's code, but I can add scripts to the page, so I'm doing some customizations with the help of jQuery.
So, right now I have something like this:
jQuery( "#new_user" ).submit(function( event ) {
event.preventDefault();
var fullname = jQuery("#user_name").val();
var email = jQuery("#email_primary").val();
var company = jQuery("#contact_customer").val();
jQuery.ajax({
async: false,
dataType: 'jsonp',
url:"https://server.com/script.php",
data: {"fullname": fullname, "email": email, "company": company},
success: function(response){
alert("json says " +response.res);
}
});
alert("hello");
});
Now, this works fine. I'm basically intercepting the form submission.
Problem is, the ajax call is only executed if I keep the alert() call in there, something obviously I do not want, it's just for debug. If I remove the alert() call, the form will submit but the ajax call will not work as it should. I have access to the web server that is supposed to receive the JSONP request, and it doesn't even get there.
The second alert actually never gets executed, but actually I don't need anything there, I just need to receive the GET on the webserver.
I have tried to add async:false to ajax() options, but no luck.
I'm a bit puzzled, and researched/experimented about it quite a bit. any tip appreciated, thanks in advance.
You have to prevent the form from submitting, otherwise the ajax request will be cancelled
jQuery( "#new_user" ).submit(function( event ) {
event.preventDefault()
jQuery.ajax(...);
alert("hello");
});
And you wanted to submit the form on ajax success, right?
jQuery( "#new_user" ).submit(function( event ) {
event.preventDefault()
var self = jQuery(this);
jQuery.ajax({
async: false,
dataType: 'jsonp',
url:"https://server.com/script.php",
data: {"fullname": fullname, "email": email, "company": company},
success: function(response){
alert("json says " +response.res);
self.submit();
});
});

After submit make ajax call!

I won't to write some values into database with ajax on submit event, after that I want to query the database (with ajax) once again to check for some response that will be written after the first ajax action. Last, if the response values are "ok" then I want to refresh the page, else I will make the query 2 secs latter till the response gets ok!
//Write into database form values on submit event
$('form').submit(function(){
$.post("submitForm.php", { "array": submitedArray});
//HOW to verify if submited values where well written into databse?
return false;
});
//ONLY after submit I want to query the database and based on the response values I will refresh the page every two seconds (if response values not good) or refresh only once (if values checked are good)
var refresh = setInterval(function(){
$.getJSON('someOtherScript.php', function(data){
$.each(data, function(index, value){
//Check values
});
});
}, 2000);
onComplete: function(){
setTimeout(function() {$("#ajaxResponse").fadeOut();}, 500);
}
Write this in your ajax function and that's it. It worked for me.
If I have this correctly, you are using ajax to submit the form and want to do the check on callback.
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// This is where you will do your get request to find the result you are looking for.
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Definitely don't use setInterval. setInterval will have that code execute EVERY 2 seconds, not just after 2 seconds. What you were looking for is setTimeout. But don't use that either.
have a look at
http://api.jquery.com/jQuery.post/
post can take a success parameter. This will let you run your 2nd bit of code only after the first completes.
Why not just have the initial submit code check the database write, if successful it returns a success code, otherwise it returns an error code. Either you trust ajax or you don't.

Categories