Django: correct way to pass AJAX - 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.

Related

Php FormData is null

I have a form with id: formC, on submit i call ajax:
var datiForm = new FormData();
var pos = [];
var i = 0;
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
pos[i] = $(this).find("input[type=checkbox]").data("id");
i++;
}
});
datiForm.append("nome",nome.val());
datiForm.append("cognome",cognome.val());
datiForm.append("email",email.val());
datiForm.append("telefono",telefono.val());
datiForm.append("dataNascita",dataNascita.val());
datiForm.append("titolo",titolo.val());
datiForm.append("ruolo",ruolo.find(":selected").data("ruolo"));
datiForm.append("sede",sede.find(":selected").data("sede"));
datiForm.append("posizione",pos);
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
$.ajax({
type: "POST",
data: {datiForm: datiForm},
url: "saveCandidate.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var position = data;
}
});
I have a problem, on server $datiForm = $_POST["datiForm"]; is null why?
Moreover i have input file where i can select file pdf. I put it in FormData:
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
You specified the data field incorrectly, it should be just the form data object
data: datiForm,
also the way you add posizione is not going to work, each entry in yrh array has to be added individually
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
datiForm.append("posizione["+i+"]", $(this).find("input[type=checkbox]").data("id"));
i++;
}
});
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
Yes
You'll need to specify the 'contentType' attribute to 'multipart/form-data' in order to upload files.

zf2 and ajax I can't get the parametrs

I can not get the data passing from the controller ajax me there any solution?
button click action
$(".bajaAlumno").click(function () {
var urlform = "<?php echo $this->url(null, array('controller'=>'Academius','action' =>'bajaAlumnos' ) ); ?>";
var dato= $(this).attr('id');
var myData = {textData:dato};
$.ajax({
type:"POST",
url:"/Academius/bajaAlumnos",
data:{data:myData},
success: function(data){
//The callback function, that is going to be executed
//after the server response. data is the data returned
//from the server.
// Show the returned text
//$("#answer").text(data.text);
//$("#answer").text(data.text);
alert('enviado');
}
});
});
and controller
public function bajaAlumnosAction()
{
die(var_dump($this->params()->fromPost()));
}
one answer?

Backbone set model inside ajax request

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.

Appending data on an area in the view MVC

$("##ViewBag.PageGroupID").append(data);
Now ViewBag.PageGroupID returns the id of the div at runtime.What if i want to append data in the div(the id which i will get runtime).How do i acheive this?
$('#btnPageElementClick').click(function () {
var flag = false;
var b;
$.ajax({ type: 'GET', url: '/ScriptedTestCase/pageElementPV/' + $('#PageElements').val(), data: null,
success: function (data)
{
$("##ViewBag.PageGroupID").append(data); //where divID is the id of the div you append the data.
}
});
return false;
});
Make sure that inside the controller action that rendered the view that contains the script you have shown, you have actually set this data:
ViewBag.PageGroupID = "someDivId";
Also note that in HTML ids cannot start with numbers.

How to pass div's html to #Url.Action in Ajax post

A. Where I am so far successfully:
I have 3 divs"
NewAction
NewController
NewArea
I have an $.Ajax post with the url currently as follows
'#Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" })'
I have several pages that require this particular Ajax post so I put the Ajax post in a partial, and each main page that uses it, has a parameter in the partial call, eg:
#Html.Partial("_PartialPage", new [] { "NewAction", "NewController", "NewArea" })
The divs in #1 above are successfully populated dynamically with the string values in #3
B. Where my difficulty lies:
Despite many efforts & attempts, I cannot change the #Url.Action values in #2 to the values in the divs in #1.
I even tried to declare C# private variables and populate them with the foreach that populated the divs above and pass those values to the #Url.Action link, but I get a run error.
Does anyone know a way I can pass the parameter values in my partial call (#3) to the Url.Action method in the Ajax post in #2 above.
Thanks in Advance.
You could have a method that will extract the values that are passed to this strongly typed partial and build the url:
#model string[]
#functions {
public string GetUrl() {
if (Model != null && Model.Length > 2)
{
var values = new RouteValueDictionary();
values["controller"] = Model[0];
values["action"] = Model[1];
values["area"] = Model[2];
return Url.RouteUrl(values);
}
return Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" });
}
}
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(GetUrl()));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
will render like this:
<script type="text/javascript">
var url = "/NewArea/NewAction/NewController";
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
But if you don't need those route values separately another possibility is to directly pass the entire url to the partial view:
#Html.Partial("_About", Url.Action("NewAction", "NewController", new { area = "NewArea" }))
and then inside the partial simply use it:
#model string
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>

Resources