jQuery AJAX data to HTML - ajax

EDIT: Ok, so the solution i came up with, is basically count the characters and see the difference between the numbers. One headache i had was related with the fact that the .html() didn't showed me the with the slash, instead, . Annoying....
function verifica(){
$.ajax({
type: "GET",
datatype: "html",
url: 'icallverifica.php',
data: "valor=0",
success: function(data) {
var verificando = $('#results').html();
var verificandox = (verificando.length);
var verificador = data.length;
if(verificandox != verificador){
$('#results').html(data);
}
}
});
}
I'm creating a little script using AJAX that retrieves data from a database. The problem is that I've used setInterval and it's refreshing all the time.
I don't have a problem with too many accesses to the database, my problem is that I want the content as static as possible until there are new entries on the database:
function verifica() {
$.ajax({
type: "GET",
datatype: "html",
url: 'icallverifica.php',
data: "valor=0",
success: function(data) {
var verificando = $('#results').html();
if (verificando != "<html>"+data+"</html>") {
$('#results').html(data);}
}
});
}
The function changes the #results div introducing the database information, the thing is that I don't want to change the div content unless there are any new entries.
What I did was check on the database and compare the previous content on the div, if it's the same, it will not overwrite.
BUT, i can't put data in html format...

Try changing the success handler to:
success: function(data) {
var verificando = $('#results').html();
if (verificando != data) {
$('#results').html(data);}
}
}

Did you try this instead ?
if ( verificando != data ){
$('#results').html(data);
}
You shouldn't need to concatenate <html> to the data while comparing it.

Such comparison is a overkill. You can basically check the ids associated to each result and then just refresh only the part which is new.
May be you can send the ids along with the ajax request itself and then filter out the response and send only which are the new results.

Related

Kendo Tooltip is empty

dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try

AJAX unsubmit form

