AJAX/jQuery alert() works, .html() or .text() doesn't - php

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/

Related

$.ajax.done works on Firefox but not in Chrome

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.

Intermittent results from AJAX PHP request

I have a select group populated by AJAX/PHP.
The issue i have although it works perfectly well, it does not return results 100% of the time of the page load.
Is there a specific reason why this might be happening?
the html
<div id='select_tags_div'>
</div>
the AJAX
$( document ).ready( function() {
selector_refresh();
});
function selector_refresh() {
url = '/home/bin/scripts/tags_list.php';
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
beforeSend: function() {
},
success: function(result) {
$("#select_tags_div").html(result);
$(".chosen-select").chosen();
$('.chosen-select').trigger('chosen:updated');
vid_tags();
}
});
}
I have checked the source on the both success and fail to show results, and the results actually are not populated at all. I thought it may have been a chosen.js issue but now its looking like it isn't that at all. Instead it seems it may be a PHP/AJAX issue not returning the results.
When i check the AJAX success with an alert, it confirms the AJAX is successful even on the times when the PHP has not populated correctly.
ADDED
I added a button which calls the function to populate the field, of which functions 100% of the time.
Could this be a case of DOM perhaps?

How to send POST jquery ajax calls to server using php / mysql for "favorite" button?

I'm looking to POST very simple data to a page for a "favorite" button, called "postData.php" where I already understand how to handle POST data and send it to the server. What I'm unsure of is how to set up the jquery .ajax function to make this work.
I understand that there will be
$('#myDiv').click(function(){}
for the function call, but what do I include in the function? The data sent in your example can be generic as I just need to understand jquery-ajax a little better.
Any help would be greatly appreciated.
There is a shortcut function called $.post().
$.post('postData.php', { name: "John", time: "2pm" }, function(data) {
$('.result').html(data);
});
Otherwise, this is how the $.ajax() function is used.
$.ajax({
type: "POST",
url: 'postData.php',
data: data,
success: success,
dataType: dataType
});
For the event itself, assuming jQuery 1.7X or later.
$(document).on("click", "#myDiv", function(){
$.post("filethatacceptspostdata.php", {'data':'object', item2:'data', item3:'data'}, function(myreturndata){
//Whatever you want to do with myreturndata here.
//I would have the filethatacceptspostdata.php file output a number 1 if the data was successfully stored.
});
});

ajax jquery call doesnt work for me

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.

jquery ajax post - not working first time page loads

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

Categories