Using jQuery event on ajax html response - javascript

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

Related

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);

Accessing DOM object after AJAX call?

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);
}
});

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;
});

JSON data not responding

Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks

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