I've made an ajax search filter which loads when a certain input has a value (this is the search query box):
$("#filter").keyup(function(event){
var query = document.getElementById('query').value;
if(query!=""){
$("#filter").submit();
}
else{
}
});
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "filter_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
Is there a way to "unsubmit" the form when there is no value? So the ajax loaded content will disapeare instead of showing the content related to the last value (that wasn't blank)?
Thanks in advance!
If you want to make the content disappear why don't you just change $('#result').html() to an empty or a default value. This could be done in the 'else' part of query check. There is nothing called unsubmit form. Hope that makes sense

Async AJAX calls overwriting each other

I've got a dashboard page, and am using jQuery to update each graph with a single ajax call.
If it run AJAX with async:false then everything works, but it's obviously slow as the calls are made one after another.
When I run async:true, the queries execute but they all output to the same element and overwrite each other.
How can I ensure that the jQuery selector in the success and error functions remain pointed to their original desintation and do not all point to the final box?
My code:
//update sparklines on dashboard page
$(".convobox7").each(function() {
id = $(this).attr('id');
$("#convobox-7-"+id).prepend("<img src='img/ajax_loader.gif'/>");
$.ajaxQueue({
url: '_ajax/getFunnelReport',
type: "POST",
dataType: "json",
async: true,
data: {funnel:$(this).attr('id'), dimension:'date'},
timeout: 50000,
success: function(json) {
var data = json;
if (data.success=='true') {
$("#convobox-7-"+id).html(data.htmlconv+"<br/><small>Past week</small>");
gebo_peity.init();
}
},
error: function(x, t, m) {
$("#convobox-7-"+id).html("");
}
})
});
Note I'm using the ajaxQueue plugin here but the same thing happens without it.
You need to localise id :
var id = $(this).attr('id');
There may be other things to fix but that one is a certainty.
EDIT
Try this :
$(".convobox7").each(function() {
var id = $(this).attr('id');
var $el = $("#convobox-7-"+id).prepend("<img src='img/ajax_loader.gif'/>");
$.ajaxQueue({
url: '_ajax/getFunnelReport',
type: "POST",
dataType: "json",
data: {funnel:id, dimension:'date'},
timeout: 50000,
success: function(data) {
if (data.success == 'true') {
$el.html(data.htmlconv+"<br/><small>Past week</small>");
gebo_peity.init();
}
},
error: function(x, t, m) {
$el.html("");
}
});
});
This has to do with function closures because you declared the variable outside the success/error function. A better approach is to use the $(this) reference in the error/success functions instead of assigning it outside the handlers.
Edit: In the context of the error/success handler for ajaxQueue, I'm not absolutely certain what $(this) refers to, you may need to navigate to a parent element. I didn't see any definitive documentation offhand. This is one of my biggest pet peeves with javascript documentation, $(this) is sometimes not what you would think it'd be and isn't documented :/
silly question, but since you already send the element id to the service, is there a reason it cannot send it back? then you can simply use that as a selector, ensuring that you have the item you need.

Multiple AJAX calls on page load

I'm attempting to pull two separate things from outside sources to put onto an HTML page I'm creating. I have a successful AJAX function to pull the most recent video from a particular Youtube channel by parsing through the XML/RSS feed for that channel. I receive this feed through an AJAX call.
I'd also like to get the most recent blog post from a Blogger account. The code for parsing the feed to get the most recent entry shouldn't be difficult, but I'm having trouble with simultaneous AJAX calls. I read somewhere that it can only handle one at a time? I'm weary about queuing them because I don't want to the content on the page to load in steps. I'd rather it all just get fetched simultaneously. How might I go about doing this?
Here is my current script:
<script type="text/javascript" charset="utf-8">
$(function() {
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/base/users/devinsupertramp/uploads?orderby=updated&alt=rss&client=ytapi-youtube-rss-redirect&v=2",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml) {
$(xml).find("item:first").each(
function() {
var tmp = $(this).find("link:first").text();
tmp = tmp.replace("http://www.youtube.com/watch?v=", "");
tmp = tmp.replace("&feature=youtube_gdata", "");
var tmp2 = "http://www.youtube.com/embed/" + tmp + "?autoplay=1&controls=0&rel=0&showinfo=0&autohide=1";
var iframe = $("#ytplayer");
$(iframe).attr('src', tmp2);
}
);
}
</script>
I read somewhere that it can only handle one at a time?
Either you misunderstood what the person was trying to say or they were incorrect. Javascript doesn't run any functions concurrently so someone with poor English might reword that as "can only handle one at a time" but that doesn't mean you can't make multiple AJAX calls. jQuery is smart and will do what it needs to do to make sure both calls are executed eventually.
If you'd like all the content to be loaded simultaneously the sad fact is you can't. However you can make it appear that way to the user by declaring a flag that is set by the success method of each call. Then just keep the content hidden until both flags have been set.
EDIT:
Here's a very simplistic approach to make it appear that they are fetched simultaneously:
<script type="text/javascript" charset="utf-8">
var youtubComplete = false;
var otherComplete = false;
$(function() {
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/base/users/devinsupertramp/uploads?orderby=updated&alt=rss&client=ytapi-youtube-rss-redirect&v=2",
dataType: "xml",
success: parseXml
});
$.ajax({
type: "GET",
url: "http://someotherdata.com/",
dataType: "xml",
success: function() { otherComplete = true; checkFinished(); }
});
});
function parseXml(xml) {
$(xml).find("item:first").each(
function() {
var tmp = $(this).find("link:first").text();
tmp = tmp.replace("http://www.youtube.com/watch?v=", "");
tmp = tmp.replace("&feature=youtube_gdata", "");
var tmp2 = "http://www.youtube.com/embed/" + tmp + "?autoplay=1&controls=0&rel=0&showinfo=0&autohide=1";
var iframe = $("#ytplayer");
$(iframe).attr('src', tmp2);
}
);
youtubeComplete = true;
checkFinished();
}
function checkFinished()
{
if(!youtubeComplete || !otherComplete) return;
// ... Unhide your content.
}
</script>
The browser will support multiple outbound calls but there is a cap per domain. Take a look at this related Q/A How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?.
There are several good libraries for doing request scheduling including chaining and parallelizing AJAX calls. One good library is https://github.com/kriskowal/q, which provides async promises framework to enable arbitrarily complicated chaining of AJAX requests. Q minified is about 3.3KB.
// The jQuery.ajax function returns a 'then' able
Q.when($.ajax(url, {dataType: "xml"}))
.then(function (data) {
var parsedXML = parseXML(data)
...
// some other ajax call
var urls = [Q.when($.ajax(url2, {data: {user: data.userId}})),
Q.when($.ajax(url3, {data: {user: data.userId}}))];
// run in parallel
return Q.all(urls)
})
.then(function (data) {
// data retrieved from url2, url2
})

jQuery filtering AJAX data and then replaceWith data

I am calling pages via AJAX in jQuery.
The content of these pages needs to be filtered so that i only grab a certain DIV class. In this instance 'Section1'.
This filtered data needs to replace the same data on the current page in the DIV of the same class.
I currently have this but it is not really working for me:
$("#dialog_select").live('change', function() {
//set the select value
var $optionVal = $(this).val();
//$(this).log($optionVal);
$.ajax({
type: "GET",
url: $optionVal,
dataType: "html",
cache: false,
success: function(data) {
var $filteredData = $(data).filter('.Section1');
$('.Section1').replaceWith($filteredData);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
I think your problem is likely here:
var $filteredData = $(data).find('.Section1');
$('.Section1').replaceWith($filteredData);
.filter() would only find top level elements in the response (if it's a page, that's <html>, and wouldn't have any results). .find() looks for decendant elements. Also keep in mind that if you have multiple .Section1 elements, this won't behave as expected and will have some duplication going on.
This is a tricky thing to do and I would recommend placing the data into something like a DOMParser or document.implementation.createDocument or MSXML.
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
is a basic code example. jQuery itself can filter on a selector with the load function. http://api.jquery.com/load/ This however has several limitations such as not being able to filter on html, head, or body tags. This is why the above method is safer.

Resources