I want to read json response as name and value pairs in my JQuery code. Here is my sample JSON response that I return from my dotnet code:
const string format = "\"HasCases\": \"{0}\"";
StringBuilder json = new StringBuilder(128);
json.Append("{");
json.AppendFormat(format, JSONString("true"));
json.Append("}");
Response.Clear();
Response.AppendHeader("Content-type", "application/json; charset=utf-8"); Response.Write(json.ToString());
Response.End();
To get Json value ,is it necessary to use Response code?In my Json page , I am able to get the output as HasCases : true.
Here is my JQuery code
<span id="testSpan" runat="server">inactive</span>
<script type="text/javascript">
inactive
$.ajax({
type: 'POST',
url: "~/Pages/UserCaselistnonEmptyAjax.aspx",
dataType: "json",
success: function (response){
$('#testSpan').innerHTML = response.HasCases;
},
error: function (e1, e2, e3) {
$('#testSpan').innerHTML = 'Error';
}
});
</Script>
When I am debugging form firebug My control does not going to "$('#testSpan').innerHTML = response.HasCases; ".It is coming out from the loop.
jQuery objects don't implement .innerHTML. Use .html() instead:
$('#testSpan').html(response.HasCases);
I am returning my json using
return (new JavaScriptSerializer().Serialize(request));
in my c# code.and I am calling the function returning this value at page load event.
and the output is this
{"registration_ids":["1","2"],"data":{"message":"Your message","tickerText":"Your ticker","contentTitle":"Your content"}}
but I am unable to read this returned json fomrat with jquery ajax
my ajax is below
function as()
{
$.ajax({
type:"get",
url:"mydjson.aspx",
contentType: 'application/json;charset=utf-8',
dataType: {'json':'datas'},
//data: JSON.stringify(request),//{ get_param: 'value' },
success:function (msg) {
$("#table").html("<h1>" + msg+ "</h1>").fadeIn("slow");
},
// function (data, status)
error: function (xhr, textStatus, error)
{
var errorMessage = error || xhr.statusText;
$("#table").html("<h3>" + errorMessage + "</h3>").fadeIn("slow");
}
});
return false;
// });
}
I am getting the error "Ivalid json" plus the content of page" mydjson.aspx".help me for this.
Related
I am passing an array from view to controller using Ajax but, on action, the array shows empty.
This is my code:
View
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values: arr["48","47","46"] },
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Action
public ActionResult array(string[] Values)
{
for (int id = 0; id < Values.Length; id++)
{
string newID = Values[id];
}
return View();
}
jQuery.ajaxSettings.traditional = true;
$("#btn").click(function () {
debugger
arry = [];
$.ajax({
type: "Post",
url: "/Main/CheckBoxes",
data: { Values:["48","47","46"]},//just edit this line
success: function () {
alert("array: " + arry.join(', '));
},
error: function () {
alert("error");
}
})
});
Your code has some issues regarding how you are sending the data! What is your expectation when you execute this expression arr["48","47","46"] ????? That is going to give you undefined and that is what you are trying to send!
There are two ways to fix your code. You can send the array in the request body. For this, you need create a JSON string from the array and send that as the data property while explicitly specifying the request content-type header value as "application/json". You may use the JSON.stringify method to get the JSON string of your js array.
Also, make sure you are making the call to the correct action method. In your question you shared the array action method code, but in your client side script you were trying to call a different action method(`Checkboxes)!
This should work.
var arry = ["48", "47", "46"];
var url = "#Url.Action("array", "Main")"; // Update your real url here
// If your script is inside the razor view, you can us Url.Action (c#) method
$.ajax({
type: "Post",
url: url ,
data: JSON.stringify(arry),
contentType: "application/json",
success: function(r) {
alert("Success");
console.log(r);
},
error: function() {
alert("error");
}
});
Another option is to send a javascript object with Values property (which has the array as the value of it) as the data property value of the $.ajax call. Now the request content-type header will be application/x-www-form-urlencoded; and the array will be sent as FormData in the request.
var arry = ["48", "47", "46"];
$.ajax({
type: "Post",
url: "/Main/array",
data: { Values: arry },
success: function(r) {
console.log(r);
},
error: function() {
alert("error");
}
});
I want to write code for multipledelete by using jquery json.
This is the jquery code:
function DeleteSelected() {
var categories = new Array();
debugger;
// iterate all checkboxes and obtain their checked values, unchecked values are not pushed into array
$("input[type='checkbox']").each(function ()
//$('input[type=checkbox]').prop("checked", this.checked)
{
this.checked ? categories.push($(this).val()) : null;
});
// assume urldata is your web method to delete multiple records
var urldata = "WebForm5.aspx/deleteRecord";
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urldata,
data: "{ 'Id':'"+JSON.stringify( categories)+"' }", // used to convert array into proper JSON format
dataType: "json",
success: function (dt) {
// done whatever tasks if succeeded
alert("entry deleted");
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
}
});
}
This is aspx code(codebehind for multiple delete):
[WebMethod]
// note clear difference between single and multiple selections
public static void deleteRecord(List<int> Id)
{
clsCategoryBL objproject = new clsCategoryBL();
// iterate through input list and pass to process method
for (int i = 0; i < Id.Count; i++)
{
objproject.CategoryDelete(Id[i]);
}
}
I want to pass the id to aspx page but the problem is that output comes error popup.
error: function (result) {
alert("Error");
}
The below line will return JSON for the array categories
"{ 'Id':'"+JSON.stringify( categories)+"' }"
Validate the value with http://jsonlint.com/ and check if the result is valid JSON.
Since you had declared the method as public static void deleteRecord(List<int> Id) that means the expected input will be like [1,2,3]
Also use below line to get exact error coming
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
UPDATE 1:
Below is working code
var categories = new Array();
// do your logic to push
categories.push(1);
categories.push(2);
categories.push(3);
var valuetxt = "{ \"Id\":\"" + JSON.stringify(categories) + "\" }";
var urldata = "WebForm1.aspx/deleteRecord";
$.ajax({
type: "POST",
url: urldata,
data: valuetxt, // used to convert array into proper JSON format
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// in result you will get same data which is posted
alert(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
});
[WebMethod]
// change the parameter to string, convert back JSON to Integer Array
public static string deleteRecord(string Id)
{
// do something - for sample here returning same JSON of integer
return Id;
}
I am passing json data to my generic handler page GenericHandler.ashx.cs using jquery ajax request and json as data type.
in my handler code i would like to return html table in string format. here is snap of my handler code
context.Response.ContentType = "text/plain";
context.Response.Write(sResponse);
where sResponse contains <table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>
my jquery code (check inline comment in error function):
id = { 'PropertyID': id };
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
dataType: 'json',
cache: false,
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status); // Output as parseError
console.log(xhr.responseText); // My sResponse string ! But Why Here ?
}
});
My Question :
Why i am not getting response in success function
Is it right way to do ? or should i convert html table to json object and then return it. And again display it in tabular format ?
From jQuery documentation here, you can see that the dataType parameter is what AJAX is expecting back as a response from the server. The contentType parameter is what is put in the header in your request to the server so that the server knows how to read the request.
Therefore, you should change your dataType to "text" like:
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
cache: false,
dataType: 'text',
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
I find this useful when alerting of a successful INSERT or UPDATE call on a database. It would be extraneous to create and return a JSON object for such a task.
Your response isn't valid JSON sine it's returning plain text. jQuery is expecting the response to be JSON because you've set contentType: "application/json"
If the rest of your site uses JSON as a transmission format, then wrap your HTML as a JSON object and return it.
In your back end code, return something that looks like this
{response_html : "<table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>"}
And in your jQUery code, you can access it in the success callback.
success: function (data) {
console.log(data.response_html);
},
NOTE - You'll need to remove the plain text content type from your backend code and make that JSON.
If you tell $.ajax that you expect a JSON, then a text/plain response from the server is not a valid response.
Regarding your second question: The good way to do it would be to return the data you want to work with, in JSON format, for example:
[
{ "label" : "PropertyName", "value" : "abc" },
{ "label" : "PropertyId", "value" : "1" }
]
And then in the success callback of your Ajax request, work with that data to build your HTML structure with jQuery.
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.
I have the following request:
var response = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: this.AgentServiceUrl + "/" + methodName,
data: data,
async: this.Async,
success: function (xml, textStatus) { if (successHandler != null) successHandler(state, $.xml2json(xml), textStatus); },
error: function (xmlHttpRequest, textStatus, errorThrown) { if (errorHandler != null) errorHandler(state, xmlHttpRequest, textStatus, errorThrown); }
});
I want to add to a variable to this request header and consume it on C#,
I try many ways but I can't consume it on C#:
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", this.AgentGUID);
},
Pass parameters:
Can you help me? I don't want to change the function at the C# part I just want to use something like:
(System.Web.HttpContext.Current.Request.Headers["someHeader"]
Your beforeSend should work as you wish, but the reason you are not getting the value on server side is that this.AgentGUID on this method call is undefined because this in that context is pointing to another object (most probably ajax request object).
By defining a variable outside your ajax call you issue will be fixed.
var me = this;
var response = $.ajax({
...
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", me.AgentGUID);
},
...
});