Parameter shown as "0:" in ajax request - ajax

var frm = $('#updateStickyForm');
frm.submit(function (e) {
var id = "{{note.id}}"
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data:
frm.serialize() + '&' + $.param(id),
success: function (data) {
console.log('Submission was successful.');
$('#test').show();
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
When I look at the network logs in Chrome the parameter is shown as "0:". I'm able to access the parameter just fine with Django and do what I want to do with it, I just want to know how I can change it from "0" to something of my choosing.

id seems to have a key 0 for the value you want to post, you can construct an object to pass to $.param with the key you want
frm.serialize() + '&' + $.param({"myid":id['0']}),

Related

call function in ajax success callback

Is it possible to call a function in success callback of ajax request?
For example I have something like that :
constructor(private http: HttpClient,private serviceComposition: CompositionService) { }
[...]
save() {
var isValid = this.isValidCompo();
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
this.serviceComposition.changeValue(isValid);
})
}
}
I want to call a function of my service (named : changeValue() ) if my ajax request is a success.
But I have this error message : core.js:12632 ERROR TypeError: Cannot read property 'changeValue' of undefined
Do you know if it's possible to resolve that ?
I am suspecting this binding is going wrong in call backs,
prefer using arrow function because of "this" operator binding.
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done((data) => {
this.serviceComposition.changeValue(isValid);
})
}
if not u can store this reference in a variable and call it
var self = this;
if (true) {
var toSend = JSON.stringify(this.setupComposition);
$.ajax({
url: "/api/setup/composition/addSetupComposition",
type: 'POST',
dataType: "json",
data: 'setupComposition=' + toSend,
success:function(response){
//console.log("Success Save Composition");
},
error: function(XMLHttpRequest,textStatus,errorThrown){
console.log("Error Save Compo");
}
}).done(function(data){
self.serviceComposition.changeValue(isValid);
})
}
Use an arrow function to access this of your parent scope. In your example, this is referring to your jQuery XHR object.
So:
// [parent scope]
$.ajax({
...
}).done((data) => {
// [child scope]
// `this` now refers to [parent scope], so the following is valid
this.serviceComposition.changeValue(isValid);
});
Another common practice prior to arrow functions (ES6) would've been assigning a const self = this; variable in the [parent scope] area to be accessed in the child method. Either method works the same.
Also check out the MDN docs on this. It's a confusing topic for many.

Laravel - Ajax and preventdefault

I have a problem with getting items in cart, after I add an item into the cart, Ajax works perfect, then when i try to remove it from the list, first time it wont work with Ajax, if I reload the page it will work.
Ajax generate response like this:
1x ItemTitle X (remove)
When remove has /delete-from-cart/id/place_id
It only works when I reload the page, and also I have a button for coupons that is also managed to work with Ajax, but it only works after refresh.
$('.deletefromcart a').each(function(){
$('#'+this.id).on('click',function(e) {
e.preventDefault();
var id = $(this).attr('data-del');
var url = $(this).attr('href');
var place = $(this).attr('data-place');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/delete-from-cart/'+id+'/'+place+'',
method: 'get',
data: $(this).serialize(),
success: function(data){
toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
$(".korpa").load(location.href + " #cartAll");
},
error: function(data){
console.log(data);
}
});
});
});
It seems like this function cant find any object to run it from ajax after I add to cart, after refresh it finds.
If you need live preview, i can make you an account.
You should bind the click event handler on each 'delete' element as,
$('body').on('click', '.deletefromcart a', function (e) {
e.preventDefault();
var id = $(this).attr('data-del');
var url = $(this).attr('href');
var place = $(this).attr('data-place');
$.ajax({
url: '/delete-from-cart/' + id + '/' + place + '',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'get',
data: $(this).serialize(),
success: function (data) {
toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
$(".korpa").load(location.href + " #cartAll");
},
error: function (data) {
console.log(data);
}
});
});
Note 1: Your method of binding will attach the event handler to all .deletefromcart a elements. But the one I suggested will bind the event handler to only one element, body. This will also work on dynamically added .deletefromcart a elements.
Note 2: You can include the header values as above too.

autocomplete functionality on dynamic textbox

