IdealForms - javascript - post not working - javascript

onSubmit: function(invalid, e) {
e.preventDefault();
$('#invalid')
.show()
.toggleClass('valid', ! invalid)
.text(invalid ? (invalid +' invalid fields') : 'All good!');
if (!invalid) $.post('register.php', this.$form.serialize(), function(response) {
}, 'json');
}
This is my post function under .When I click submit the text 'All Good' comes but the page doesn't refresh or post the details to the register.php page.

You seem to be fundamentally misunderstanding how AJAX works. You're expecting the page to refresh, but the code you're using explicitly tells the page not to refresh. First, there's this:
e.preventDefault();
This does exactly what it says, it prevents the default event. Assuming this is on a form, it's explicitly preventing the form from submitting. Then you have your AJAX request:
$.post('register.php', this.$form.serialize(), function(response) {
}, 'json');
As you've confirmed in FireBug, this sends a POST request to the server. But... you're not doing anything with the response. Your function is empty:
function(response) {
}
So... what do you expect to happen? An empty function... doesn't do anything. You can confirm in FireBug whether the response is what you expect it to be, but that's an entirely separate issue. Whatever the response is, whether it's correct or not, isn't going to display on the page if you don't actually display it. Take a look at the examples in the documentation:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
The response is placed in the $(".result") element(s). In this code they're displaying the response. If you want to see the response, you have to display it somewhere as well.

Related

jQuery, how in read Wordpress Contact form 7 AJAX JSON response from another function

I'm using Wordpress Contact form 7 and want to customize its behavior. As I understand it uses jQuery form to submit a form and get response. I want to change it's 'success'/read behavior, to do that I need to know that r() function which is used by jQuery Form is executed and there was response from a server, perhaps I could read this response as well. But I can't figure out how I can find it is done, I know there is $.when function, but it does not help me, it does not see r(), perhaps it is located in another script and in another variable zone
(function ($, root, undefined) {
$(function(){
$(document).ready(function(){
$('.wpcf7-submit').click(function(){
//$(this).parents('.wpcf7-form')
//console.log( arguments.callee.toString() );
$.when( r ).then( function( data, textStatus, jqXHR ) {
alert( jqXHR.status );
});
//$(document).ajaxStop(function () {
// // 0 === $.active
//});
});
});
});
})(jQuery, this);
How can I find jQuery form is submitted? Can I read response from my function in another script?
$(document).ajaxComplete(function(e, xhr, settings) {
if( e.currentTarget.activeElement.className == 'wpcf7-form-control wpcf7-submit' ){
//console.log( xhr );
if( xhr.responseJSON.mailSent == false ){
var formID = xhr.responseJSON.into;
/////////////////////////////////// to do something
}
}
});
I think I found a solution via simple ajaxComplete, you can also put it Submit click event to avoid unnecessary checks. But I am not sure that will work find I mean ajax event will be handled before being actually sent. So I made simple ajaxComplete with a check of which element sends it and reading a response from a server. It works for me.

Unwanted redirect to POST url after successful ajax

I do a jQuery ajax POST which successfully delivers the correct data to the server.
After the POST is complete, the browser has redirected to the post url page... which I don't want. Neither of the alerts occur. The POST data has arrived at the server just fine.
i.e. after the ajax is performed within a page at http://myDomain/myPage.html as shown below, the browser address bar shows http://myDomain:39991/updateEnabled and no alerts have happened.
var enabledAjax = $.ajax({
url: 'http://myDomain:39991/updateEnabled',
method: 'POST',
data: $('#enabledForm').serialize(),
dataType: 'jsonp'
});
enabledAjax.done(function (msg) {
alert('done')
})
enabledStatus.fail(function (jqXHR, textStatus) {
alert('textStatus');
})
In express, i have router.post('/updateEnabled', urlEncodedParser, updEnab);
Within updEnab all I do at the moment is a console.log of req.body and res.end()
I've tried a 'success' method within the ajax params but that doesn't work either.
What am I doing wrong that is causing the redirect to the POST url?
hello when you submit form this is submitting normally so you need to use this.
event.preventDefault()
this will stop stop normal submitting of form.
To stop the redirection you can use the return statement like this:
enabledAjax.done(function (msg) {
return false;
})

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

Show user that the form was submitted successful or not

I have a form which sends data to a CRM. If I create a simple HTML form and send the data to the server it will refresh my webpage and show the text:
{"success":false,"error":{"message":"<whatever the error is>"}}
or
{"success":true,"result":"ok"}
After styling the form and integrating animations and validations and stuff everything still works perfectly. Now the data is sent by using http://jquery.malsup.com/form/#getting-started. The server receives it but the user has no idea whether it did or not.
Using this jQuery form plugin or some other plugin you might want me to use(or even code) please help me display text inside a div whether the operation was successful or not, depending on the server's response.
I have only tried to display the response using the examples provided here: http://jquery.malsup.com/form/#ajaxForm but I have failed until now.
Here I've put together a JSfiddle with some form fields and the jQuery form plugin I am using in order to send the data to the server: http://jsfiddle.net/n78p9/1/.
I hope someone will be able to show me what I did wrong or show me another way of doing this.
Thank you!
EDIT #Arun: so it looks like this:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: '.optional',
resetForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('Thank you for your message! Our team will contact you in the shortest possible time.')
}
});
}
I am definitely on the right way, but there is a problem: the error alert actually shows when the response is successful. I do not understand why. I have intercepted the POST request through a local proxy and re-sent it through the server and the server sent back this:
{"success":true,"result":"ok"}
But the script considered it an error. That is why I have inserted that text into the error:alert field:D.
What might be the problem?
Try using the callbacks provided by the library
var options = {
target: '#response',
success: showResponse,
clearForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('some error')
}
};
$('#contact-form').ajaxForm(options);

How to continue form submission after an AJAX call?

I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
var proceed = false;
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
proceed = true;
} else {
alert("Error: " + response);
proceed = false;
}
});
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return proceed; //breakpoint here makes the code run
});
});
The code is adapted from a WPSE question, which originally didn't work for me as the form didn't get submitted. I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. If there are errors, the alert is issued without a problem.
What is the best way to handle this?
EDIT
Based on #Linus answer below, the following code works with both valid and invalid data:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
if(jQuery(this).data("valid")) {
return true;
}
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
jQuery("#post").data("valid", true).submit();
} else {
alert("Error: " + response);
jQuery("#post").data("valid", false);
}
//hide loading icon, return Publish button to normal
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
});
return false;
});
});
Short answer: You can't - not in this manner.
Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.
So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.
This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.
EDIT:
Another way would be to set an attribute on your form, say valid, and in your submit handler check that:
jQuery("#post").submit(function() {
if($(this).data("valid")) {
return true;
}
// Rest of your code
});
And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:
$("#post").data("valid", true).submit();
EDIT:
You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.
Bind your button to a validation function instead of submit. If it passes validation, call submit().
Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. Set up your callbacks and go....
The real question is - why are you doing validation server-side? Why can't you load in the validation criteria before - as the post is being written? Then your validation can happen real-time and not on-submit.
jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out.
$.ajax({
type: 'POST',
url: ajaxurl,
async:false,
data: data,
timeout:3000,
success: function(){
}
});

Categories