AJAX Complete Response - php

I have a password change function on my site and everything is done now, except I want to display a success or fail message. So here's my html:
<form id="change_Pass" action="" method="post">
//stuff
</form>
<fieldset id="response_field_pass" style="display:none;"><p style="color:black;"></p></fieldset>
And my jquery:
$('#change_Pass').submit(function() {
if(pass_val.form()) {
$.ajax({
type: "POST",
url: "script.php",
complete: function(data) {
$('#response_field_pass').show();
$('#response_field_pass >p').text(data);
if(data) alert("success");
else alert("fail");
}
});
}
return false;
});
The php scripts echos true or false so when successful i am getting an alert box that reads success. Which is great. But the fieldset is not showing and neither is the text that should be inside the <p>. It essentially just skips:
$('#response_field_pass').show();
$('#response_field_pass >p').text(data);
And moves on to the alerts. Any ideas why it isn't unhiding the fieldset?

I doubt if it skips the lines you mentioned. Most probably the paragraph inside the fieldset has nothing to display, since first argument of complete handler is jqXHR object and not the data you receive from the server. In order to solve the problem I'd suggest you to use success handler instead:
$.ajax({
type: "POST",
url: "script.php",
success: function(data) {
// ...
}
});
The first argument of success function is data which is returned from the server.
To handle possible request errors, you can use error handler. It receives three arguments: The jqXHR object, a string describing the type of error that occurred and an optional exception object, if one occurred.

Related

Ajax getting cancelled in browser

When I click and run my ajax script, I see this error in Chrome:
Status: cancelled
The json data returns to the page in the url bar. My sql table is updating but the error message I indicate above is displaying and the modal doesn't remain open. I suspect there could be a few problems here but I wonder if anybody notice something.
This ajax script is inside a PHP variable that is why you may see some escaped characters. Here the $row is a PHP array. Please don't get confused.
$("document").ready(function() {
$(".form-inline'.$row["userid"].'").submit(function(event) {
event.preventDefault;
var formData = new FormData($(".form-inline'.$row["userid"].'")[0]);
console.log();
$.ajax({
type: "POST",
dataType: "json",
url: "sponsorship.php",
data: formData,
success: function(response) {
if (response.success) {
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
contentType: false,
processData: false,
error: function() {
alert("this error is getting displayed");
}
});
});
});
event.preventDefault is a function. You're referencing it, but not calling it.
The default action of the submit event will therefore happen, causing you to leave the page and terminate the JS.
Don't forget to put () when you are trying to call a function.
The problem is with String conctatination on your JS :
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
You have to either fix the concatination :
$("#myModal'.$row['userid'].'")
Or I'm assuming you are missing the php tags on $row

Jquery/Ajax not getting input value from widget

Have a ajax request sending data to a WordPress action which works fine however I can receive the nonce value perfectly but the email input isn't being sent. I know I'm targeting the right value. It does not want to get the value of the email input. If I hardcode a value into the input it will see it. I need to get the user entered value and send that to the ajax script. The code is also run on document load and is after the form values have been rendered.
Input field looks like this:
<input type="email" name="cjd_email" id="cjd_email" class="cjd-email-input"/>
The jquery selector looks like:
var cjd_email = $('#cjd_email').val();
The ajax call is:
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: {
action: 'cjd_subscribe',
nonce: cjd_nonce,
email: cjd_email
},
cache: false,
success: function(data) {
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
}
else {
console.log(message);
}
}
});
Thanks :)
I am assuming you are having a class on form i.e. cjdajax. Then use serialize method to send data instead of any other.
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: $('.cjdAjax').serialize(),
cache: false,
success: function(data) {
//your code
}
});
Depending on the browser you use, type=email might not be supported by jQuery / JavaScript and thus the valid() method could return rather strange values. As an alternative, one can use type=text with input validation.
Also, you should Review the success function : You attempt to apply the find()-method on text rather than a DOM element. The code could be corrected if the server returned a JSON-encoded string, so in JavaScript you could convert the string back into an object.
In PHP one could write print(json_encode($yourArray, true)); (notice how the true flag is required for associative keys), while
...
success: function(data){
var yourObject = JSON.parse(data);
if (yourObject.responseData === "success")
console.log(yourObject.message);
},...
could replace the respective current JavaScript passage.

Submit to multiple php scripts

I have a javascript function which I'm using to change the action field of a form and then submit it. Here's the function
function printmulti(){
form=document.forms['form2'];
form.action="http://localhost/output_sample1.php/";
form.target = "_blank"; // Open in a new window
form.submit();
form.action="http://localhost/output_sample2.php/";
form.target = "_blank";
form.submit();
return true; }
But somehow only output_sample2.php is being shown. Why isn't the first part of the code being executed?
you cant submit to multiple forms like that, you need to use something like ajax and make the requests that way. Currently you are starting the submit for the first and then starting the second right after so the second one stops the first one from submitting.
Ajax Tutorial
Use ajax like this:
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample1.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample1.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample2.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample2.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
Hope will give you some idea to start your work. For more info visit this link ajax example

Performing update query then change page in Jquery Mobile

I have a confirmation dialog that leads to an update query when the user clicks a link.
<div class="ui-bar">
<a id="confirm" href="#" data-strid="<?php echo $str_info['str_id'] ?>">Confirm</a>
</div>
What I am looking to do is run an update query, then reload the previous page with the updated information on it.
I thought I accomplished this, but some sort of error keeps popping up in firebug and the ajax doesnt seem to be successful. The error only comes when I reload the page...and when I put a delay on it, there is no error, so I can't even read what it is.
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
}
});
$('.ui-dialog').dialog('close')
setTimeout(
function()
{
location.reload()
}, 750);
return false;
});
</script>
Is there any good way of accomplishing this? Again, in summary, I am looking to perform an update query, then reload the last viewed page (not the dialog) so that the changed info is displayed. ../../ajax/add_land is in PHP.
There are few better ways of achieving this but that is beyond the point, in your case you should do this:
<script>
$('#confirm').click(function (){
var str_id = $("#confirm").data("strid");
$.ajax({
type: "POST",
async: true,
url: '../../ajax/add_land',
dataType: 'json',
data: { str_id: str_id },
success: function(){
$('.ui-dialog').dialog('close');
location.reload();
}
});
return false;
});
</script>
When ajax call is successfully executed it will call code inside a success callback. Ajax call is asynchronous action, that means rest of the code is not going to wait for it to finish. Because of this success callback is used. So there's need for the timeout.
One more thing, there's also an error callback, use it to debug ajax problems:
error: function (request,error) {
alert('Network error has occurred please try again!');
},

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

Categories