only submit the page is ajax was successful - php

I am sending an email in jQuery and PHP, i need to tell the page to submit if the ajax was successful and don't submit if not.
I have tried to place the return values in the success and error attributes, but that did not work, so i want to see if i could set the form to not send by returning false but if it was successful letting it submit the page for some server side work.
In the example below i have tried to set a variable and used a conditional to read it. I get an error message because the value does not seem to get passed globally, so when the conditional reads sendMe, it says it is undefined.
Is there a way to do this correctly?
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
var sendMe = 'true';
},
error: function(){
alert('Error: Message could not be sent');
}
});
if (sendMe == 'true'){
//Submit the page...
}
else {
return false;
}

just create a sendMe() function, and call that function from success:
That should do the trick.
The reason your code does not work is because the javascript is not waiting for the ajax call to come back, right after the ajax call it evaluates sendMe which at that point is still false.
You could consider doing this call synchronously of course to prevent that, but I am not sure that is the right way to go. ( async : false is deprecated as of jQuery 1.8 )

When is your conditional
if(sendMe == 'true') ...
ever getting called?
make a little function like this:
function sendMe(){
// whatever your form's id is, put it in place of myForm
$("#myForm").submit();
return true;
}
and in your ajax success block call the function

Try using this setup:
var form = this;
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
form.submit(); // submit form, bypassing jQuery events
},
error: function(){
alert('Error: Message could not be sent');
}
});
return false; // prevent submit
By returning false after the ajax request, we prevent the submit, then we directly submit the form bypassing all of jQuery's submit handlers using form.submit();

Set the form to go through a validator method on submit event:
<form onSubmit='return checkForm();'>
</form>
In this method - checkForm() - perform your ajax post normally. If the ajax post returns as 'success' proceed with the submit else use return false; to cancel submit and notify the user accordingly.

Related

JQuery validate plugin, ajax submit

I am using JQuery validate on two fields. I do all my validation and display messages if validation fails. I then have my submit handler which is using Ajax
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType : 'json'
})
.done(function (response) {
if (response.success == 'success') {
alert('success');
} else {
alert('fail');
}
});
return false;
}
My problem is that both fields are not required, only one or the other (or both). I have handled this no problem. However, the submitted data will be sent to my PHP file using Ajax. In this PHP, I check to see what fields have data e.g.
if (isset($_POST["mobileNumber"] && !empty($_POST["mobileNumber"])){
var_dump("WORKING");
}
I then need to check the input against a web service API. If I do this seperately, it is not a problem. However, if both inputs are entered into the form, I then need to make 2 API calls to 2 different APIs (each input uses a different API), and then return the response for both back to .done. Once again, if only one input is provided, I dont see a problem. The thing I am wondering about is if both inputs are provided, and how I can return both response?
Any advice appreciated.
Why don't you send both the responses of the API calls back in one response?
$response = array();
if (isset($_POST["mobileNumber"] && !empty($_POST["mobileNumber"])){
$response['mobileNumberResponse'] = array('success'=>true,'data'=>array());
}
if (isset($_POST["secondParameter"] && !empty($_POST["secondParameter"])){
$response['secondParameter'] = array('success'=>true,'data'=>array());
}
echo json_encode($response);
Or something similar. If this isn't an option send two ajax's requests if both parameters are present.

How can make sure code after my ajax request only runs if the request was a success?

I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}

Receive data on php file send by jquery function

I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/

Ajax request goes to new page instead of updating current page?

It was working before and I do not remember changing anything. I have a form and it sends the info to a "processing" php file and should get a response back. Instead, it just goes to the "processing" php and echoes the JSON data on a new page. Jquery is including from google and the form page and "process" page are both in the same directory.
$data = array(
'status' => $status,
'message' => $errorMsg
);
echo json_encode($data);
if ($status == "success"){
session_destroy();
}
exit();
So that is what it does at the end of all the processing (making sure data is good and all that which works just fine). This is the javascript used:
$(document).ready(function(){
$('#signupForm').submit(function(){
//various client side checks to keep form from submitting easy to see garbage
if($(this).data('formstatus') !== 'submitting'){
var responseMsg = $('#response');
responseMsg.hide()
.addClass('response-waiting')
.text('Signing Up...')
.fadeIn(200);
var dataString = //the data
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(data) {
var responseData = jQuery.parseJSON(data),
messageClass = '';
switch(responseData.status){
case 'error':
messageClass = 'response-error';
break;
case 'success':
messageClass = 'response-success';
break;
}
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(messageClass)
.text(responseData.message)
.fadeIn(200,function(){
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(messageClass);
});
},5000);
});
});
}
});
}
return false;
});
})
If there is something specific I should look for please let me know and I will update. qand like I said, I had it working (yesterday) and I do not remember changing anything except taking out a client side check at the top which I know should not matter at all.
A few things might help is solving this.
The first is that it's recommended not to use return false to stop usual on click events from happening.
It's best practice to at the top of the function do
preventDefault();
see http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
This should stop the form from submitting and therefore loading the post page instead of doing the ajax call.
The second issue is that you have a return false call which is obviously not being hit. The above fix will stop the form from submitting no matter what but I'd guess that you have a javascript error in the code between the start and the return false. This will throw an exception and therefore return false will never be called. Once the above fix is put in and it stops redirecting, check your console in your browser for the exception.
Cheers
I assume your form action is heading process.php and you are not returning false on submit.
It should be like this
<form name='myForm' action='nonjspage.php' method='post' onsubmit='return false;'></form>
If the error still continues, then its not your form but an error in the javascript. Depending on what browser you are using there is an error console.
In firefox you head to the menu -> web developer -> web console.
Once you have opened this, reload the page and press the submit button again, it should give you information about your javascript error.

