Real-time load result (ajax) - javascript

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.

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

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

Returning data from ajax results in strange object

I know this question hast probably been asked a thousand times, but i cannot seem to find the answer. I want result to be the data returned from the ajax-request, which should be a json-data array (the result of console.log(data)).
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
aync: false
});
console.log(result);
However, console.log(result); will return some strange object, which I don't know how to handle. Why isn't result = data ?
Typo.
Change this:
aync: false
to:
async: false
And the ajax method still returns the jqXHR object doing the request, not the result. Use the data parameter in the success call and store it somewhere.
First of all remove the aync: false from your code. It should be spelled async: false but you don't need it to achieve your goal and what it actually does is block the entire browser's user interface resulting in a terrible user experience. Remember that "A" in AJAX means Asynchronous.
The result of an $.ajax() call is a promise which is not the same as your data, but it can still be useful to get to your data. You just need to use it in a certain way.
Try changing:
console.log(result);
to:
result.done(function (data) {
console.log(data);
});
or:
result.done(function (data) {
console.dir(data);
});
or even this might work - untested:
result.done(console.dir);
See this answer for a better explanation.
Initialize result inside success function.
var result;
$.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
result = data;
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
console.log(result);
There is a small spelling mistake aync: false should read async: false assuming of course that you require the request to run synchronously i.e. for the remainder of your code to wait for this result.
I think that the main issue here is that the result you are trying to output to the console is not being referenced by the ajax request.
It is entirely your choice how you reference the data returned by the ajax request, you chose the word data this could just as easily have been result or json_Data or return_Data or ....
Hence to send the result of the ajax request to the console I would suggest:
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(result) {
console.log(result)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
You mentioned console.log(result) returns a strange object, actually this strange object is known as xhr (XMLHttpRequest) object.
Since the call is syncronous because of async: false so it's easy to get the returned data like
var result = $.ajax({...}); // get the xhr object in to result
console.log(result.responseText); // xhr object has a "responseText" property
As because result.responseText will be available only after the request completes and there is no chance to execute this console.log(result.responseText); because of async:false, before the request completes because a syncronous ajax request hangs on everything before it finish the request.
In your success callback data will be an object because of dataType: 'json' but outside of success callback, i.e. console.log(result.responseText); will be only text so to use it as an object you have to convert it to an object using $.parseJSON(result.responseText).

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

Categories