I have a jquery mobile based implementation of a mobile website and now learning backbone.js and rethinking the app to better organize it.
var membership = Backbone.Model.extend();
var memberships = Backbone.Collection.extend({
model: membership,
parse: function (resp, xhr) {
},
url: "/groups.svc/memberships/azxcv01"
});
var col1 = new memberships();
col1.fetch({ success: function () {
console.log(col1);
}
});
In chrome, I see that the URL is formatted well and returns valid JSON back. The parse() event also gets a valid resp. But the console.log() above displays and empty array "[ ]".
What am I missing ?
try this,
here link to fiddle http://jsfiddle.net/w7xeb/ (updated)
var membership = Backbone.Model.extend();
var memberships = Backbone.Collection.extend({
model: membership,
parse: function (resp, xhr) {
return resp;
},
});
var col1 = new memberships();
col1.fetch({
url : "/restful/fortune",
success: function () {
console.log(col1);
}
});
response
$.mockjax({
url: "/restful/fortune",
responseTime: 750,
contentType: "text/json",
responseText: [{
a:'a'
},{
a:'b'
},{
a:'c'
}]
});
Related
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
I have the following Web Api method, which works fine as far as creating a new product and setting the location. I know this because I check the response header in Google developer tools and see that it is valid. If I cut and paste the location from tools to the browser, the page loads fine. However, it will not load as a result of returing the response from the method.
public HttpResponseMessage PostProduct(Product product)
{
productsRepository.Create(product);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
string uri = Url.Link("ProductsIndex", null);
response.Headers.Location = new Uri(Request.RequestUri,"/Products/testview");
return response;
}
The jQuery that calls PostProduct:
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
// Send an AJAX request to create a new product
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
$.ajax({
url: '/api/productsapi',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8'
});
return false;
});
Why is the location being ignored?
Well, I added
statusCode: {
201 : function() {
window.location.replace("/Products/testview");
}
to my jQuery click function and got to the desired page that way. But should not the original way have worked?
First of all I looked trough a lot of same questions on stack. My problem is as follows:
I'm working on a school project to make a card game (ginrummy)
In this web application (mvc 4) I want to move cards to sets (right side) and I want to do this with ajax.
added a picture to clearify.
The ajax perfectly triggers the controller and perfectly bring over the data I put through.
In firebug I checked the response and it even added a card to the right correct set
The problem is when the ajax is done, it doesn't trigger the succes function neither it updates the page.
Note: This is my first time I work with ajax.
The complete function returns OK status.
Now the code:
View:
var GameId = #Model.Id
$(function () {
$(".droppable").droppable({
drop: function (event, ui) {
var id = ui.draggable.find("a").attr("data-CardId");
var location = droppableId = $(this).attr("id");
$.ajax({
type: "POST",
url: '#Url.Action("ChangeCardLocation")',
data: { 'id': GameId, 'cardId': id, 'location': location },
succes: function () {
alert('wow');
},
complete:function (){
}
});
}
});
});
Controller:
public ActionResult ChangeCardLocation(int id, int cardId, Location location)
{
var game = db.Games.Find(id);
var card = db.Cards.Find(cardId);
game.ChangeCardLocationTo(card, location);
db.SaveChanges();
game.Info = game.GetInfo(id);
if (game.GameState == GameState.playerOneLayOn || game.GameState == GameState.playerTwoLayOn)
{
return View("LastTurn", game);
}
else
{
return View("Details", game);
}
}
Any suggestions on what is going wrong?
I'm a student and it is for a school project!
#comment:
When I did this:
error: function(xhr, error){
console.log(error);
console.log(xhr);
},
I noticed it didn't get triggerd.
After that I tried the same in complete:
complete:function (xhr, error){
console.log(error);
console.log(xhr);
}
The result was
succes
object that returned readystate 4
I misspelled success thats in the first part it wasn't working. But my next question is how do make it updating the contents of the page that the ajax call is getting back.
I am trying myself offcourse now. In the data succes is getting is my whole page delivered as I want to have it.
Is it because you have misspelt "success"?
$.ajax({
type: "POST",
url: '#Url.Action("ChangeCardLocation")',
data: { 'id': GameId, 'cardId': id, 'location': location },
success: function () {
alert('wow');
},
complete:function (){
}
});
Hello I have the following code which uses knockout.js,
var allJobberDetailsArray = [];
getAllJobberDetailsArray();
function getAllJobberDetailsArray() {
$(function() {
$.ajax({
url: 'http://example.com',
type: 'GET',
data: {
request: "yes",
getAllJobberDetailsArray: "yes"
},
success: function(data) {
allJobberDetailsArray = data;
}
});
})
}
// ViewModel
function JobberCheckBoxListUserControlViewModel() {
var self = this;
self.allJobberDetailsArray = ko.observableArray(allJobberDetailsArray);
}
ko.applyBindings(new JobberCheckBoxListUserControlViewModel());
any change to allJobberDetailsArray I would like to update the UI automatically say an array item is added updated or deleted i would like the UI to reflect it.
How do i achieve it?
EDIT
var allJobberDetailsArray = ko.observableArray();
getAllJobberDetailsArray();
function getAllJobberDetailsArray() {
$(function() {
$.ajax({
url: 'http://example.com',
type: 'GET',
data: {
request: "yes",
getAllJobberDetailsArray: "yes"
},
success: function(data) {
allJobberDetailsArray.removeAll();
allJobberDetailsArray.push(data);
},
});
})
}
// ViewModel
function JobberCheckBoxListUserControlViewModel() {
var self = this;
self.allJobberDetailsArray = allJobberDetailsArray;// allJobberDetailsArray is now observable but any change to this doesn't reflect in the UI
}
var viewModel = new JobberCheckBoxListUserControlViewModel();
ko.applyBindings(viewModel);
in the above code i made the array itself observable and trying to auto update the UI if there are any changes to the array how do i achieve it?
Firstly the array you are updating isn't an observable array. Secondly your success callback actually overwrites the array. Finally you do not keep a reference to your viewModel so you are unable to properly update the observable array. ObservableArray wrap real arrays to make them observable. All add's removes etc need to go through the observableArray so the subscribers can be notified.
Try this instead.
// ViewModel
function JobberCheckBoxListUserControlViewModel(initialArray) {
var self = this;
self.allJobberDetailsArray = ko.observableArray(initialArray || []);
}
var viewModel = new JobberCheckBoxListUserControlViewModel();
function getAllJobberDetailsArray() {
$(function() {
$.ajax({
url: 'http://example.com',
type: 'GET',
data: {
request: "yes",
getAllJobberDetailsArray: "yes"
},
success: function(data) {
viewModel.allJobberDetailsArray(data);
}
});
})
}
ko.applyBindings(viewModel);
I would also recommend refactoring to put the getAllJobberDetailsArray method inside your viewModel so it doesn't polute the global namespace and maintains encapsulation.
Hope this helps.
I am returning a simple string from a webmethod to a Javascript function.
I am using an AJAX enabled website in ASP.NET 2.0. I get the date in firefox but inside IE 8 it returns undefined.
Do I have to parse the string in the JSON format using some serialize class? In my webmethod, I am just using:
return DateTime.Now.ToString();
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getDet',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:OnSuccess,
failure: function(msg){
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert('error fetching values from database');
}
});
});
function OnSuccess(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert(msg);
}
});
Edit
It seems the success function is firing the problem is with response 'alert(msg)' works in firefox but not in IE 8 with asp.net 2.0
Maybe you dont want to use this, but I´m very happy with the asp net ajax build in function, since it builds a header, that works properly on browsers.
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
var proxy = Sys.Net.WebServiceProxy;
proxy.invoke("", // if current page "", if webservice "/srv.asmx"
"getDet", //method name
false, //post = true, get = false
{ categ : trgId }, //javascript object
OnSuccess, // Success Function
onError, // Error Function
{ yourOwn : userData } // Custom User Data to Handler
);
});
function OnSuccess(response, usercontext)
{
// usercontext.yourOwn === userData;
// response is sent WITHOUT "d", it is removed internally by the proxy
alert(response);
}
});
Dont forget to include the ScriptManager...