I have a page where I need to add a drag and drop functionality to certain elements. When the drop event occurs, it makes an ajax call to a php function and then refreshes the contents of a div. I'm using jQuery with jQueryUI for the drag and drop, and CakePHP as a PHP framework (not sure if this is relevant).
Everything is working just fine in Firefox, Safari and even IE, but in Opera or Chrome the contents of the div isn't refreshed (although the action from the PHP function is executed).
So, here is the code:
jQuery('#lists div').
filter(function() {return this.id.match(/item[\d]+_[\d]+/);}).
each(function() { jQuery(this).draggable( {axis: 'y'}); });
jQuery('#lists div').
filter(function() {
return this.id.match(/list[\d]+/);}).
each(function() {
jQuery(this).droppable({
drop: function(event, ui) {
dropID = jQuery(event.target).attr('id');
dragID = jQuery(ui.draggable).attr('id');
itemID = dragID.substr(dragID.lastIndexOf('_') + 1);
oldListID = dragID.substr(4).replace(/_[\d]+/g, '');
newListID = drop.substr(4);
jQuery.ajax({
url: "/lists/itemToList/"+itemID+"/"+oldListID+
"/"+newListID,
type: "POST",
success: function (data) {
jQuery('#lists').html(data);}
});
}
});
});
Basically, the success function isn't executed, but if I try to see the errorThrown (on the error event) it is "undefined"
Try something like this:
jQuery.ajax({
url: "/lists/itemToList/"+itemID+"/"+oldListID+
"/"+newListID,
type: "POST",
success: function (data) {
jQuery('#lists').html(data);
}
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
It will show you what http response are you getting for your request. I had the same problem some time ago. My script worked great in Firefox and Chrome, but it didn't do anything in Opera and IE. I checked it and the problem was, that the php backend was returning 404 (I still don't know how did it work under Chrome and FF).
I know it's been a long time since I've posted the question, but here is what I found to be the solution, in case somebody else needs it: the problem was not the in javascript but with CakePHP: the html that was added on success contained an ajax form (rendered using $ajax->form()). $ajax->form() needed the $data variable from the controller to be an array, but for some reason it wasn't, and this broke the rendering of the form, and Opera and Chrome didn't like this. So the solution was to simply add
$this->data = array();
to the itemToList() function in my controller.
I don't see anything in the code that would cause a cross browser issue. My feeling is that it's a problem doesn't lie in the code at all, but in the rendering of the div and/or its contents in Chrome and Opera (i.e. a CSS problem or something along those lines where the innerHTML of the div is updated, but because of styling or positioning you don't get the visual result you were looking for).
Have you checked using Dragonfly or some other developer tool to verify that the contents of the target element are in fact unchanged after a successful request? Along those lines have you tried stepping through the code execution in the problem browsers? You could also try adding a error handler to the JQuery.ajax options to see if there is some problem with the request itself, although I don't believe that is where the problem lies.
EDIT: I didn't see that last bit below the code block. So you have verified that the success handler isn't being executed. You said that you did try and implement an error handler for the request and got some undefined result, but I don't see it in the code. Could you post the code for the error handler and describe what in the error is undefined?
I think he means, that alert(errorThrown) is showing 'undefined'.
Related
I want the data coming from the server to show in the <div id="demo"> element.
But sometimes, it just appears and goes, and other times, it is not even showing up. I searched and tried lots of options, but nothing works for me.
My code is:
function loadDoc(){
document.getElementById("demo").innerHTML = "Paragraph changed!";
alert("hello world");
$.ajax({
type:'POST',
url :"new_mark.php",
data :"regno=u4cse13xxx",
success: function(data) {
//$("demo").html = "Narayana!";
document.getElementById("demo").innerHTML = data;
alert(data);
}
});
}
To debug an web site, i advise you tu use the Chrome debugger or on generaly the browser debugger its very simple and usefull.
Click F12 and go to ressources and put an debug point at your line and it finished
Just call the Element and set the the content via a jquery method like text (Reference: .text())
So your code inside success would be:
success: function(data) {
$("#demo").text(data);
}
And maybe you can tell me if it worked? :)
Greets!
Go to the Network tab of the debugger, select your request (new_mark.php), then check the Response tab. If there was an error, it should appear in the response.
For example in Chrome:
I have the following code that runs when the process_2banner button is clicked on a html page. This code does what is supposed to do when using Firefox. When using Chrome and Internet Explorer the ajax code is called but the div spinner_block does not show/hide as the code intends to.
Strangely enough it works if I open firebug in Chrome and place a breakpoint right before the ajax call (after the .css("display","block") statement. The spinner_box <div> shows, and then after the ajax call returns, it hides.
Can you see what is wrong here?
Thank you very much!
Andres
$('#process_2banner').on("click",function() {
var postdata = "lead_id="+rowId; //needs to include the pidm of the user clicking the button
$('#spinner_box').css("display","block");
$('#spinner_box').html('Wait, we are processing the record..');
$('#spinner_box').css("display","block");
$.ajax({type: "POST",
url: "insert_srwordpress.php",
data:postdata,
success:function(result) {
if (result.isOk == false) {
alert('Some error occurred while writing Banner') }
else {
$('#spinner_box').hide();
}
},
async: false});
});
The response result is an string in format JSON?
May you need parse the JSON before use it?
Example:
var jData = $.parseJSON(result);
if (jData.isOk === false) {
}
I have a lil problem with an AJAX request.
We have a lil PHP, JavaScript application (Website). The application is running fine on all desktop browsers + on our old MDE's (some Windows CE6 MDE). Now on our new Motorola MC9200 (Windows Embedded Compact 7 formerly CE7) it's not working anymore.
The problem is some small JavaScript function. It disables the buttons/input fields, starts a Ajax.Request (prototype 1.72 but I tested jQuery 1.11.1 too), does something on the database and when everything went right it is refreshing the site via window.location. This function isn't working always on the new devices. Sometimes it does, sometimes not.
simplified code:
function loadSite(siteName) {
disableForm();
var parameters = {
/* SOME PARAMETERS */
};
new Ajax.Request('ajax/ajax_db_execute.php', {
method: 'post',
parameters: parameters,
onSuccess: callbackFunc
});
}
function callbackFunc(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
} else {
show_error_box(response.errortext);
enableForm();
}
}
I tried to output the response in the callbackFunc but that function wasn't even called. Next thing I tried was to put some alert at the end of the loadSite function, it was fired everytime. I already checked the parameters and they look fine too.
After that I put some simple fwrite in the php file. It looks like that file isn't even called sometimes. So the question is why?
By changing the method to 'get' I couldn't reproduce the problem and everything is working fine. Problem about that is that I don't want to use get + some parameters might be too long for get to handle.
The parameters in that example were just some simple integers and strings. Does anyone have an idea what might cause the problem and some workaround?
It seems that your post request response is not synchronized. So please use setTimeout function in your post callback like that
setTimeout(function(transport) {
response = transport.responseText.evalJSON(true);
if(response.retcode === 0) {
window.location = "start.php?id=<?php echo $id; ?>";
}
else
{
show_error_box(response.errortext);
enableForm();
}
}, 3000);
I'm using ajax to get some data then based on the data use html() to put it on the page.
In IE, the data returned is empty (it's html). It still triggers the success function, but the html is not there. I've set the dataType: "text" but still doesn't work.
Any ideas?
Thanks!
EDIT:
Here's the exact code:
$('#frm').submit(function(event){
event.preventDefault();
var self = this;
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
return false;
}
} else {
return false;
}
$.ajax({
url: "/ajax/zip",
type: 'GET',
async: false,
dataType: 'html',
data: {zipcode: $('.zip_field').val()},
success: function(data) {
if(data == 'false'){
error($(".zip_field"));
return false;
}else{
self.submit();
$('.container').empty().append(data);
}
}
});
})
It's submitting a zip code. On submit, it checks to make sure it's a number and 5 digits in length. If that passes, it goes to the ajax and checks to make sure it's a valid zip code (database check), if that fails it returns 'false' as text, if it's good then it returns some html.
It works in Firefox and Chrome, but not in IE. When it's good, it submits the form but the data returned alerts empty and is appended as empty space.
demo: https://so.lucafilosofi.com/jquery-ajax-return-data-empty-in-ie/
your code don't work simply because it is buggy, it have nothing to do with IE.
it should be something like below.
$('#frm').submit(function (e) {
e.preventDefault(); // this one already act as return false...
var form = $(this);
// why you have .zip_field & #zip_code ?
var zip_code = $.trim($('#zip_code').val());
var valid = (zip_code.length === 5 && !isNaN(zip_code)) ? true : false;
if (valid) {
$.get('/ajax/zip', {
zipcode: zip_code
}, function (data) {
if (data == 'false') {
alert('error!');
} else {
//if you submit the form here
//form.submit(); then the line below
//is totally useless
$('.container').html(data);
//.empty().append() is = .html()
}
});
}
});
NOTE: the fact that chrome and firefox don't display errors dosn't mean that errors are not there; internet-explorer simply tend to display errors everytime it run through malformed code etc. Also i strongly doubt that your code work really as expected since it is not so good as you may think. I guess the problem is in your code and have nothing to do with jQuery itself or it's ajax function or dataType.
One thing could be that this URL is cached by the browser. If you obtain a 304 status your response's text it will be empty. Check your HTTP cache headers, and adjust them properly. You could also trying to use POST (only GET are cached).
Also, have a look to Content-Length if is properly set.
If nothing of above works, inspect the network's call will give to you (and us) some additional details, try the IE's dev tools.
You could also try to have the same request using XMLHttpRequest's object directly (assuming you're using IE>6).
I have same problem in IE and Google Chrome
$.ajax is not working in this browser because of security reason.
so if you want to run explicitely
for chrome run chrome with
chrome.exe --disable-web-security
and in IE you need to change setting from Menu>Tools>internet Options
Some versions of IE will not ~repair~ invalid HTML in XHR requests and simply discard it; I've been bitten by this before.
Make sure the HTML returned is valid for the doctype IE thinks you're using (use the developer tools in IE to see), and check your HTML with a validator tool. Obviously, it will complain about missing <html>, <head>, etc, but ignores those and focus on the other errors. once you've fixed those, it should start working.
Also, aSeptik's answer is full of good tips to improve your code.
Trying to get a very simple request working with MooTools Request.JSON. After having no success building it from scratch, I took an example from somewhere and slowly pared it down to the bare, bare minimum, then put it back into my own page. The only things changed are the url and element ID, but to no avail.
Any help, ideas, will be greatly appreciated.
json.php
<?php
$result['name'] = 'yay';
header('Content-type: application/json');
echo json_encode($result);
?>
demo.js (snippet inside window.addEvent('domready', function() { )
$(document.body).getElement('input[id=game_name]').addEvents({
'keydown' : function(){
alert('hmm'); //this fires
var jsonRequest = new Request.JSON({
url: "json.php",
onComplete: function(result){ //changing to onSuccess kills everything afterwards
alert('result.name'); //this fires
alert(result.name); //this does not fire
alert('result.name'); //this does not fire
}
}).get();
}
});
PS. in neither my page, or the pared down example pages, can i get the request to send on domready, only inside an event. why is that?
thanks again
As it turns out, the problem was that I had accidentally loaded a synced duplicate file into my browser that was therefore (obviously) unable to execute anything server side.
Thank you very much for your help.
Several suggestions/questions:
Are you getting any errors in your web browser's console? Which web browser are you using? The fact that the third alert doesn't fire at all suggests that alert(result.name); is throwing an error, in which case, all further execution will be stopped and an error will appear on your browser's console.
When you say "changing to onSuccess kills everything afterwards", what exactly do you mean? Does code further down (i.e. code that's not included in the above code snippet) never execute? Or does onSuccess just never fire?
Is json.php in the same directory as the page where this script is running? Try replacing json.php in url: "json.php" with an absolute URL (/mydirectory/json.php or http://www.mywebsite.com/mydirectory/json.php) and see whether this works.
If it's any help, the following code results in an alert reading "yay" (running on a local server; json.php is a file containing the PHP code in your question):
var jsonRequest = new Request.JSON({
url: "json.php",
onSuccess: function(result) {
alert(result.name);
}
}).get();
you can find a great tutorial here
http://net.tutsplus.com/tutorials/javascript-ajax/checking-username-availability-with-mootools-and-request-json/
Exactly the same problem here.
I solved it by decoding the JSON string, which is given as parameter (instead of the expected object).
onSuccess: function(jsonString) {
console.log(JSON.decode(jsonString));
}
Here ist the documentation:
http://mootools.net/docs/core/Utilities/JSON#JSON:decode