Sticking the content of .load into a variable - ajax

Is it possible to use jQuery's .load and stick the loaded content into a variable so I can use the variable and append it to something else later on?

You can, but this is unnecessary. Use the $.get method to directly access the response instead.
$.get("foo.php",function(response){
console.log(response);
});
If you want to do both, (i.e. load the response into a div and use the returned data), you can use the callback on the $.load method similarly.

According docs:
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
So you can create function to save your response:
$('#result').load('ajax/test.html', function(responseText, textStatus, request) {
alert(responseText);
});
Other approach is to use $.get or $.post methods:
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert(data);
});
$.post('ajax/test.html', function(data) {
$('.result').html(data);
alert(data);
});

$(selector).load(url);
Is just a shorthand for:
$.get(url, data, function(response) {
$(selecton).replaceWith(response);
});

You can try something like this in AJAX
$.post(yourfile,function(response) {
//div hidden with the html of your page
$("#hiddendiv").html(response);
});
OR with get
$.get(yourfile,function(response) {
//div hidden with the html of your page
$("#hiddendiv").html(response);
});

In that case use GET, POST or AJAX method of jquery.
.load method of jquery internally uses asynchronous http request only and so all above mentioned methods.

Related

Why Does An AJAX Request Have To Have This?

<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
});
</script>
why does an AJAX request have to have a placeholder for the function? (in this case it is 'data'). If you remove it, or use any other word it still works fine. Can someone please explain why?
Your data here is an alias for returned value (the "answer" for your ajax request to script.php), so you can reefer to it. It is NOT the placeholder for function itself.
How you name it is up to you - just like with names of lambda parameters in c++ (I find them similar to JavaScript anonymous functions in that case):
[](string data){
... = data...
}
or with "out" parameters of functions/methods in other languages.
For the C++ analogy: how it would look to pass an lambda as a parameter to another method (you would have to define the Button class of course):
button.click(/*...,*/ [&](string data){ //"on success"
MessageBox(NULL, data.c_str(), "Alert", NULL);
...
});

call ajax with mootools

Hi everyone I call ajax with mootols and obtain this error, I looking for internet but dont find anything
this is my code to call ajax
$$('.item-129 a').addEvent('click', function(event){
event.stop();
var req= new Request({
method: 'get',
url: '<?php echo JURI::root()?>index.php?option=com_content&view=article&id=6',
data: {'do': '1'},
onComplete: function(responseText){$('textos').set('html', responseText);}
}).send();
});
and this the error
TypeError: $("textos").set is not a function
anonymous()mootoo...ssed.js (lĂ­nea 959)
return self.apply(bind, args || arguments);
any idea!!!
it means that either:
the element is not found
you don't use mootools 1.2+, hence no set method, unlikely given you use Request and not ajax
jQuery has the $ or something else, which does not have the .set method
try first of all:
onComplete: function(){
console.log($("textos"));
}
if this responds, see what it returns. if you use jquery, it will return the wrapped jquery function. if it's mootools, it will be an element.
if you have jquery, mootools will silently drop to document.id instead.
so. write as document.id('textos').set('html', responseText)
if with document.id('textos') you don't get an element either, it's not found.

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

How can I manipulate an Ajax response before it's injected into the DOM?

Here is what I have so far:
$(function () {
dataValModify('body');
$('body').bind('ajaxSuccess', function (e, xhr, settings) {
dataValModify(xhr.responseText);
});
});
function dataValModify(elem) {
// Code to modify elements within the response.
}
How can I take the Ajax response and modify it before it is injected into the DOM? Previously, I was binding ajaxComplete and modifying the DOM directly after injection, but I would like to modify the response instead. I don't think it makes a lot of sense to find elements in the Ajax response and use them to modify the DOM. I send the xhr.responseText into my function so that I don't reapply the modifications to the rest of the body, which will have already been modified by the time of an Ajax call. Also, is there something better than xhr.responseText to use for this? I couldn't get xhr.responseHTML to work.
EDIT: Right now I'm just using a simple test Ajax call to return an MVC partial view:
$('#ajaxTest').load('<MVC Route>')
If I'm understanding your requirements correctly, they are as follows:
Make an asynchronous HTTP request to get some HTML
Modify the returned HTML using the dataValModify() function
Insert the modified HTML into your element with the ID: 'ajaxTest'
If so then it sounds to me like you need to make a lower level ajax call than what you're using at present i.e. $(elem).load()
Essentially the call to .load() is a wrapper for $.get() followed by a call to $(elem).html(someContent) where "someContent" is the responseText from the HTTP request.
Therefore if you want to modify the response before it's injected into the DOM, then you can do something similar to the following:
$.ajax({
type: "GET",
url: "<MVC Route>",
dataType: "html",
success: function(jqXHR, textStatus, errorThrown){
// Your HTTP call was successful but nothing else has happened with the response yet
// Therefore you can now do whatever you want with the it...
// First modify the HTML using the dataValModify function
// Assumption being that your function returns the modified HTML string
var myModifiedHTML = dataValModify(jqXHR.responseText);
// Inject the modified HTML
$('#ajaxTest').html(myModifiedHTML);
}
});
You can use ajaxComplete to modify the responseHTML itself.
$('body').ajaxComplete(function(e, xhr, settings) {
dataValModify(xhr.responseHTML);
});
Update: I haven't tried it, but it might help:
$.ajaxSetup({
converters: {
"text html": function( textValue ) {
if ( valid( textValue ) ) {
// Some parsing logic here
return dataValModify(textValue );
} else {
// This will notify a parsererror for current request
throw exceptionObject;
}
}
}
});
More info here: http://api.jquery.com/extending-ajax/

load doesn't trigger ajaxSetup complete handler on complete

I have
// Ajax setup
$.ajaxSetup({
beforeSend: function() {
$('#general-ajax-load ').fadeIn();
},
complete: function() {
$('#general-ajax-load ').fadeOut();
}
});
on page load to set loading animation for all my ajax calls. It works perfect, except for load() calls. For loads only beforeSend is triggered, and complete never gets called, Which results with showing animation which never dissapears.
Any idea?
According to http://bugs.jquery.com/ticket/4086#comment:4, the "correct" way would be:
$(document).ajaxSend(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeIn();
});
$(document).ajaxComplete(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeOut();
});
I just did some testing and that indeed seems to work in all cases (including $.load).
Adding success fixed the problem, thanks (I can swear I tried it before)
$.ajaxSetup({
beforeSend: function() {
$('#general-ajax-load ').fadeIn();
},
complete: function() {
$('#general-ajax-load ').fadeOut();
}
success: function() {
$('#general-ajax-load ').fadeOut();
}
});
:)
The $.load manual says:
...It is roughly equivalent to
$.get(url, data, success) except that
it is a method rather than global function and it has an implicit
callback function.
It would seem that $.load's implicit callback function is overriding the complete callback in your $.ajaxSetup. The $.ajaxSetup documentation says:
All subsequent Ajax calls using any
function will use the new settings,
unless overridden by the individual
calls, until the next invocation of
$.ajaxSetup().
I guess the solution would be to replace your $.load calls with $.get (or the more verbose $.ajax). You could also try using success instead.

Resources