I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.
Related
I wrote the following ajax call to fetch data using the nb (number of document view) parameter:
if ($("#fetch").hasClass("active")) {
$.ajax({
url: "ServletAjaxController",
type: "POST",
dataType: "json",
data: "c=" + controller + "&nb=300",
success: onSuccess,
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
});
}
Now I want to do the same thing but expressing nb != 300 instead of the equal expression. Any IDEAs?
Please how can I send a whole number like twelve to php using ajax. I have been able to send string variables using both GET and POST methods successfully, but when it comes to numerical values it becomes a problem , I don't know why.below is my jQuery
function user_ajax_call(){
var data = $(".people_names").length;
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data:{data:data},
processData: false,
contentType: false,
cache:false,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And these are sample php lines
$limistart = $_POST['data'];
if(isset($limistart)){
echo $limistart;
}
You need to send them through: data.
You could do something like this in your data variable:
data = {
name_length : $(".people_names").length,
number : 12
};
And just pass it like this in your ajax:
function user_ajax_call(){
var data = {
name_length : $(".people_names").length,
number : 12
};
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data: data,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And in your server side access it like :
$_POST['name_length']
$_POST['number']
If you change the value of contentType key it should work correctly.
So change this:
contentType: false
to:
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
EDIT:
and change the line:
processData: false
to:
processData: true
// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you
How to call multiple ajax calls one after another in a chained way?
Hi,
I am having a controller method which returns json based on the start limit and end limit which needs to done by ajax call.
So, initially in first ajax call start limit =1 and end limit=100 and on success of this ajax, same ajax call should be called with updated start limit =101 and end limit=200.
Like wise multiple ajax reuqests needs to be sent till actual dead line of 1000 i reached.
So totatlly 10 ajax calls from 1-100,101-200,201-300 e.t.c till 1000 have to be sent.
Actually i am sending these chained ajax;s this way,
$.ajax({
url: getdata/100/200",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//2nd ajax
$.ajax({
url: getdata/101/201",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//3rd ajax
$.ajax({
url: getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
}
}
But all the time only my first ajax is getting success and rest of the ajax;s are not getting executed and giving 404 error.
Is there any timeinterval needs to be set for calling one ajax inside?
What is the mistake i am doing here..?
can anyone help me in this issue?
Thanks
You can solve these issue by using function like following :-
// Make initial call to function with your data
myAjaxCall(data, 1, 100);
function myAjaxCall(data, startLimit, endLimit)
{
$.ajax({
url: "getdata/"+startLimit+"/"+endLimit, // Concat variables as per your codes
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
myAjaxCall(data, endLimit+1, endLimit+100);
}
}
});
}
If you need to chain Ajax call try to use Jquery.Deferred
it will looks like:
$.when($.ajax(...)).then($.ajax(..)) ...
You can achive this by recursive function
function ajaxRun(data){
$.ajax({
url: "getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(resultData) {
json=JSON.stringify(resultData);
console.log("json" + json);
console.log(JSON.stringify(resultData));
if(json != null && json != "") {
ajaxRun(data);
}
}
});
}
Hello change your parameter name every ajax success method like
success: function(resultData)
second time
success: function(secondresultData)
When this AJAX request POSTS, the newUser() function says no arguments are being passed, even though i have the userInput and passInput fields filled out. The JS/JQ/AJAX:
var userInput = document.getElementById('registerUsername');
var passInput = document.getElementById('registerPassword');
var message = document.getElementById('checkUsernameMessage');
$(document).ready(function() {
$('#submitRegisterButton').click(function () {
$.ajax({
type: "POST",
url: "/newUser",
data: JSON.stringify({"username":userInput, "password":passInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#checkUsernameMessage').text(msg.d);
}
});
});
});
And my python bottle function newUser() :
#post('/newUser')
def newUser(username, password):
etc..
You need to nest your selectors within your dom ready call. Right now they are running before the DOM is ready, and are thus returning undefined. You can verify this by consoling the variables to see if they return any data.
The other thing, is you probably want to select the value of these inputs, and not return the DOM elements themselves: so instead, try
var userInput = document.getElementById('registerUsername').value etc.
$(document).ready(function() {
$('#submitRegisterButton').click(function () {
var userInput = document.getElementById('registerUsername').value;
var passInput = document.getElementById('registerPassword').value;
var message = document.getElementById('checkUsernameMessage').value;
$.ajax({
type: "POST",
url: "/newUser",
data: JSON.stringify({"username":userInput, "password":passInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#checkUsernameMessage').text(msg.d);
}
});
});
});
This should fix your issue.
With the clientside issue fixed, the python issue was:
The post request was being called as: def newUser( username, password ) where there should have been no arguments passed in, but derived from the form variable:
def newUser():
username = request.forms.get('userInput')
password = request.forms.get('passInput')
message = request.forms.get('message')