Accessing DOM object after AJAX call? - javascript

I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click), so using something like .load() or .on() doesn't work here (as far as I know).
I tried setting the $.ajax() call to a variable: var new_div = $.ajax(...) but that didn't get me anywhere.

If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});

If you want to decouple your code from the callback:
functionWithALotOfStuffToDo = function(data){
// do stuff here
}
$.ajax({
url: url,
success: functionWithALotOfStuffToDo
});

how about:
$.ajax({
url: url,
success: function(data) {
$('body').append(data).find('#new_div').show();
}
});

Assuming the data being returned is something like <div id='new_div' /> then try something such as
var newDiv = null;
$.ajax({
url: url,
success: function(data) {
newDiv = $(data).appendTo($('body'));
}
});
This will add the <div /> to the body of your page, and assign the jQuery element to the variable newDiv which can then be accessed again at a later stage.
However, if you access newDiv before success has been returned, it will be null or the previous value, if it was assigned previously.

Actually this sort of things can be solved by following way:
(I know it is similar to others, but a little bit more clear)
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
afterHtmlAppendCallback();
}
});
function afterHtmlAppendCallback()
{
$('#new_div').show();
}

I think it's ajax async cause the problem you mention.
In jQuery ajax funciton API says:
Perform an asynchronous HTTP (Ajax) request.
If you want to access the data from ajax right after request
you should put you code in the ajax.success function like:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
Or turn the async setting into false
$.ajax({
url: url,
async:false,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
that will make sure the $('#new_div') selector gets the object

I have the same issue and find a method that was great.
If you have the jQuery functions in a file for example library_jquery.js, just load that file again in the success.
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
//LOAD THE SCRIPT FILE AGAIN
var path_script_file="libray_jquery.js";
$.getScript(path_script_file);
}
});

Related

Using jQuery event on ajax html response

I'm want to use jcarousel on an ajax html response. Here is how i use jcarousel on elements loaded with the DOM.
jQuery(document).ready(function() {
jQuery('#mycarousel-2').jcarousel({ wrap: 'circular' });
});
Now when i use ajax, the above code doesn't work on the returned html. What do i have to do to refire the jcarousel script?
var data = {
action: 'get_thumbnails',
id: id
};
jQuery.post(ajaxurl, data, function(response) {
});
call it inside ajax success callback to initate jcarousel again for dynamically loaded element
jQuery.post(ajaxurl, data, function(response) {
//success callback
jQuery('#mycarousel-2').jcarousel({wrap:'circular'});
});
Might not be the proper approach, but you may use jQuery's event delegation, I think it can be useful, if not in a straight way, then a tricky way :)
Hey buddy i believe that the right code for ajax is this
$.ajax(
{
type: "POST", /// your URL
url: pageurl + "/testajaxfunc1", /// backend function
data: '{"testval":"' + $('#testField').val() + '"}', /// data fields
contentType: "application/json;charset=utf-8", // content type
dataType: "json", // datatype
success: OnSuccessReturnValues, // function that it would initiate on success
error: OnError // function that it would initiate on Error
}
);
hope this help

Jquery response load

A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);

Append a php file with jquery

i have a file which echoes out data from a database.
I wish to have a load more button which appends this file so that it will keep loading the rest of the results.
The php page works fine but need help with the jquery...
have used this else where for a json return but dont think this is needed for this.
So i am trying this:
$(document).ready(function(){
$("#loadmore").click(function () {
$("#content").append('includes/loadmorebuilds.php');
});
});
In essence, this works but it appends 'includes/loadmorebuilds.php' as just that. I simply appends those words and not the file.
Any help on this?
Many thanks!
You could use $.ajax to get content from file to be appended into DOM. One important thing is that you should use Relative PATH to your web root on url parameter in $.ajax
So it will become like this
$('#loadmore').click(function() {
$.ajax({
url: '/relative/path/to/your/script',
success: function(html) {
$("#content").append(html);
}
});
});
And make sure you should be able to access your script on http://www.example.com/relative/path/to/your/script
You have two options:
$('#content').load('includes/loadmorebuilds.php');
Which will replace the content of #content with the new html.
Or this:
$.ajax({
url: 'includes/loadmorebuilds.php'
}).done(function(data) {
$('#content').append(data);
});
Which will append the new data.
use $.ajax
$(document).ready(function(){
$(".loader").click(function(){
$.ajax({
url:"index.php",
dataType:"html",
type:'POST',
beforeSend: function(){
},
success:function(result){
$(".content").append(result);
},
});
});
});

