JavaScript POST falls when connect to MVC controller - javascript

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!

I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

Related

Ajax success event doesn't fire

Doing Okta Authentication on WebForms
The login works but the redirect part doesnt
I tried with void and to return json object/string but doenst work
if i delete contentType and dataType from ajax method the success event works but then i can't debbug the method and it wasn't doing what was suppose to do
My objective is at the end of the webmethod to redirect to SignedIn.aspx tried with this code but couldn't make it work either that's why im doing client side through ajax success method
HttpContext.Current.Response.Redirect("SignedIn.aspx");
Ajax:
function FormSubmit() {
$.ajax({
type: "POST",
url: "Example.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("Method Called Sucessfully" + response);
window.location.href = "http://localhost:8080/SignedIn.aspx";
},
error: function (response) {
alert("error " + response);
}
});
}
WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Login(string hiddenSessionTokenField)
{
//var result = new { url = "http://localhost:8080/SignedIn.aspx" };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var properties = new AuthenticationProperties();
properties.Dictionary.Add("sessionToken", hiddenSessionTokenField);
properties.RedirectUri = "~/SignedIn.aspx";
//Okta Authentication
HttpContext.Current.GetOwinContext().Authentication.Challenge(properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType);
//System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
//return s.Serialize(result));
}
//return s.Serialize(result));
}
$('#test').on('click', function () {
$.ajax({
type: "POST",
url: "TEST.aspx/Login",
data: "{hiddenSessionTokenField:'" + $('#hiddenSessionTokenField').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// alert("Method Called Sucessfully");
window.location.href = "http://localhost:8080/index.aspx";
},
error: function (response) {
alert("error " + response);
}
});
})
public static void Login(string hiddenSessionTokenField) {
int x = 0;
}

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

How to pass a list of id's in a AJAX request to the Server in MVC

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});

How to get data from Ajax

I have a variable called sid which handle number of seat. I want to throw sid to TryJSON.aspx method test. then I wanna do manipulate data on method test then throw back the result to this ajax. but I have an error when I just try to throw sid
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
this is my C# code to receive noSeat
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
// return noSeat;
//JavaScriptSerializer serializer = new JavaScriptSerializer();
// return new JavaScriptSerializer().Serialize(new { noSeat = noSeat });
}
I have try return only noSeat and also with Javascript serializer. but it has an error. it says
An attempt was made to call the method 'test' using a POST request, which is not allowed.
I have been tried
return "Success !!"
but it doesn't appear on console and still same error.
what's the matter ?
var sid = jQuery(this).attr('id');
console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (response) {
var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});

Post JSON data along with id in Jquery AJAX

I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}

Categories

Resources