Call c# code behind from jquery with parameters [duplicate] - javascript

This question already has answers here:
C# Web method is not calling in javascript
(3 answers)
Closed 7 years ago.
Ajax Code
$.ajax({
type: "POST",
url: "LiveFeed.aspx/SearchStateList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
Code Behind
[WebMethod]
public static string SearchStateList()
{
}
The above code works fine and the code behind is called
But when I send some parameter as given below, code behind is not invoked and when I see the Firebug console errors, it throws
NetworkError: 500 Internal Server Error -
http://localhost:61276/App/LiveFeed/LiveFeed.aspx/SearchStateList
Ajax Code
$.ajax({
type: "POST",
url: "LiveFeed.aspx/SearchStateList",
contentType: "application/json; charset=utf-8",
data:{value:"samplevalue"},
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
Code Behind
[WebMethod]
public static string SearchStateList(string value)
{
}
I also tried to change modify the data of ajax call as
var param={value:"samplevalue"}
data:JSON.stringify(param),
and also tried directly with out JSON.stringify
data:param,
Every time when I tried to pass a parameter it did not invoke code behind and 500 error is thrown.

Why don't you try
var param={"value":"samplevalue"}
data:JSON.stringify(param),

I think data content goes with quotes:
data: '{value:"samplevalue"}',

You can access variables sent in the data by accessing the Request Collection.
Request.Form["your_var_name"] // use this when you $.post
Request["your_var_name"] // use this when you $.get
So your code behind can look like this:
public static string SearchStateList(string value)
{
Response.Write("The value of value is: " + Request.Form["value"]);
}

In your Ajax post, you have set the data property as :-
data:{value:"samplevalue"}
Subtle change, to this below would work :-
data:{ "value" :"samplevalue"}

Related

Getting json on cross domain with jsonp using jquery

I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc

Ajax Call not returning Partial View

I am making an AJAX call, and then returning PartialView from Controller to populate it in a div.
The following is my code :-
var file = document.getElementById("file").files[0];
jq.ajax({
type: "POST",
url: '/Main/getData',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
jq('#partialPlaceHolder').html(response);
},
error: function (error) {
alert("Some Error Occured");
}
});
[HttpPost]
public ActionResult getData(FormCollection form)
{
......
return PartialView("_pageMain", retMod);
}
As I debug the Code in Controller, there is no Error till the end, But still the AJAX throws the alert("Some Error Occured").
The PartialView is not populated in div. How to solve this?
You are setting the return data type to json
dataType: 'json'
try changing this to
dataType: 'html'
See here http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
Why not to use .load() JQuery .load()?
Description: Load data from the server and place the returned HTML into the matched element.
And simple:
$('#partialPlaceHolder').load("#Url.Action('getData')", { form: formData })
Third parameter for .load() is callback function, so feels free with it.
BTW: I did not find using variable file in your code.

double controller value in URL call by ajax

I got a strange problem. while i run my VS and click specific button on browser, an ajax function fired and shows error. After debugging i found the URL is showing error. the error is::
POST http://localhost:4942/Employee/Employee/AllEmployees 404 (Not Found)
The problem is, for some reason the "/Employee" controller is coming two times.
my ajax call is:
function allEmployeeFunc() {
$.ajax({
type: "POST",
url: "Employee/AllEmployees",
//data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
// context:"" ,
error: function (msg) {
alert("something is wrong");
},
success: function (data) {
}
});
}
Here the URL clearly showing only one /Employee. so whats the problem?? can anyone help please??
Try to add a slash to the URL
url: "/Employee/AllEmployees"
I guess you are using too much in url; I can see "/Employee/Employee/AllEmployees". Employee twice. Rather try
url: "AllEmployees"
I guess that should do. Assuming that you have annotation [HttpPost] in place to hit AllEmployees function.

jQuery AJAX call to .NET code-behind won't return

adAsText(file);
$.ajax({
url: "WebForm1.aspx/OnSubmit",
rn "abcd";
}
it is a success and all the contents of the file prints as an alert, but I can't get it to return. It there something wrong with the content/data type?
Your Code is not clear.
I think you should clear it as much as possible. The Error I see is that you are not calling the server side function anywhere. Then how you hope to be having returned data. First Call the function by passing a string value to it.
I think this is your problem, if not, please clarify more.
Try changing dataType to json. Even though it should infer, it's better to be explicit.
$.ajax({
url: "WebForm1.aspx/OnSubmit",
type: "POST",
data: file,
dataType: "json",
contentType: "plain/text; charset=utf-8",
processData: false,
error: function (msg) {
console.log(msg.d);
alert("error");
},
success: function (msg) {
console.log(msg.d);
alert(file);
}
});

Can I bind asp.net dropdownlist using javascript/jquery?

Can I bind asp.net dropdownlist using javascript/jquery? I get the data from jquery ajax from a web method so I want to avoid postback at this point. But I still want to do postback and save all the data using server side code (i.e. I still be able to do this dropdownlist1.selecteditem.text) after binding it using clientscripts.
Is it possible and can someone explain me how it can be done?
Thanks,
Use Json ajax
Syntax:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
See simple example for json:
<script type="text/javascript">
$(document).ready(function () {
var msgbox = $("#status");
$("#Button1").click(function () {
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: "BeginJson.aspx/CheckDateTime",
// If you want to pass parameter or data to server side function you can try line
// data: "{}",
//else If you don't want to pass any value to server side function leave the data to blank line below
data: "{'args':'Somnath'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//Got the response from server and render to the client
msgbox.html(msg.d);
}
});
});
});

Categories

Resources