I'm a newbie at asp.net and trying to understand ajax responses. I have following code:
$(document).ready(function () {
$('#<%=cbx_pep.ClientID%>').change(function () {
var mSis = $('#<%=cbx_pep.ClientID%>').val();
getRCT(mSis);
});
});
function getRCT(mez_sis) {
$.ajax({
url: '/Staff/PEX.aspx/GetTempInfo',
method: 'get',
contentType: 'application/json',
data: '{d_val:' + mez_sis + '}',
dataType: 'json',
success: function (data) {
alert(data.d);
},
error: function (error) {
alert(error);
}
});
}
and that's my server side code:
[WebMethod]
public static string GetTempInfo(string d_val)
{
string str = d_val;
return str;
}
I'm repeatedly getting error. Appreciate for help.
First, as mybrithname said, You have yo use method: 'post' and then your json is invalid, you have a missing quotes there:
It should be something like this
data: '{d_val:\"' + myVar + '\"}',
You should use method: 'post' if you are going to send data to the server, which you are doing in data: '{d_val:' + mez_sis + '}'
Related
I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});
can you help about that issue?
I am trying to pass my data to the controller. Below you can see my ajax code.
<script type="text/javascript">
$(document).on("click", "#login_button", function () {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
if (userName !== "" && password !== "") {
$.ajax({
url: '/Home/Login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {
'userName' : userName,
'password' : password
},
datatype: 'json',
success: function (data) {
}
})
}
else {
alert("Lütfen Alanları Doldurunuz.")
}
})
</script>
And my controller is like,
[HttpPost]
public ActionResult Login(string userName, string password)
{
return View();
}
I checked my data and it is not empty or null. How can I fix it?
Now I am getting this error =
jquery.min.js:4 POST http://localhost:59277/Home/Login 500 (Internal Server Error)
Thanks a lot.
I had the same problem today during a programming competition.
What solved it for me was using a different way of sending a GET request:
$.get("URL/to/send/request/to", function(data, status){
alert("Data: " + data + "\nStatus: " + status);//data is the actual response you get, while status is weather the request was successful
});
});
Hope it works for you too.
i thik you should use
url: 'http://stackoverflow.com/Home/Login',
instead of
Home/Login
i solve my problem changing the type of ajax as "GET" and changing my controller as "HttpGet" but when I do this for "POST" it didn't solve. Can anyone explain it to me?
$.ajax({
url: 'http://stackoverflow.com/Home/Login',
type: "POST",
dataType: 'json',
data: dataToPost,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("hi" + data);
}
});
i think it is work
I have a canvas in my .aspx form page where one can sign a signature, I would like to send the base64 data from the JQuery client side to the C# Asp.Net side. Here I want to upload this base64 data to a database.
(a couple things I tried)
Jquery:
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: '{ data: "' + base64 + '"}',
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 }); // another thing i tried
C#:
var d = Request.Params["data"];
The variable d is null when i put a breakpoint at it.
Does anybody see how I can tackle this hurdle, or make it easier?
(note: I do not have a lot of experience with JQuery)
Your JSON with base64 could be available as request body.
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
string text = reader.ReadToEnd();
}
If you replace
url: 'EvaluatieForm.aspx'
by
url: 'EvaluatieForm.aspx?data=' + base64
and remove
data: '{ data: "' + base64 + '"}',
then it will work.
Try this:
Just a small change in your existing code, used JSON.stringify to post data.
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
var objectToPasss = {data: base64};
var postData =JSON.stringify(objectToPasss );
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: postData,
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 });
Try this:
$("#savebtn").bind("click", function () {
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: {
sketch: $('#sketch')[0].toDataURL("image\png")
},
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
where
var d = Request.Params["sketch"];
The data argument in the jQuery ajax() function works in conjunction with the contentType. As you are setting it to application/json, then it stands to reason that data will be serialized, so setting the sketch variable seems about right.
With ajax you can try xhr.
maybe this thread helps you out! :)
How can I upload files asynchronously?
EDIT- I have figured out that the request is working correctly but I don't know what to do with the data once it has been retrieved from the server. I don't know how to access the JSON, how do I do this?
I am trying to do a jQuery AJAX request and parse the JSON which is hopefully received. Here is my code:
search.onsubmit = function() {
$.getJSON("http://www.geocodefarm.com/api/forward/json/d4abb1b19adb13e42eac5a7beac6f4dbeb4b4ba4/" + searchBox.value, function(data) {
var rawJSON = $.parseJSON(data);
alert(rawJSON.COORDINATES.latitude);
});
alert("test");
}
I known that the getJSON function is not working because the test alert appears. Why does it not work?
You can do it like so:
sendAjax: function (url, dataObj) {
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(dataObj),
contentType: "application/json; charset=utf-8",
timeout: 30000,
success: function (result) {
//do shit..
}
,
error: function (result) {
}
});
}
I am using render partial concept in MVC. Its not showing the output in div. While debugging everything is OK (Showing Staus 200 OK) but its not going inside success block.Below is my jquery function.
function ShowNavigation() {
var jsonObj = {
'Display': 'Index',
taFormula: $('#taFormula').val()
};
$.ajax(
{
url: "/Home/Index",
type: "POST",
data: jsonObj,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var message = data.Message;
$("#contentDiv").html(message).val();
}
});
}
My Controller code is:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var val = collection["taFormula"].ToString();
ViewBag.Output = GetValue(val);
return View();
}
Remove the datatype: "json" bit. You're receiving html back from the server, not json data, but because of that setting it's trying to parse it and failing. If you had an error callback function it would go into that.
Also, you don't need the .val() on $("#contentDiv").html(message).val();
Try adding an error handler to the ajax call and see if that gives you any more information:
error: function (xhr, status, error) {
alert(status + " : " + error);
}
Try this for your json object:
data: JSON.stringify(jsonObj),
You might need to include json.js for older browsers.