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
Related
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!');
},
I've posted a question about it already, but I've figured out what is the exact problem. Now, I need a solution for that :)
Here's my code:
$('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
The Problem and Explanation:
Every time a key is triggered up it loads this ajax. If my JSON file finds a keyword it returns with error = false flag. You see, if it happens, it loads the effects, changing, etc...
The problem is that when you start to type, for example asdasdasd and just after that I paste / write the keyword there'll be some ajax queries which ones are still processing. These ones are modifying and loading the fadeOut-In effects X times.
So I'd need a solution to stop the processing ajax requests, while an other key is pressed!
Thanks in advance,
Marcell
Personally I would have the script wait so it didn't fire on each keyup. Actually I would probably use http://jqueryui.com/autocomplete/
But you can just abort the ajax before trying again.
...
var iTunesAppID = $('input[name="iTunesAppID"]').val();
if (typeof req!='undefined' && req!=null) req.abort();
req = $.ajax({
...
try adding the option async: false to your ajax this will prevent any other calls until the current one is finished.
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.
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')
I have a have a button that calls a JavaScript method that looks like this:
processSelection = function(filename) {
//alert('method reached');
$.ajax({
url: "sec/selectUsers.php",
data: "filename="+filename,
cache: false,
dataType:'html',
success: function(data) {
//$('#uploader').html(data);
$('#noUsers').sortOptions();
values = $('#noUsers').children();
for (i = 0; i < values.length; i++) {
$(values[i]).bind('dblclick',switchUser);
}
$('#addButton').bind('click',addSelection);
$('#removeButton').bind('click',removeSelection);
$('#submitButton').bind('click',addUsersToFile);
},
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry');
}
}); /* ajax */
}
It is not going to the selectUsers.php script, nor is it posting the error message. When I click on my button 'add users' it does nothing. The other methods: switchUser, removeSelection, addSelection, and addUserstoFile are already defined.
I am fairly new to JavaScript and php and have been assigned this project running maintenance on our website. My php_error.log shows no error either. If anyone has any advice on this specific problem, or debugging in general I would very much appreciate it.
here is the click event:
<input type="button" value="add users" onclick="processSelection('<?=$drFile['name']?>')"/>
Okay,
To simplify my problem, I have done this:
processSelection = function(){
//alert('method reached');
$.ajax({
url: "sec/testPage.php",
cache: false,
success: function() {
alert('success');
},
dataType:'html',
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry'); }
});
}
where testPage.php is just a table with some values in it.
Now when I click the button it show 'success', but never shows testPage.php
dataType: 'HTML'
has to be before your success method as far as i know. If still does not work try the following:
it will not show the test page because you are not appending anything to your current body. Your script executes successfully if you see "success"on your screen. All you need to do is if you have html generated in your testPage, assign all html to a php variable and then just echo it instead of returning it like
echo $myhtmlgenerated
and change
success: function() { ....
TO
success: function(result) {
$(body).append(result);
}
or you can play around with it and specify a special div which will hold the content from that page.