Why isn't this function triggered upon .click?

We need to load a given function on page load. Then, we should repeat that function execution, each time a given button is clicked. How can we do that?
Here's the code:
$(function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
});
$('.addMember').click(showMember);
showMember doesn't trigger uppon click.
Can anyone please explain with detail, why is that ?
that is because your created function is in limited scope $(function ..)....
you can simply do
$(function(){ //document.ready function
showMember(); //call showmember when document is ready
$('.addMember').click(showMember); //call same function when clicked
});
function showMember() {
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}
As an addendum to bipen's answer: the reason your code does not work is because you don't seem to get what $ is.
Since you have tagged your question with jQuery, I assume that you are using it. When you include the jQuery library in your code it gives you a function called jQuery. This function is aliased as $. That is, $ is the same as jQuery.
When you call a function in javascript you can pass in arguments:
parseInt('1234');
At the top of your code you are calling $, and passing a function definition as an argument. So
$(function showMember()...
is the same as
jQuery(function showMember()...
That is syntactically correct, but limits the scope of the function to the list of arguments you have passed to the $ function. Once that call is complete the function showMember will no longer exist.
This is why you code does not work.
Here are few points:-
You don't need to call $(function showMember() like this.
You need to call it like function showMember() simply.
Also, you need to call the click function inside the DOM ready method.
Just to make sure that your click event is fired when the DOM is fully loaded, as follows:
$(document).ready(function () {
$('.addMember').click(showMember);
});
OR
$(function () {
$('.addMember').click(showMember);
});
When you pass custom function inside event handler (i.e click, change etc ) then you need to create function as normal, You do not need wrap function within $();
And also do not forget to wrap code inside $(document).ready();
function showMember()
{
$.ajax(
{
success: function(html)
{
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>',
data: {index:$('#members div>h3').size()},
cache: false,
dataType: 'html'
});
}
$(document).ready(function(){
$('.addMember').click(showMember);
});
You need to use ready function when using jQuery
$(document).ready(function(){
$('.addMember').click({});
});
Try this:
$('.addMember').click(function(){
showMember();
});
function showMember(){
$.ajax({ //Perform an asynchronous HTTP (Ajax) request.
success: function(html){
$('#members').append(html);
},
type: 'get',
url: '<?php echo $this->createUrl('member'); ?>', //A string containing the URL to which the request is sent.
data: {index:$('#members div>h3').size()},
cache: false, //if false, it will force requested pages not to be cached by the browser.
dataType: 'html' //The type of data that you're expecting back from the server.
});
}
you may have this lement bind dynamically,
so I think you need to bind it after all binding is complete :
$('.addMember').live('click', function(){
showMember(); return false;
});

Real-time load result (ajax)

I dont know how write this script. I need load results with some URL (eg: localhost/index.php?action=get&type=29) and this result to give a variable for further processing. I need create this on Jquery. Thanks.
There are features in jQuery that can be used, you have either a quick load using the simple .load() function that will parse the HTML into an element. Usage:
$('#element').load('http://www.urlgoeshere.com/');
With processing events with AJAX with further writing options, you have many options to choose from:
http://api.jquery.com/jQuery.ajax/
These options below are using the .ajax() function but makes the writing easier:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
EDIT: With your "refresh", you can use the setTimeout function to repeat the ajax call:
setTimeout(function()
{
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
}, 1000); // This will "refresh" every 1 second
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
you can use
$.ajax({
url: "localhost/index.php",
data: "action=get&type=29",
success: function(data, status, xhr){
// data is the response from the server, status is the http status code,
// xhr is the actual xhr
},
error: function(){
},
...
});
to get the results.
Be sure to define the success and error callbacks to process the data when it is returned.
Look here http://api.jquery.com/jQuery.ajax/ to get started.

Categories