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:
Related
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) {
}
jQuery GET function does not execute.
I am using a Telerik Data grid that executes the following script when a row is selected
<script type="text/javascript">
function onRowSelected(e) {
IPAddressId = e.row.cells[0].innerHTML;
var dialogDiv = $('#result');
var viewUrl = '/IPAddresses/Edit/' + IPAddressId;
$.get(viewUrl, function (data) {
alert(viewUrl);
});
};
</script>
I have the alert inside the .get function for testing. I actually have other code I will place in there.
If I place the alert(viewUrl) above the $.get function, the alert displays however as it is shown above the alert does not get displayed.
Your $.get is correct.
It's possible you are getting a 500 error, and you didn't specify an error function to get called, so you never see it. Open your console (Firebug, Chrome Developer tools, etc) and go to the 'net panel'. What does it say?
The function(data){ alert( viewUrl ) } is a callback function . It will be excuted when the ajax request obtain the server correct response .
So you should debug this, use firefox's firebug extension ,or use chrome developer tool. Watch the newwork panel , and lookup this request , is it have been responsed with http code "200"?
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
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'.
I have basically this on a page:
<script type="text/javascript">
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, 'xml');
}
$(document).ready(function() {
$("#username").blur(refresh_context);
});
</script>
<input type="text" name="username" id="username" maxlength="255" value="" />
<input type="hidden" name="context" id="context" value=""/>
<div id="ajax-context"></div>
What it should do (and does fine on Firefox) is when you type a username in to the #username field, it will run /ajax/ldap_search.php?cn=$username, which searches our company's ldap for the username and returns it's raw context and a formatted version of the context like this:
<result>
<display>Staff -> Accounting -> John Smith</display>
<context>cn=jsmith,ou=Accounting,ou=Staff,ou=Users,o=MyOrg</context>
</result>
The formatted version (display) goes to the div #ajax-context and goes to the hidden input #context. (Also, the -> are actually - "& g t ;" (without spaces)).
However, on IE the div stays stuck on "Searching..." and the hidden input value stays blank.
I've tried both .get and .post and neither work. I'm sure it's failing on the .get because if I try this, I don't even get the alert:
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function() {
alert("Check");
});
Also, IE doesn't give me any script errors.
Edit: Added "$(document).ready(function() {", the .blur was already in it in my code, but I forgot to include that in my post.
Edit 2: The request is being sent and apache2 is receiving it:
10.135.128.96 - - [01/May/2009:10:04:27 -0500] "GET /ajax/ldap_search.php?cn=i_typed_this_in_IE HTTP/1.1" 200 69
Problem was in the ldap_search.php file.
I had this (based on an example I read on someone's blog):
header("content-type:application/xml-xhtml;charset=utf-8");
It actually needed to be this for IE to read it properly:
header("content-type:application/xml;charset=utf-8");
God, I hate IE.
Try changing:
$("#username").blur(refresh_context);
To:
$(function(){
$("#username").blur(refresh_context);
});
This will hold off on assigning the blur event until the entire page is loaded.
Edit:
Could it be the use of > in the text of the XML?
set your type to 'xml'
jQuery.get( url, [data], [callback], [type] )
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function() {
alert("Check");
},'xml');
Can you find out if the Ajax request is even being fired?
You can use Web Development Helper or Fiddler to log Ajax requests.
As general good practice you should enclose any jQuery code that accesses the DOM in a $(document).ready function. This will ensure it doesn't execute until the entire DOM is loaded, although in this instance it doesn't look like that's causing the problem if the div is changing to 'Loading...'
<script type="text/javascript">
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, "xml"); // As pointed out, you should specify the return type
}
$(document).ready(function() {
$("#username").blur(refresh_context);
});
</script>
You may want to change the $.get call to a $.ajax call, so you can set an error handler to see why it's erroring.
As I recall, this is done like this:
$.ajax({
type: 'GET',
url: "/ajax/ldap_search.php",
data: {cn: $("#username").val()},
success: function(response) { /* do something here */ },
error: function(xhr, type, exception) { alert("Error: " + type); }
})
The exception object should have more detail about the error as well.
I had same problem but not with xml - i had simple html as ajax-return. header("content-type:text;charset=utf-8"); was the solution.
Does not work:
$.post("/welcome/add_mail", function(data){
alert('ok');
});
Works fine with base url in IE7:
$.post("http://localhost/welcome/add_mail", function(data){
alert('ok');
});
Usually with $.get/$.post you have to specify the return type. This makes it easier for jquery to a) recognize what it looks for and b) decode it for you.
This may help.
Instead of $("display", xml).text()
Maybe try: $(xml).find("display").text()
Can you see what the response is or is it just timing out? Can you see what params are being sent in? If not, expand your:
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
$("#ajax-context").html($("display", xml).text());
$("#context").val($("context", xml).text());
}, "xml"); // As pointed out, you should specify the return type
}
to
function refresh_context() {
$("#ajax-context").html("Searching...");
$.get("/ajax/ldap_search.php", {cn: $("#username").val()}, function(xml) {
var displayXml = $("display", xml).text();
$("#ajax-context").html(displayXml);
var contextXml = $("context", xml).text();
$("#context").val(contextXml);
}, "xml"); // As pointed out, you should specify the return type
}
and then debugging the script.
I had a similar problem, but loading JSON. The $.ajax fix worked for me but I also discovered that in my case it had to do with the URL. When I use:
$.getJSON('',{ ajax: "addressPicker",OID:pickIDNo,s:pickVal}, function(data) {
I would get a silent response, but when I replaced the empty URL '' with '?' it worked. In your case the URL was present, but it might be picky as to URL.