I have a strange error where my jquery ajax request doesn't submit all the parameters.
$.ajax({
url: "/ajax/doAssignTask",
type: 'GET',
contentType: "application/json",
data: {
"just_a_task": just_a_task,
"fb_post_date": fb_post_date,
"task_fb_postId": task_fb_postId,
"sedia_task_guid": sedia_task_guid,
"itemGuid": itemGuid,
"itemType": itemType,
"taskName": taskName,
"assignedToUserGuid": assignedToUserGuid,
"taskDescription": taskDescription
},
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
But using firebug (and debugging) I can see that only these variables are posted:
assignedToUserGuid
itemGuid
itemType
just_a_task
taskDescription
taskName
It's missing fb_post_date, task_fb_postId, and sedia_task_guid
I have no idea what would cause it to post only some items and not others? Anyone know?
Data is sent to asp.net controller that returns jsonresult (hence the contentType)
Any help is appreciated. Thanks!
You could try some things such as:
See if all variables have values
Try to remove the "_" from the variable's names
What you should to to help with coding and debug is move the JSON data to a variable... ie, then you can easily see what is inside the variable before posting
var myData = {
just_a_task: just_a_task,
fb_post_date: fb_post_date,
task_fb_postId: task_fb_postId,
sedia_task_guid: sedia_task_guid,
itemGuid: itemGuid,
itemType: itemType,
taskName: taskName,
assignedToUserGuid: assignedToUserGuid,
taskDescription: taskDescription
};
var jsonData = $.toJSON(myData);
$.ajax({
url: "/ajax/doAssignTask",
type: "GET",
contentType: "application/json",
dataType: "json",
data: jsonData,
success: function(data, status) {
//success code
},
error: function(xhr, desc, err) {
//error code
}
});
Though I dont have time to run the code, could be the speech marks in the JSON. That should be out as its native JavaScript
Check for special characters in your data values (, { } [ ] " '). You have to escape those characters for JSON to work.
Hope this helps.
in the interest of a sanity check, try adding a beforeSend to your options and ensure the values are being sent and go from there....
e.g.
.ajax({
beforeSend: function (xhr) {
// this==the options for this ajax request
if(! fb_post_date || !task_fb_postId || ! sedia_task_guid){
alert("BORKED!");
}
},
....
Related
I am trying to get value based on 2 parameters, below is my function where I added my 2 parameters in JSON stringify :
function GetItemLocationOnHand(itemId, locationId) {
var data = JSON.stringify({
itemId: itemId,
locationId: locationId
});
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemInventory3',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}
Below is my code in my controller to retrieve the data I want based on these two parameters :
[HttpGet]
public JsonResult GetItemLocationOnHand(int itemId, int locationId)
{
var itemLocQuantity = objDB.ItemLocationDatas.Single(items => items.ItemId == itemId && items.LocationId == locationId).Quantity;
return Json(itemLocQuantity, JsonRequestBehavior.AllowGet);
}
Upon calling this function via below on change code, I can't seem to get my data and is always returning the error.. If I only have 1 parameter, then no error encountered.
Please advise what went wrong when trying to pass 2 parameters.
$("#LocationId").change(function () {
var itemId = $("#ItemId").val();
var locationId = $("#LocationId").val();
GetItemLocationOnHand(itemId, locationId)
});
Issue solved by doing the following :
added correct URL which is GetItemLocationOnHand
removed Stringify and used var data = ({ itemId: itemId, locationId:
locationId });
thanks a lot to Freedom and Reflective and others for your comments!
function GetItemLocationOnHand(itemId, locationId) {
var data = ({ itemId: itemId, locationId: locationId });
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemLocationOnHand',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}
Just to avoid some misunderstanding how AJAX GET works and setting some parameters which you don't have to set (i.e. you are still not so deep into jQuery AJAX) you may use the shortcut they also implemented i.e. $.get so your request will look as simple as that and you can't get wrong as it will use the proper defaults for GET. If you want the response to be treated as JSON, just set Content-type of your response headers (from backed) to application/json. This will be checked by jQuery AJAX response handler and it will parse the incoming data as JSON.
var data = {itemId: 1, locationId: 2 };
$.get('GetItemLocationOnHand', data, function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
}).fail(function (jqXHR, textStatus ) {
alert(`Error = ${jqXHR.status} ${textStatus}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
See my example below. This works for me when doing ajax requests to a MVC controller with multiple params.
Below is my MVC controller action with multiple params.
// GET
[HttpGet]
public ActionResult Index(string referenceID, int typeID, int supplierID, bool isArchived)
{
// Do CODE here
}
Below is my Ajax request that I use to get or post. Depending on your needs. I use data type 'JSON' and format my data as a JSON object.
var formData = {referenceID: 'Test', typeID: 3, supplierID: 2, isArchived: false};
$.ajax({
type: 'GET',
cache: false,
url: getActionUrl, // url: domain/controller/action |or| domain/area/controller/action
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: headers, // ignore if not needed. I use it for __RequestVerificationToken
data: formData,
success: function (data, status, xml) {
// do something with the data
},
error: function (xml, status, error) {
console.log(xml)
// do something if there was an error
},
complete: function (xml, status) {
}
});
I think your issue might be that you are using 'JSON.stringify'. It could be interpreting your JSON string as a single parameter input and not two separate parameters.
Please see below snippets from documentation. https://api.jquery.com/jquery.ajax/
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
I am having a problem with making an ajax call in jQuery. Having done this a million times, I know I am missing something really silly here. Here is my javascript code for making the ajax call:
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
var inputEmp = {};
inputEmp.id = id;
var jsonInputEmp = JSON.stringify(inputEmp);
debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: jsonInputEmp,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
});
}
Here is my CS code that is trying to be called:
[WebMethod]
public static string GetEmployee(int id)
{
var employee = new Employee(id);
return Newtonsoft.Json.JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented);
}
When I try to run this, I do get the alert that says Before Ajax Call!. However, I never get an alert back that says success or an alert that says failure. I did go into my CS code and put a breakpoint on the GetEmployee method. The breakpoint did hit, so I know jQuery is successfully calling the method. I stepped through the method and it executed just fine with no errors. I can only assume the error is happening when the jQuery ajax call is returning from the call.
Also, I looked in my event logs just to make sure there wasn't an ASPX error occurring. There is no error in the logs. I also looked at the console. There are no script errors. Anyone have any ideas what I am missing here?
`
Try This
function editEmployee(id) {
$('#<%= imgNewEmployeeWait.ClientID %>').hide();
$('#divAddNewEmployeeDialog input[type=text]').val('');
$('#divAddNewEmployeeDialog select option:first-child').attr("selected", "selected");
$('#divAddNewEmployeeDialog').dialog('open');
$('#createEditEmployeeId').text(id);
//var inputEmp = {};
// inputEmp.id = id;
// var jsonInputEmp = JSON.stringify(inputEmp);
//debugger;
alert('Before Ajax Call!');
$.ajax({
type: "POST",
url: "Configuration.aspx/GetEmployee",
data: {id: id},
// contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (msg) {
alert('success');
},
error: function (msg) {
alert('failure');
}
}); }
if ajax call doesnot goes inside the success function then the problem is with your dataformat in CS code . the return data must not be in a proper JSON format . you should be getting "500" Error i guess.
Try returning it in a proper JSON format.
Using JQuery, I am passing values to an action in the controller. customerId and productId are not null:
$.ajax({
type: "GET",
url: "Customer/Product/",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
In MVC3 controller, i have the action:
public ActionResult Product(string Customer, string Product)
{
//both are null
}
I don't know why both are null? Please guide
$.ajax({
type: "GET",
url: "Customer/Product/",
data: "Customer="+customerID +"&Product="+productId,
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
Try this way.
MVC may be expecting a JSON string. Try using this as your data
data: JSON.stringify({ Customer: customerID, Product: productId})
If you change it to a "POST" request it should work.
However it looks like you are actually trying to just "GET" data from the server which should really be encoded in your URL e.g. mysite.com/Customer/{customer_id}/Product/{product_id}. In this case you'll probably need to change your routing rules.
I just did "File -> New Project" and just added the one controller and tried directly using:
var customerID = 42;
var productId = 4242;
$.ajax({
type: "GET",
url: "http://localhost:51622/Customer/Product",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
console.log(json);
}
});
It binds the values just fine, so you might want to grab fiddler or something similiar and make sure that you are actually sending values to the server.
Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.