Storing data Object coming from a response of jQuery ajax call - c#

I am calling a web method from asp.net 1.1 site and getting a response.
I use this object to populate some data, Now I want to store this object so that I can also save this data in database while saving click event.
How can I achieve this.
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (**msg**) {
// STORE THIS msg object.
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});

$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
// STORE THIS msg object.
//if hidden field has id 'name'
$('#name').val(data.name);//if json object contains a key 'name'
//if hidden field has class name
$('.name').val(data.name);
//if hidden field name is name <input type="text" name="name" />
$(document).filter(':[name=name]').val(data.name)
//do the same for all elements to save
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});

$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, jqXHR){
// STORE THIS msg object.
/* now you can store data object to where you want to store.*/
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});

Related

Ajax function failing to hit method on code behind on server

I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:

Posting to WebMethod with ajax error

Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>

Asp.net Post json

login.aspx.cs
[System.Web.Services.WebMethod]
public static string jQueryPageMethod(string name)
{
return "<h3>jQuery - PageMethod </h3>result" + name;
}
JS/Jquery:
If i run below method it works.
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":"exampleValue" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
If i run below method it does not work.
var somevalue = "Value";
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":' + somevalue + ' }', // Problem here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
Where i miss in second example in part of data ?
Your data should not be formatted as a string, but rather as a javascript object like this:
data: { "name": somevalue }, // No Problem here :)
Try this data: '{"queryname":"' + queryname + '"}'

Pass Dictionary From Ajax to C# Codebehind

I am using ASP.Net and jquery/ajax
I have the following script in jquery:
var sizes = [];
sizes.push({ key: "1", value: "3"});
$.ajax({
type: "POST",
url: pageUrl,
data: '{"sizeList":' + sizes + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
This is the codebehind:
public static void AddProductToDB(Dictionary<String, String> sizeList)
Can someone please tell me what I am doing wrong as I have tried everything I could think of.
Thanks
var param = {
'[0].Key': '1',
'[0].Value': '3'
};
$.ajax({
type: "POST",
url: pageUrl,
data: param
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
I am looking at this two years after it got posted but hopefully it will help someone if they stumble upon this post. I used the base of Damith's answer to form the parametes I was going to pass and got it to work by passing them the following way:
var param = {
'filters[0].Key': '1',
'filters[0].Value': 'test',
'filters[1].Key': '2',
'filters[1].Value': 'test',
id: 1,
width: 150,
height: 150,
};
Then on the MVC code I had my method with the following signature:
public async Task<ActionResult> IndexPartial(int id = -1, int? width = null, int? height = null, Dictionary<string, string> filters = null)
With these two things I was able to have the method detect the information passed as a Dictionary<string,string> and at the same time I was able to pass in additional parameters. Hopefully this will resolve your issue.
Looks like you are trying to use a page method. If so, you need to decorate your method (in code behind) with the WebMethod attribute
[WebMethod]
public static void AddProductToDb(Dictionary <string, string> sizelist){}
Then make sure you are posting the json object with jquery to the correct url...for example...PageName.aspx/AddProductToDb
That's all you need if you are using page methods
I believe you need to set traditional to true so it will serialize properly
$.ajax({
type: "POST",
url: pageUrl,
traditional: true,
data: '{"sizeList":' + sizes + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
Please refer below code. Make sure your method "AddProductToDB" has HttpPost attribute and identical/same name of the parameter in this case "sizeList".
C# / MVC / Back End Side :
[HttpPost]
public static void AddProductToDB(Dictionary<String, String> sizeList)
{
//Business logic or Data
}
Javascript / jQuery / Client Side:
And Enter the URL where you this function/method AddProductToDB.
For example "YourController/AddProductToDB".
<script type="text/javascript">
var sizes = [];
sizes.push({ "Key": "key1", "Value": "value1" });
sizes.push({ "Key": "key2", "Value": "value2" });
sizes.push({ "Key": "key3", "Value": "value3" });
$.ajax({
type: "POST",
url: '/YourController/AddProductToDB',
data: JSON.stringify({
sizeList: sizes
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
</script>
you can use this:
var param = {
'1': '3'
};
$.ajax({
type: "POST",
url: pageUrl,
data: JSON.stringify({sizeList: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
}
}
then you can read it from dictionary variable with this:
public static void AddProductToDB(Dictionary<String, String> sizeList) {
sizeList["1"]; // return "3"
}

AJAX GET REQUESTS

Please help, I'm stuck here. I have a problem with passing input parameter to my C# controller. I tried really a lot of things I found here, but still there's some mistake.
Here is code:
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: "location=Paris%",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
And here is controller:
[HttpGet]
public JsonResult Weather_get(String location) etc etc...
Everything I tried gives me input location NULL. I know my controller is working fine because I get data from it, but I really need that data to be for specific location, so that's why I need it like this. Also don't want to change it to POST because this is homework problem so I have to have both HttpPost and HttpGet in my controller.
Try this
var place="Paris%";
var a = $.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: '{ "location":"' + place+ '"}',
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
just include the parameter name in your controller and the value you want to pass like this.
$.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: { location:paris},
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
The way ASP.Net binds the HTTP request URL to the model used by your controller is controlled in part by the routing engine.
If you navigate to
/Weather1/Weather_get/Paris
do you see the data from Paris?
If so, you could modify your AJAX this way
$.ajax({
type:"GET",
url: "/Weather1/Weather_get/Paris"
(etc.)
})
You should probably use JSON.stringify.
something like this:
var data = {
location: "Paris%"
};
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;

Categories