I have a scenario as follows,
Need to put autocomplete functionality on dynamic textbox with onkeyup functionality
My code is as follows, Here i have invoked a function "GetName" on buttonclick where am loadin the dynamic textboxes
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()
});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
$("#ResourceNames").empty();
$("#ResourceNames").append('<table>');
$.each(result, function (i, Name) {
$("#ResourceNames").append('<tr><td ><Label>' + Name.Value + '</label></td><td> <input type="text" id="Supervisor" class = "form-control", onkeyup="GetResource(\'' + Name.Text + '\');"/></td></tr>');
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append('</table>');
}
Here onkeyup event of textbox supervisor am calling the below function getresource with an argument
function GetResource(i) {
debugger;
var dataToSend = JSON.stringify({ prefixText: $("#Supervisor").val(), designation: i });
$.ajax({
url: "GetSupervisor",
data: { jsonData: dataToSend },
dataType: 'json',
type: 'POST',
success: function (data) {
$("#Supervisor").autocomplete({source:data});
});
},
error: function (error) {
alert('error; ' + error.text);
}
});
}
am not able to bind autocomplete data to dynamic textbox, can anyone help me out on the same?
You have several issues in your code:
First of all jQuery doesn't concatenates strings into DOM, it creates a DOMElement. So,
$("#ResourceNames").append('<table>'); will append an entire <table> element. Anything you append to #ResourceNames will be added after the table, not inside it.
The HTML you're appending contains id. So there can be multiple elements with same id which is invalid, depending on the response. It's better to use a common classname for those elements instead.
You don't need to manually handle the keyup event. You can specify the url you want to hit as the value of the source option of autocomplete, provided it returns a response suitable for the autocomplete. see this example in docs.
Instead of passing the value via the inline handler, you can store the value as a data-* attribute and access it later.
So your code should be something along:
function GetName() {
var dataToSend = JSON.stringify({ prefixText: $('#search').val(), Id: $("#SearchType").val()});
$.ajax({
type: "POST",
data: { jsonData: dataToSend },
url: "GetName",
datatype: "json",
success: function (result) {
var htmlString ="<table>";
$.each(result, function (i, Name) {
htmlString +="<tr><td ><Label>" + Name.Value + "</label></td><td> <input type='text' class = 'form-control Supervisor' data-name='"+ Name.Text + "'/></td></tr>";
});
},
error: function (xhr, status) {
alert(status);
}
})
$("#ResourceNames").append(htmlString);
$(".Supervisor")..autocomplete({
source: "GetSupervisor" // where GetSupervisor is your data source
});
}
If you want to manually send requests along with data and pass the results into the autocomplete, you can specify an function as the value of source option. (See my another answer for more info). for example:
$(".Supervisor").autocomplete({
source: function(request,response){
/*send the request here.
request.term contains the current value entered in textfield
pass the results you want to display like response(data)*/
}
});
Read the API documentation, play with it for a while and you'll be able to get it working.

jQuery Ajax not executing

Greeting.
I have made this jQuery Ajax call, which doesn't seems to be executing.
It does handle the .live() call, but not the .ajax() call.
Any ideas?
Source of ajax.js:
$("#action_login").live("click", function() {
var username = $("#login_form input.username").val();
var password = $("#login_form input.password").val();
alert("Username: " + username + "/nPassword: " + password);
$("#login_form .status").ajax({
type: 'POST',
url: 'ajax/login.php',
data: {
'username': username,
'password': password
},
success: function(data) {
alert(data);
},
error: function(data) {
alert("error" + data);
},
dataType: dataType
});
});
It does call the first alert(); command, with the right value from the inputs for username and password, but after that nothing happens.
Hope someone can help me out.
$("#login_form .status") is the call to the $ function with "#login_form .status" as parameter.
It returns a very different object than $, and it doesn't have any ajax function.
So, replace
$("#login_form .status").ajax(
with
$.ajax(
Replace
$("#login_form .status").ajax
With
$.ajax

how to clear a asp dropdown list and populate using ajax?

What i am trying to do is get a user to change one drop down, which then calls an ajax function which posts to the code behind (vb.net file) then clears and populates another asp dropdown list with the data returned from the function..hope i made sense
<script>
$(document).ready(function () {
$('.manuf').change(function () {
$.ajax({
type: "POST",
url: "ajax.aspx/GetModel",
data: '{' +
'ManufID:"' + $('.manuf').val() + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = json_parse(msg.d);
if (data.error) {
alert("Error!");
return;
}
alert(data.model);
},
error: function(msg) {
alert('Get Details Failure: ' + msg);
}
});
});
});
</script>
My bad - you can write your ajax call like this -
$.ajax({ url :"/website/myurl", type:"POST", contentType:"application/json;", dataType:"json", data : "{ 'id' : '" + $("select[id*=selCurrentManuf]").val() + "' } ",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value","0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("select[id*=selCurrentModel]")); });
}, error:function () {
// handle error
}
});
I assume that you know how to fetch data from the backend via ajax. Something like this -
$.ajax({ url :"/website/myurl", type:"POST", dataType:"application/json"; data:"json",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
}, error:function () {
// handle error
}
});
Lets say you are getting it in a variable data which is an array.
You may try something like this -
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value", "0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("#ddlExperience")); });
// user $.each to iterate the data object which
You may try things on these lines.... Hope this helps.

Resources