i have to get a value from my REST service and assign it to knockout observable
the code looks like
mydata=$.ajax({ url: 'http://myserver:7101/MUDRESTService/rest/v1/mudstats?onlyData=true',
type: 'get',
dataType: 'json',
success: function(output) {
dailyMinRest = JSON.parse(mydata.responseText).items[0].AvgSession;
console.log(dailyMinRest)
sessionCountRest = JSON.parse(mydata.responseText).items[0].Sessions;
}
});
self.dailyMin = ko.observable(dailyMinRest);
the problem is with the last line. if i keep here the obviously there is no guranteed for it to execute after rest returns the response. however, if i move it to inside the succss method then the self variable is not resolved.
Create the dailyMin observable immediately and then update it when your ajax request completes by calling the observable and passing in the new value:
self.dailyMin = ko.observable();
mydata=$.ajax({
url: 'http://myserver:7101/MUDRESTService/rest/v1/mudstats?onlyData=true',
type: 'get',
dataType: 'json',
success: function(output) {
self.dailyMin(JSON.parse(mydata.responseText).items[0].AvgSession);
}
});
BTW, I'm not sure why you're calling JSON.parse(mydata.responseText) instead of using the already parsed JSON response in output, but I'll assume you know what you're doing there :-).
Related
I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.
I am trying to update a FullCalendar object using a function that receives an array of events.
$('#sh1_cal').fullCalendar({
events: function(callback) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
//var events = [];
console.log("printing " + reply.first)
alert(typeof reply.first);
callback(reply.first);
}
});
}
});
Reply is intended to be an object containing two arrays as its properties. I'm extracting the first, and it seems that the typeof alert is returning the correct type, but the callback is not working. Any suggestions?
I have not used this plugin but from the docs (http://arshaw.com/fullcalendar/docs/event_data/events_function/) it looks like the events function takes 3 parameters: start, end, and callback.
Start and end are date objects indicating when the event starts and ends. The way you have it now, that function thinks there is a date object called 'callback' which is why you're getting the error. In JavaScript the name of the parameter is not important (for example you can call it 'cb' or 'foo' instead of 'callback') but the order is.
Try (untested):
$('#sh1_cal').fullCalendar({
events: function(start, end, callback) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
callback(reply.first);
}
});
}
});
Try this:
$('#sh1_cal').fullCalendar({
events: 'http://localhost:8080/getEvents'
});
Shouldn't be any need for writing your own ajax call, it's built in.
If that doesn't work, can you post the output of your JSON feed?
try this and let me know if it works:
$('#sh1_cal').fullCalendar({
events: function(cb) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getEvents',
dataType: 'json',
success: function(reply) {
return cb(reply.first);
//or try: cb(reply.first);
}
});
}(callback)
});
if not that, remove the return on the callback.
did either work?
*please note: I assume that "callback" is a function you are passing in and have instantiated it somewhere.
Event (As Function) in fullcalendar has been changed. Now the third parameter is timezone.
Further information on FullCalendar Documentation v2
In the most of the websites when I see the browser 'view page source', a lot of java-script array or JSON data is populated dynamically. I think this data we can get it from the database and store it in java-script array. Can any one suggest me how to add data dynamically from jQuery ajax call and assign it in array variable..
I tried with array push() method. but no luck.
Can any one suggest me how to do it?
You can do it as follows:
$.ajax({
type: "GET",
url: // Your URL,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var result = data.d; // your json data
$.each(result , function (index, value) {
myArray.push([value.property, value.property2]); // push array note `[]`
});
}
});
I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)
In the web app I am working on there is potential for very long running ajax queries.
I'm using jQuery's $.ajax method to do something like:
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){
// handle a success
},
dataType: "json"
});
Is there a way to modify the success callback after this._xhr.readyState = 2 (loaded) and before this._xhr.readyState = 4 (completed)
I tried modifying this._xhr.onreadystatechange but found that jQuery does not define onreadystatechange.
The abort method sounds like the best option to me.
I don't know much about the ajax method internals, but I can think of a few ways to do what you want. Both involve global state and would break if it's possible for your user to send a second request before the first has finished, so I'm not sure I recommend them.
First, you could keep a reference to the method that does your success work, and change it:
MySuccessMethod = function(d, m) { /* handle a success */ };
this._xhr = jQuery.ajax({
type: "GET",
url: "/path/to/service",
data: "name=value",
success: function(data, message){ MySuccessMethod(data, message); },
dataType: "json"
});
// later...
// user cancels request, so change the success method
MySuccessMethod = function(d, m) { /*print a simple message*/ }
Alternatively, you could just put all the logic in the one success method, and use a global flag to determine what to do:
success: function(data, message){
if (RequestHasBeenCancelled) {
//display a simple message
}
else {
// handle a success
}
},