C# not getting data from Ajax - javascript

I have a problem sending ajax data from my javascript file to my c# controller. I get a "bad request error" in my c# program, and the reason i get that is because the data parameter "result" which i am sending with ajax is not getting received by c# and the c# variable stays null. I know Ajax is routing to the correct controller since it is calling the method, but the variable "result" is not getting received by c# for some reason.
Here is my ajax request.
$.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { 'result' : result },
url: "https://localhost:44374/api/task",
cache: false,
success: function (data) {
// Process the received data.
}
});
Here is my c# controller
[HttpPost]
public ActionResult<string> Get(string result)
{
string id = result;
getTaskContent(id);
return id;
}
After changing Ajax to GET, the program works and the output is:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44374/api/task/1108164994166723?_=1549876832637 application/x-www-form-urlencoded; charset=UTF-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.8526ms 404
But for some reason the C# Actionresult method is not getting executed.
See that the URL is localhost:44374/api/task/1108164994166723?_=1549876832637, where the result variable is 1108164994166723, what I have no idea about is how the ?_=1549876832637 part is coming. If I alert the result variable in the window it is only 1108164994166723
Solution
The combination of changing to GET instead of POST and the changing URL in Ajax to url: "localhost:44374/api/task?result=" + result, did the job.
Correct Ajax code is:
$.ajax({
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "https://localhost:44374/api/task?result=" + result
});

try changing the content-type to "application/json;charset=utf-8" and sending the parameter name in the URL like this:
$.ajax({
type: 'POST',
contentType: "application/json;charset=utf-8",
url: "https://localhost:44374/api/task?result=" + result,
cache: false,
success: function (data) {
// Process the received data.
}
});

Change the GET method in the controller to POST method. Since in your ajax call you are specifying the type as post.

you must changeto HttpPost in Controller and change the result type to JsonResult.

Try to change your type to type:GET -- because your controller action method is a HTTPGET and contentType to: contentType: 'application/json; charset=utf-8
and data to data: JSON.stringify({ result: result })

Related

Node.js endpoint ampersand is getting appended when making an ajax call

I've the below code which I'm using to hit a node.js endpoint. However when it is getting hit, the endpoint URL appends an & to it like this,
http://localhost:3004/expenses/?q=&12/02/2014
Hence I'm not getting the desired result back.
Here is how my code looks like,
$('#myForm').on('submit', (e)=>{
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/?q=',
processData: false,
data: $('#startDate').val(),
contentType: 'application/json',
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
})
})
Can someone shed some light?
The issue is most likely related to the processData: false telling jQuery to not format the data for the request, and the GET url already containing ? in it. Given that you are not giving the request json, I would suggest reducing your call to simplify the issue.
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/',
data: { q: $('#startDate').val() },
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
});
If you do not give the processData in the options, it will convert the data you give it to a query param for the request. Given that this is a GET request, it will generate the ?q=<value> for you. And as mentioned in the comments, you do not need contentType: application/json on the options as that is telling jQuery to put the content type on the request so the server knows you are sending it json in the body. Which you are not, :)

jQuery post not working whereas get works with same structure

I've got an ajax call to the following php method:
public function test(){
die(json_encode(['test' => 'test1']));
}
My ajax call works when set as GET but not as POST. The GET call is:
$.ajax({
type: 'get',
url: url,
success: function(msg) {
log(msg);
},
dataType: 'json'
});
Which successfully returns the JSON element. But when I set it as POST:
$.ajax({
type: 'post',
url: url,
success: function(msg) {
log(msg);
},
dataType: 'json'
});
Returns nothing. If I removed the dataType it will return the whole webpage where it's being triggered from.
I do need to make the request as POST since I'll be sending a large amount of data.
Thanks.
Do you have CSRF protection enabled?

Javascript POST to API

So I am a bit lost and hoping you can help me out. I am writing an app in simple PHP/HTML/Javascript app.
My Goal: To POST json data to an API.
How can I go about this? I just can't find any good examples to show me the best way to handle this.
In my request I need to send Basic Authorization as well as the json values.
This is what I have right now
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
success: function (){
alert('Comment Submitted');
}
});
I can't get the above code to work. Im using a button to call a function that will start the ajax call but nothing is happening.
Any help be be amazing! Thank You.
Use
contentType:"application/json"
You need to use JSON.stringify method to convert it to JSON format when you send it,
And the model binding will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
If you're writing the API in PHP, and it uses $_POST to get the parameters, you shouldn't send JSON. PHP only knows how to decode multipart/form-data and application/x-www-form-urlencode. If you pass an object to $.ajax, jQuery will use the urlencode format.
Just take the quotes off the object that you're passing to the data: option.
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
success: function (){
alert('Comment Submitted');
}
});
You also shouldn't use async: false, it is deprecated. Learn to write proper async code.
Nobody seems to have addressed one issue - the URL
If the page this is requested from is http://yourhost.com/path/file.html the request will be sent as http://yourhost.com/path/host.com/api/comments
As you have host.com in the URL, I assumed the request is to a different domain?
use one of
http://host.com/api/comments
https://host.com/api/comments
//host.com/api/comments
will only work if your page is loaded http and not https
will work only if the remote API supports https
will only always work properly if the remote API supports both http and https
The other issue is regarding the format of the sent data
The default content-type for $.ajax POST is application/x-www-form-urlencoded; charset=UTF-8
So, sending a POST request with various combinations of contentType and data shows the following
Firstly, without setting contentType
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
request is sent as formData '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
request is sent as formdata, the following values:
value1: 2.0
value2: setPowerState
value3[state]: 0
looks better, because there's actually multiple values, not just a string
Now, let's set contentType
contentType: 'json', data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
firefox does not tell me the format of the following string: 'value1=2.0&value2=setPowerState&value3%5Bstate%5D=0' - looks useless
And finally
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
sends the following JSON: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
So, finally, if the API requires JSON request data, and it's actually on a domain called "host.com"
$.ajax({
type: "POST",
url: "//host.com/api/comments",
dataType: 'json',
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
});

Why error function is always fired on my ajax call? [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Ajax do not pass data to method using GET

I have a method which Is accesed using Get
[HttpGet]
[AdminAuthorization]
public ActionResult MakeReservation(ReservationModel m)
{
return PartialView(m);
}
here Ajax Code:
$.ajax({
url: "/DeviceUsage/MakeReservation",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ data: Ids }),
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są unikalne " + data);
},
success: function (data) {
$('#ProperModal.modal-body').html(data);
$("#Modal").modal('show');
//if (data === "sukces") {
}
});
If I change method description and ajax type to POST function works. How should I modify this code to make it work wiht GET calls?
You need to use JsonRequestBehavior.AllowGet in your controller. For more information you could read this answer on SO
And I think it is good practise to return Json (not PartialView) in your action (for ajax). If you want to return PartialView, you could use this technique
You don't need to explictly tell the HttpGet, By Default, it takes it as HttpGet, but if you put HttpPost attribute, then it does not work on Get Requests.
Same is the case for Jquery ajax, if you don't tell it, its get or post request, it by default makes a get request to server
Remove contentType and dataType: 'json' (this indicates you are returning json, but your code returns a partial view). And Remove JSON.stringify as jQuery accept your JS object directly. Haven't tested it, but it should work.

Categories