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!');
},
Related
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
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 PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.
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.
I have the following ajax call:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
});
Aimed at the following piece of my site:
<div id="welcome">
<h2>Welcome <a class="close" href="Javascript:;"></a></h2>
<div class="left">
</div>
<div class="right">
<div class="loginElement">
</div>
</div>
<div class="clear"></div>
</div>
With the following code to answer the ajax request:
<?php
class VisitorsController extends AppController {
function hide_welcome() {
if($this->RequestHandler->isAjax()) {
$this->Session->write('Welcome.hidden', true);
echo 'Success.';
}
else {
echo 'I am, in fact, here.<br>';
$this->autoRender = false;
}
}
}
?>
It's pretty straight forward. It calls to /visitors/hide_welcome to set a session variable noting that they've hidden the welcome. But it doesn't seem to complete. If I place alerts on either side of it, like so:
$("#welcome a.close").click(function(e) {
alert("Begin.");
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
alert("End.");
});
They will trigger. But alerts placed in success are ignored. The same goes for error and complete. This was working just fine on my test machine. The page in question is definitely there, I can reach it with out ajax. Firebug reports nothing, neither does the error console. Success simply never fires.
The strangest part is that often if I reload manually the welcome disappears, indicating that the ajax call did fire. It just never returned. What is going on here? I'm at wits end. Any one see any trees I haven't barked up yet?
SOLUTION:
CakePHP is supposed to auto detect ajax calls. But in this instance, it wasn't. As a result it was running the code I had for the Ajax, but then returning a 404 when it failed to find a view. The solution was to append $this->autoRender= false; to the end of the ajax handling controller function. After that everything worked beautifully.
I think given your symptoms, you're redirecting to whatever URL the <a class="close"> you're clicking on pointed to - since the default behavior isn't prevented.
The e.preventDefault() call should happen in the base method, not a callback, like this:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
}
});
e.preventDefault();
});
Try adding data to your success callback like so:
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});
EDIT:
Try supplying the absolute path of your url:
$.ajax({
type: "GET",
url: "http://fridgetofood.com/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});