Backbone set model inside ajax request - ajax

Hi all I have an app in Backbone where inside a function I want to convert price from GBP to EUR for example using a php file called with ajax.
In the success function I want to assign the converter data to my object.
But seems that not setting this because into the template uin underscore there is always the old value.
This is my function inside my model:
toJSON: function() {
var json = _.clone(this.attributes);
json.rooms = this.rooms.toJSON();
_.each(json.rooms, function(room){
var converter ="<?php echo(site_url('/backend/hotel/ajax_currency')); ?>";
$.ajax({
url: converter,
type: "POST",
data: {
from_currency : room.currency,
amount : room.price_adult
},
dataType: "json",
success: function(data) {
console.log(data);
room.price_adult = data;
}
});
});
return json;
},
I have also tried:
room.model.set('price_adult',data);
but return me error that don't find model.
How can I solve?

This is not a thing you want to put in toJSON function, I can think of several reason why it should work for you. The most important one is that toJSON function is synchronous and the AJAX response is async. so your render function is happening before you get the response from your ajax.
I would suggest having a Room model that will be responsible for the concurrency, and it's view will render it when ajax has returned and the price_adult is ready.
var Room = Backbone.Model.extend({
initialize:function(){
this.convertConcurrency();
},
convertConcurrency:function(){
var model = this;
$.ajax(.....,
success:function(data){
model.set("price_adult", data);
}
);
},
});
var RoomView = Backbone.View.extend({
initialize: function(){
this.listenTo(this.model, "change:price_adult", this.render);
if (this.model.has("price_adult")) this.render();
},
.....
});
var Rooms = Backbone.Collection.extend({...})
var RoomsView = // Rooms collection view
This way the view will be rendered only when there is a price_adult ready.
Maybe you should create a model on the client that gather the concurrency information from the server and compute the concurrency conversation by itself, so you will only have one ajax and the model will compute it for you instead of the server.

Related

Django: correct way to pass AJAX

I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

How to populate array with data returned from ajax call?

I'm making a call to an app to fetch data (routes), then looping through that data to fetch additional data about each individual route. The final data will show up in console.log without a problem, but I can't get it into an array.
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var routes = [];
$(data).each(function(i){
routes.push(data[i]._id);
});
function getRouteData(route, callback) {
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json',
success: function(data) {
callback(data);
}
});
}
var route_data = [];
$(routes).each(function(i) {
getRouteData(routes[i], function(data) {
console.log(data); // this shows me the 13 objects
route_data.push(data);
});
});
console.log(route_data); // this is empty
});
nnnnnn's right, you have to use Deferreds/promises to ensure that route_data is populated before sending it to the console.
It's not immediately obvious how to do this, with particular regard to the fact that $.when() accepts a series of discrete arguments, not an array.
Another issue is that any individual ajax failure should not scupper the whole enterprise. It is maybe less than obvious how to overcome this.
I'm not 100% certain but something along the following lines should work :
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var route_promises = [];
var route_data = [];
function getRouteData(route) {
var dfrd = $.Deferred();
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json'
}).done(function(data) {
//console.log(data); // this shows me the 13 objects
route_data.push(data);
}).fail(function() {
route_data.push("ajax error");
}).then(function() {
dfrd.resolve();
});
return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail.
}
$(data).each(function(i, route) {
route_promises.push( getRouteData(route) );
});
//$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary.
$.when.apply($, route_promises).done(function() {
console.log(route_data);
});
});
untested
See comments in code.

How to call partial view through ajax in mvc3

I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.
$("#UserName").change(function () {
var userid = $("#UserName").val();
var ProvincialStateID = $("#State").val();
var Hobbyid = $("#Hobby").val();
var Districtid = $("#DistrictNames").val();
var Homeid = $("#Hobbyhome_EstablishmentId").val();
var urlperson = '#Url.Action("FetchPersonByUserName")';
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
//Dont know what to write here
});
});
Here is the function that I have written in my Controller:
[HttpPost]
public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
{
//Code to fetch the data in the partial using all parameters
return PartialView("_LearnerAssociationGridPartial", list);
}
When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view
What you need is something like
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid,
stateid: ProvincialStateID,
hobbyid: Hobbyid,
districtid: Districtid,
homeid: Homeid },
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
it is recomended to not use data straight from variable but you can.
Now target location is where you want the result to be displayed to.
See more information in here:
http://api.jquery.com/jQuery.ajax/
As to slow fetching data, try optimalize your query
Update
For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.
I dont understand what you mean by redirect to the parial view. Usually people use ajax and Partial views to get part of a page without a page refresh ( you might have seen this kind of behaviour in this site/facebook/twitter etc..) So i guess you probably want to show the data you are fetching asynchronosly to be shown in a part of your current page. you can do that in your success handler
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
$("#divUserInfo".html(data);
}
});
Assumung you have a div with id divUserInfo in your current page.
If you really want to redirect after the ajax post, you can do it like this.
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
window.location.href="Why-I-need-Ajax-Then.php";
}
});
Personally, I dont use HttpPost (both in client and server) If it is a method to GET some data. I simpy use the jquery get or load.
$.get("yourUrl", { userid: userid, stateid: ProvincialStateID } ,function(data){
$("#divUserInfo".html(data);
});

Resources