I'm making an AJAX call to a JSON page that grab variables to populate a playlist for an HTML5 music player. I'm trying to have it so the playlist data updates every minute since its grabbing the information from a radio. I also dont want it to refresh the player itself, only the playlist. Everything works great except I'm getting myPlaylist is not defined I'm also trying to come up with the best way to refresh the AJAX call every minute... but one thing at a time.
$(document).ready(function(){
function ajax_playlist(str1, callback){
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function(data, status, xhr){
callback(data);
console.log(arguments);
}
});
}
ajax_playlist("str", function(pl) {
myPlaylist = [
{
mp3:'http://radio.gnradio.org:9966/vod/mp4:audio/file.m4a/playlist.m3u8',
artist:pl.data[0].track.artist,
title:pl.data[0].track.title,
cover:pl.data[0].track.imageurl
}
];
});
var description = 'Welcome to SilvertoneRadio.com BETA Online player. We will be gradually improving it.';
$('body').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description,
jPlayer:{
swfPath:'plugin/jquery-jplayer' //You need to override the default swf path any time the directory structure changes
}
});
});
myPlaylist is defined when the anonymous function passed to ajax_playlist is called.
That function is passed as the argument named callback.
That is called in the success function passed to the ajax method.
Asynchronous JavaScript and XML is asynchronous.
The success function won't be called until the HTTP response is received and processed.
So what happens is:
Ajax HTTP request is sent
description has a value assigned to it
ttwMusicPlayer is called (with myPlaylist which is currently undefined)
HTTP response is received
myPlaylist gets a value assigned to it
Move all the code that depends on myPlaylist having a value into your callback function.
AJAX is asynchronous, anything that depends on its result MUST be called in the success callback!
Move the ttwMusicPlayer call inside the function(pl) { ... } block (after the myPlaylist = [...];)
Related
I've never done this type of manipulation of AJAX calls (to stop/abort/cancel or ignore? already running AJAX calls before the execution of a new one) before so I really don't understand how to do that and would appreciate some direction.
I have a page in my app where I make a number of AJAX calls to fill dynamically the data in my table (Object Name, Object Fit, Object Progress) when the page loads. For example, there are 5 rows in the table. So I call
$.post("/getFit", {objectId: objectId}, function (result) { manipulation with result }
and
$.post("/getProgress", {objectId: objectId}, function (result) { manipulation with result }
5 times each in the loop -- one for each of the objects.
The first column of my table has links to more detail on the object, and clicking on them I call another AJAX:
$(document).off('click', '.js_object').on('click', '.js_object', function (e) {
var objectId = $(this).attr("id")
$.post("/viewObject", {objectId: objectId}, function (result) {document.getElementById("main_window_content").innerHTML = result; });
})
The problem is that the browser will not render the results of the last AJAX call (/viewObject) until it has received the results of all of the previous calls (/getFit x5 and /getProgress x5).
As a result, a user that wants to drill into the detail on an object needs to wait until the AJAX calls for the other objects are complete before they see anything.
So I struggle with how to stop/abort/cancel (or ignore?) "/getProgress" and "/getFit" so we can fully execute "/viewObject" and view the results of it.
I would very much appreciate your help.
Use xhr.abort() to kill the xhr requests as shown in the below code in JS. I believe there is ajax.abort(); in JQuery
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
If you want execute one ajax after another, and you need all requests to work to show the final result, you can use .done():
$.ajax({
url:'/getFit',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /getProgress
$.ajax({
url:'/getProgress',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /viewObject
$.post("/viewObject"....
})
});
That way you only show /viewObject if the others calls were successfull
I have an onclick event for a radio button that calls a function which launches period AJAX calls to some url
Example in MVC cshtml view
<script>
function onClick(selectedRowId) {
GetData("/home/GetData/" + selectedRowId);
};
</script>
Ajax call
function GetData(url) {
$.ajax({
url: url,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: onSuccess,
error: onError,
complete: function (xhr, status) {
setTimeout(function () {
GetData(url);
}, 10000);
}
});
}
When a different radio button is selected I need to call the onClick method with the selected radio button id and this again initiates a call to the url with the different id.
However, I would like the previous AJAX function call to terminate since the AJAX onSuccess method updates an html element with the data retrieved for that specific selected Id.
Any way to signal the previous call to terminate before launching new one ?
One way to solve this could be
a) Not make id as a paramter to the url call then
b) in the onClick method send a call to Server to set the Id variable (this makes the server aware that all data must be returned for that Id)
c) Then ensure that ajax function is called only once and server will change data returned based on Id information conveyed to it in (a)
Not sure if the server round trip is worth it here for every button click.
The best I can think is each time onClick fired, it needs to cache the selectedRowIndex which you are only interested in the latest selected one. As you mention, the server need to return that ID back. That way on your onSuccess function, you only need to process returns that matched ID and ignore any other.
I don't think you can literally stops previous ajax. You don't have access to the previous ajax object any more. Just ignore previous responses.
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
I'm trying to retrieve the data I submitted to an asynchronous ajax request should the back-end fail in some way. The data in 'myJSONData' is actually pulled off a queue (array) in memory and I need to put it back into the queue if any kind of error occurs.
e.g.
var myJSONData = {"parm1":"value1","parm2":"value"};
$.ajax({
type: "POST",
url: "/postData.ajax",
dataType: "json",
data: myJSONData,
success: function(jsonReply) {
// I need to refer to the posted data here (i.e. myJSONData)
},
error: function(xhr,ajaxOptions,thrownError) {
// I need to refer to the posted data here (i.e. myJSONData)
}
});
My code fires off a number of calls at various times, the trouble is that if I refer to myJSONData within the success or error blocks it contains the most recent value of that variable in memory, and not what was in the variable at the time of the ajax call.
Is there some other way to access the data associated with the particular instance of ajax call - something like $.ajax.data ?
You should be able to access it in your success and error functions :
success: function(jsonReply) {
var p1 = myJSONData.param1;
}
I have the following code:
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function () {
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
});
When a user changes some data the code updates the database. There is code that comes before this that picks the data values and it all works good.
When the user changes the Position column the database gets changed and I wanted to trigger a refresh of the screen (it's a report screen sorted by position). The refresh works but it seems like it is out of sync. I have the location.reload() in the success area but is it possible that is getting run before the Ajax has completed?
Is it possible that this kind of refresh is taking place before the database has been properly updated? When I do another refresh of the page manually from the browser the data always appears in the correct order.
Your document is cached. You shouold use
location.reload(true)
to realod with clear cache.
AJAX is asynchronous by default. Once the call is issued, the rest of your code will continue executing. If the value of location gets changed before the ajax call returns its data, the success function will be using the current-at-the-time-it-executes value of location, which is now something different than what it was when the ajax call started.
The success code will not run until the ajax call returns, so that's not the problem. but you're depending on location not being changed between the time you start the ajax stuff and the time it completes.
there is a API in jquery ajaxComplete. whenever a ajax call will be completed this will be invoked.
$.ajaxComplete(function(){
//do something
});
reference : http://api.jquery.com/ajaxComplete/
Whatever you write inside the success handler will be executed only after the completion of the ajax request you made to the server page. so you can load the updated content in that handler.you can use a parameter to accept the response from your success function and check whether your transaction is success or not.
From your server page, after making the database update,you can return true or false.
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function (data) {
// This will be excuted only after you receive a response from your server page
if(data=="true") //db updated properly
{
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
else
{
alert("Error in updating the data");
}
}
});