Why cant I access the render function when ajax returns successfully? maybe im going crazy but i've done this before.
Its telling me that this.render is not a function?
DataItem.prototype = {
display: function () {
$('body').append(this.name + ": " + this.getData(this.rootData, this.subData) + "<br />");
},
getData: function (rootData, subData) {
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
this.render(json);
}
});
},
render: function (json) {
var res = [];
for(var i=0, t; t=json.log.entries[i]; i++) {
var p = t.request.url;
if (p!=undefined) res.push(p);
}
return res.length;
}
};
The scope has changed when you try to call this.render(). I believe this contains the ajax request object instead of the DataItem object.
A simple solution is doing like this:
getData: function (rootData, subData) {
var self = this;
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
self.render(json);
}
});
},
Edit: I was wrong, inside the success function the this variable contains the options for the ajax request, however my solution is still correct. See more in the jQuery documentation (http://docs.jquery.com/Ajax/jQuery.ajax#options)
Just to add to #adamse answer. If you want to externalize your success function instead of using an anonymous function you could use the following to pass additional parameters:
function handleSuccess(json) {
this.self.render(json);
}
$(function() {
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
// pass an additional parameter to the success callback
self: this,
success: handleSuccess
});
});
since the following code works (i.e "abcd" is printed), I am not sure what is the problem you are facing unless you would share more code.
<script>
DataItem = function(){};
DataItem.prototype = {
display: function () {
return 'a';
},
getData: function () {
document.write(this.render());
return this;
},
render: function () { return "abcd"; }
};
di = new DataItem();
di.getData();
</script>
Related
I want to delete a row from the table, but the success part of ajax does not execute.
function fn_delete() {
$("a.delete").click(function () {
idProduct = $(this).parents("tr").find("td").eq(1).html();
$.ajax({
type: "POST",
url: "DeleteProduct",
data: { idProduct },
success: function () {
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
}
});
});
};
this inside your success callback will not be the same as this in the code that makes the ajax call, unless you explicitly set the context:
$.ajax({
context: this,
data: ...
});
I don't think this is giving the value that you're expecting.
Try this:
function fn_delete() {
$("a.delete").click(function () {
idProduct = $(this).parents("tr").find("td").eq(1).html();
var myRow = $(this).parents("tr");
$.ajax({
type: "POST",
url: "DeleteProduct",
data: { idProduct },
success: function () {
$(this).parents("tr").fadeOut("normal", function () {
myRow.remove();
});
}
});
});
I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"
I have an array of symbols as shown below.
For each element of the array I am making an Ajax request.
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
$.each(symbols, function (index, value) {
loadXMLDoc(value);
});
});
function loadXMLDoc(value) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function (data) {}
}
In the browser console, I see many XHR requests under pending state.
Is it possible to make the next Ajax request only when the response has been obtained for the previous array element?
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
loadXMLDoc(symbols);
});
function loadXMLDoc(symbols) {
if(symbols[0]) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function(data){ loadXMLDoc(symbols.slice(1)) }
});
}
}
There is no value being used in loadXMLDoc in your question, I suppose you want:
url: 'https://ganaga/aaaa/'+ symbols[0],
Also, I would rename function to loadXMLDocs.
I would just use a little recursion:
var symbols = ["SSS", "SEE"]
$(document).ready(function () {
loadXMLDoc(0);
});
function loadXMLDoc(idx) {
value = symbols[idx];
if (value) {
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/' + value,
success: function (data) {
//...
loadXMLDoc(idx+1);
}
});
}
}
Invoke the next AJAX call in the callback function.
function loadXMLDoc(n) {
var value = symbols[n];
$.ajax({
type: 'POST',
url: 'https://ganaga/aaaa/sss',
success: function (data) {
if (n < symbols.length-1) {
loadXMLDoc(n+1);
}
}
}
}
Start it with:
loadXMLDoc(0);
I'm trying to pass an object around in JS (with some jQuery thrown in). :)
I want to call the FlappyBarHelper.getUserPropertyCount() method once the promise.success function has run. I've tried passing this.FlappyBarHelper to :
return $.ajax({
type: "GET",
url: 'get-the-score',
flappy: this.FlappyBarHelper,
});
But that still makes flappy undefined in promise.success
My full code is:
function Rating(FlappyBarHelper) {
this.FlappyBarHelper = FlappyBarHelper;
}
Rating.prototype.attachRaty = function(property_id)
{
var promise = this.getPropertyScoreAjax(property_id);
promise.success(function (data) {
$('#'+property_id).raty({
click: function (score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
})
.done(function (msg) {
$('#extruderTop').openMbExtruder(true);
//**** FlappyBarHelper is undefined at this point ****///
FlappyBarHelper.getUserPropertyCount('.flap');
});
}
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id)
{
return $.ajax({
type: "GET",
url: 'get-the-score',
});
}
Read from the documentation of ($.ajax](https://api.jquery.com/jQuery.ajax/)
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
Therefore you should pass your variable along the multiple call you are doing:
Rating.prototype.attachRaty = function(property_id){
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
// use proxy to keep context when the click will be received
click: $.proxy(function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// here it should be defined
this.FlappyBarHelper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
});
}
You can also consider making a closure variable:
Rating.prototype.attachRaty = function(property_id){
// here is the closure variable
var helper = this.FlappyBarHelper;
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
click: function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score'
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// you can still use the defined variable: power (and danger) of closures
helper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score'
});
}
How can I assign a variable(var) to a json object which is returned from ajax call to the server? I need to access that object in the rest of the body.
For example, I've try this, I don't know it's correct.
var selectValues=$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
})
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
Note that, variable selectValues is used in the rest of the body.
I think you should do the whole code inside the $(document).ready(function() function and then make the ajax call synchronous. Because now the ajax call will be made when the document is ready, but the other code will be run directly without waiting for the document to be ready. Also the ajax call is asynchronous by default, so you should make it synchronous and assign the selectValues variable inside the success function of the ajax call. It will become something like this:
$(document).ready(function() {
var selectValues;
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(data) {
selectValues = data
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
})
you have to define the var outside the document ready scope like this:
var selectValues;
$(document).ready(function() {
// ajax
});
in the onSuccess function you can define the selectValues = data or something like that
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: function (result){
var selectValues=result;
}
});
try this.
Here is how we extract the returned information from our (xml) ajax calls:
$.ajax ({
type: "POST",
url: "something.cgi?someparam=whatever",
data: "key=val&key2=val2",
dataType: "xml", // you use json, but I don't think it matters
success: function (data) {
if ($("error", data).text() === "") {
// I could assign $("error", data).text() to a var just here
// This gets the "error" parameter out of the returned xml or
// json, here contained in "data"
}
[snip the rest]
Another way to do this is to add the rest of your code in the success callback lik this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(selectValues) {
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
}
});
})