Send just a string from $.ajax to c# - c#

This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..

As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.

Related

Can't get ajax call with parameters to hit my C# function

Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});

jquery $.when not working by waiting function in master page

i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.

Getting a base64 string of a jpg in JQuery from an ASP (C#) Method

I am trying to get a base64 string of a jpg image from a C# ASP method. I have confirmed that the base64 being returned is actually converted into the image correctly. However, when trying to set it as an 's src through JQuery, I get a BAD REQUEST error in FireBug monitor.
JQuery:
function GetImage() {
$.ajax({
url: "Default.aspx/GetImageArray",
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
document.getElementById("MainContent_output").setAttribute('src', 'data:image/jpeg;base64,' + $.fromBASE64(msg['d']));
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
C# ASP:
[WebMethod]
public static string GetImageArray()
{
return Convert.ToBase64String(File.ReadAllBytes(path));
}
Don't mind the 'GetImageArray' name, the method returns a string.
Well, SOS pretty much :)
For those needing an answer I resolved it with the following:
C# (ASP) (Unchanged):
[WebMethod]
public static string GetImageArray()
{
return Convert.ToBase64String(File.ReadAllBytes(path.jpg));
}
JQuery:
function GetImage() {
$.ajax({
url: "Default.aspx/GetImageArray",
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
document.getElementById("MainContent_output").setAttribute('src', 'data:image/jpg;base64,' + msg['d']);
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Note: Element 'output' in an asp:Image control. The only issue remaining is that the string is too large in length for Javascript Serializer, which occurs for large images. I will reply with a fix when I figure it out.

Unknown web method parameter method name

I'm building a Web Application in which I'm trying to call a WebMethod in a WebForm, I've tried every single page in google but I'm still getting nothing. This is an example of the Jquery Ajax Call
$.ajax({
type: "Post",
url: "Default.aspx/Return",
data: {dato:'Hello'},
contentType: "application/json; chartset:utf-8",
dataType: "json",
success:
function (result) {
if (result.d) {
alert(result.d);
}
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
And this is the WebMethod in the codebehind
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Return(string dato)
{
return dato;
}
You can't access a Static method this way. Remove the "Static" reference and it will work. Also, like someone else said - do not use that as your method name "Return".
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Return(string dato)
{
return dato;
}
I think, on your success event the function with result is used, which is a string and u are trying to access property named d assuming result is an object.
use of only alert(result);
User F12 tool to debug and find your error.
Make sure that you have enabled page methods in your ScriptManager element:
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
and your method
$.ajax({
type: "Post",
url: '<%= ResolveUrl("~/Default.aspx/Return") %>',
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
Try this
var url = window.location.pathname + "/Return";
$.ajax({
type: "Post",
url: url,
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result.d);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});`

List of GUIDs JSON being sent to MVC controller via GET is empty upon arrival, POST works

I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});

Categories

Resources