I have a very simple AJAX request with jQuery and PHP. This is my code
var request = $.ajax({
method: "POST",
url: "Url.php",
data: { param: valueParam },
dataType: "html"
});
request.done(function(html) {
alert('Hello');
});
The code works perfect in Firefox 38.0.5 but not works in Chrome 43.0.2357.124m.
The problem in Chrome is the follow: the "Url.php" returns a pair name-value. If it returns a value distinct than null, then the alert is not displayed (and there isn't any error in the console). But if the url return a null value, the alert is displayed. I tried ctrl+F5 but not works.
In Firefox works good in both cases.
Thanks!
Does fail function return something?
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
console.log("Request failed: "+textStatus);
});
The problem is when I was firing the ajax request. I was doing it in "onchange" (of a input text with jQuery autocomplete) jQuery event. When I select an item of the list of autocomplete, the onchange() event is not raised in Chrome (yes in Firefox).
So I fire the ajax request in jQuery "focusout" event and works in Chrome and Firefox.
Related
I'm newbie to jquery and AJAX and I have a really annoying problem with returning AJAX response simply into a div.
Code
$(document).ready(function() {
$.ajax({
method: "GET",
url: "lists2.php",
cache: false,
dataType: "html",
beforeSend: function() {
$("#sidebar-content").text("Loading..");
},
complete: function() {
$("#sidebar-content").text("");
},
success: function(lists) {
$("#sidebar-content").text(lists);
},
error: function() {
alert("Something went wrong..");
}
});
});
Code fires fine and no error appears, Firebug shows also no errors and if I put for example alert(lists) instead of .text() or .html() it works and alerts the data. But .text() or .html() don't work.
lists2.php is a complex file that analyzes data from SQL db and outputs the content inside a bootstrap sidebar. It worked fine in the old version without AJAX.
What am I doing wrong?
Complete() fires after success(), and is clearing your content.
Complete
A function to be called when the request finishes (after success and error
callbacks are executed). The function gets passed two arguments: The
jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
categorizing the status of the request ("success", "notmodified",
"nocontent", "error", "timeout", "abort", or "parsererror"). As of
jQuery 1.5, the complete setting can accept an array of functions.
Each function will be called in turn. This is an Ajax Event.
http://api.jquery.com/jquery.ajax/
I have a
$(".clickButton").click(function() that loads a page using $.ajax and return the result to a DIV. This works perfectly in Chrome, FireFox and Safari, but not IE11.
$.ajax({
url: "go.php?ab=1",
success: function(data, textStatus, xhr) {
$("#res").html(data);
}
});
As a quick test I tried the following and again it works in Chrome, FireFox and Safari but not IE11.
$.get('go.php?ab=1', function( jqXHR, textStatus, errorThrown )
{ alert(jqXHR); });
The date being returned is text and is either OK or ERROR.
The go.php is running multiple command line scripts and depending what the variables passed depneds on what runs.
All that part is fine and it works really well in the 3 browsers, but not IE11.
When the page first loads in IE it sort of works, it appears to run the go script and return a result. But any subsequent click return instant and the go.php page isn't called. Results are displayed but they appear to be the first processes return results. It's as if the result and process have been cached.
Any ideas how to make this work in IE as it does in the others ?
It's as if the result and process have been cached.
This is possible. If you are sending multiple GET requests to the same URL your browser may be caching the result. If you wanted to verify this you could click the button, clear your cache without reloading the page, and click the button again to see if it works as expected this time.
To prevent caching of GET requests you can add
cache: false
to your $.ajax options for each request, or you could disable it for all requests by using
$.ajaxSetup({ cache: false });
I dont know if we been to the same problem, but just earlier I was trying to get the responce data from the go.php and add it into a div.
My code goes like this.
onClick:
<script type="text/javascript">
function gimmeData(){
var url = 'go.php';
$.ajax({
type: "GET",
url: url,
data:{'something':'1'},
success:function(results)
{
$('#add_data').html(results);
}
});
}
</script>
this will give go.php?something=1 url.
html:
<input type="button" onclick="gimmeData();" value="clickme!" />
<div id="add_data"></div>
button click
$('a').on('click', function(){
var a = $(this).data('first');
var b = $(this).data('second');
alert(a + ":" + b);
});
html:
<a id="button" href="#" data-first="something" data-second="something2" onclick="click();">click me</a>
using data() function. see http://api.jquery.com/data/
or you can do $(this).attr("data-value") to get the value of a data-attribute
JSFiddle sample.
I've created a custom wordpress plugin that should do the following:
on page load, submits a form
ajax catches it and does some other functions
results are returned
Only problem is that the plugin started redirecting to another page and looping infinitely. I've isolated it to the jquery submit code but I can't figure out what I'm doing wrong. I was hoping you folks could lend a sleep-deprived programmer a hand.
$('#searchform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '../wp-content/plugins/otwcsl/getStores.php',
data: $('#searchform').serialize(),
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
});
});
It worked fine on my localhost environment but went berserk on the 'live' website. I can't figure out the disconnect but I'm pretty sure the problem lies here. Thanks in advance!
UPDATE: I've cut everything down until it looks like this:
$('#searchform').submit(function(e) {
return false;
}
It's stopped looping but it redirects from http://www.mypage.com/index.php/locations/ to http://www.mypage.com/index.php/?s=. I can't figure it out since it's clearly not ajax that's affecting it.
FINAL UPDATE: I've finally fixed the problem. I removed all 'submit' functions and used a button click instead. I used the answer found here in option 3. I'm guessing there was some previous script that was severely messing with the form. Unfortunately, it's not an option for me to go disabling the scripts to find the root cause at this point. Thanks everyone for helping me troubleshoot it!
You have this code in the ajax call:
$('#searchform').unbind().submit();
In it you submit the form again. I guess that is what's going wrong.
infinite loop because you submit the form again if submit is seccussfull:
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
why submit again on success? remove it and it will work!
it should be:
success: function(response) {
searchLocations(response);
}
UPDATE:
your submit function should be like this:
var _form = $('#searchform');
_form.unbind();
_form.submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../wp-content/plugins/otwcsl/getStores.php",
data: _form.serialize(),
success: function(response) {
//searchLocations(response); // check this method may be its submit the form again
}
});
});
Check the response from the server and set the propper datatype in the ajax call.
you can debug your ajax by using:
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serializeArray()
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
console.log(data, textStatus, jqXHR);
});
UPDATE:
I need to get the jason.. The click event doesnt work why..
update:
<script>
$(document).ready(function(){
$("#RefreshButton").click(function(){
$.ajax({
url: "/test2/ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
alert("This is my data: "+data);
$(".article").remove();
$.each(data, function(key, value){
$('articleColumn').append( '<p class="article"><font size="5"><b>'+value[0]+'</b></font><br/>'
+value[1]+' Read more...</p>');
});
},
error: function( error )
{
alert(JSON.stringify(error));
}
});
});
});
</script>
The ajax call works..but not when it is in the click event handler..why?!?
I think the solution to the problem lies in the html:
<a href="" id="RefreshButton" >Refresh</a>
may be it refreshes the page and then send the response. I think it is the problem in the way the event propogates ..hmm
Generally when making an ajax call using jQuery I use the short hand version of POST and GET methods. So in your case I would do something like this
$.get("ajax.php", function(data){
alert(data); //just to make sure it works
}, "json");
Be sure to send the response back from ajax.php as json using json_encode(array("key"=>"value","key"=>"value")); ?>)
Also since ajax cannot go across domains you don't have to specify http://localhost/ajax.php, rather you can just specify it as the relative path to where you are calling the jquery function from.
I have some ajax/jquery code in one of my pages and the problem I'm having is that it doesn't work the first time the page is loaded. If I refresh the page it works no prob. It does work in firefox first time. All the variables that I'm using are ok as I've alerted them out. I don't get a success or error message. It justr doesn't appear to do anything?
Any ideas?
$('.window .request').click(function (e) {
var itm = document.getElementById('txtItm').value;
var qty = document.getElementById('txtQty').value;
var msg = document.getElementById('txtMessage').value;
var op_id = document.getElementById('txtOp_id').value;
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
It's hard to determine what the problem might be given the information and it sounds like you've not fully tested the page in a consistent manner. It seems likely there is another element on the page affecting the click event, as opposed to the handler logic itself, but there's no way to tell. Make sure you are binding to the click event after the page is ready:
$(document).ready(function(){
$("#uniquedomid").bind('click',function(){
// click handler logic
});
});
Also, as you're new to JQuery, one thing you're going to want to start looking at are all the various ways in which JQuery can improve your life. It does almost everything. But for starters, you're going to want to start using:
$("#uniquedomid")
Instead of
document.getElementById("uniquedomid")
And
$("#uniquedomid").val();
Instead of
document.getElementById("uniquedomid").value