How stop an HTML form from submitting if user is not signed in, but allow submit if user is signed in?

In my app, a user must be signed in to submit form info.
After a user clicks on the form submit button, my jQuery checks if a user is signed in.
If not signed in, then an error message pops up, requesting sign in/up.
I can now successfully stop the default action (submit).
However, how do I also allow the default action if the user is already signed in?
With my current code, the default action is also blocked if the user is signed in.
Here's my code:
jQuery('.member-only').click(function(event) {
var $element = jQuery(this);
var SignedIn;
jQuery.ajax({
type: 'POST',
url: '/ajax/member',
dataType: 'json',
success: function(data) {
var $err = jQuery('<div></div>')
.addClass('member-check')
.html(data.msg)
.css('left', $element.position().left);
SignedIn = data.SignedIn;
if (!(data.SignedIn)) { // not signed in
$element.after($err);
$err.fadeIn('slow');
return false;
}
}
});
jQuery('.member-check').live('click', function() {
jQuery(this).fadeOut('slow', function() {jQuery(this).remove(); });
});
if (!SignedIn) {
event.preventDefault();
event.stopImmediatePropagation();
return false; // block default submit
}
});
Thanks.
You need to let your JS function return false; to block the event's default action.
However, this doesn't cover users who have JS disabled or are capable to spoof it. So you should handle this gracefully in the server side as well :)
Update: As per your update, please add
alert(typeof Signedin);
alert(Signedin);
right before if(!Signedin) and tell what you get for both cases. It might be of the wrong type and/or value which is causing that you're always entering the if block and thus always returning false.
For example, a type of undefined will always cause !Signedin to evaluate true. You'd like it to be a boolean type all the time with values true or false.
This is a Moo question. Your not loged in user should have never seen a form that he can't submit in the first place.
Fix your PHP so as to not write a form that a non-logged in user can't submit.
$(form_id).submit(function(){ //triggered when user submits form
var signed_in = check_if_user_is_signed_in(); //checking
if(signed_in){ //singed in
//Do stuff
return true; //submit form
} else{ //user not signed in
//Do stuff
return false; //prevent form from being submitted
}
})
See if there is any user logged in . keep a flag for it. If flag is not set just disable the submit button . or just set the form action part using jquery only if flag is set.
Use event.preventDefault(); in your event handler. Return false only works in some cases (it's more of a workaround).
http://api.jquery.com/event.preventDefault/
https://developer.mozilla.org/en/DOM/event.preventDefault
I would also add an ajax request to check if user is logged in if your website often is opened in multiple windows.
Please review my modifications to your code. Let me know the datatype of the returned data.SignedIn; I added a console.log to return it to firebug.
My example takes action on the document being ready, as opposed to waiting for the user to interact, thus preventing the usability problem of showing the user that an ansynchronous call is happening in the background (the ajax spinner):
$(document).ready(function($){
var memberStatus;
jQuery.ajax({
type: 'POST',
url: '/ajax/member',
dataType: 'json',
success: function(data) {
console.log(data.SignedIn) //I need to know what format this is returned (Boolean: True/False?)
memberStatus = data.SignedIn;
}
});
if (memberStatus) { //if true, that means they are a member
//draw member box
} else {
$("#submitButtonID").attr('disabled',true);
}
});

Categories