How to create a nested ajax requests? - javascript

I have a WEB API that is working fine. I want to call an action that is a part of my API via Ajax request. It seems that it is easy and I had it working for simple requests. However, I tried to put nested calls and for some reason the data that is passed to the second request gets lost. I was wondering if it is a scope problem or something I did wrong in my code.
Here is the javascript code:
$("#submit_request").click(function () {
var firstName = $("#first_name").val();
var lastName = $("#last_name").val();
var faciltiy = $("#facility").val();
// Collecting all the documents into an array of JSON
var documents = [];
var request = JSON.stringify({
"PatientFirstName": firstName,
"PatientLastName": lastName,
"Facility": faciltiy
});
//the first request is working fine and it has a success state
$.ajax({
url: "http://localhost:64611/api/requests/createRequest",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: request,
success: function (request_id, state) {
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
console.log(documents); // it is returning a correct object
console.log(typeof (documents)); // type object
$.ajax({
url: "http://localhost:64611/api/requests/addDocumentsOfARequest/",
type: "post",
datatype: 'json',
contenttype: 'application/json',
data: JSON.stringify(documents), ---> this object should be passed to the api action
success: function (response, state) {
},
error: function (err) {
if (err) {
}
}
});
},
error: function (err) {
if (err) {
}
}
});
});
The definition of my api action is like the following
public async Task<IHttpActionResult> addDocumentsOfARequest(RequestDocument[] documents)
The class RequestDocument is like the following:
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
My WebApiConfig is like the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "defaultApiRoutes",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"\d+" } // Only matches if "id" is one or more digits.
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
the parameter 'documents' is empty. Any idea?
Thanks!

Here's my exact working code :
Server
public class GamesController : ApiController
{
// GET api/<controller>
[HttpPost]
public async Task<IHttpActionResult> Post(RequestDocument[] document)
{
var req = await Request.Content.ReadAsStringAsync();
return Ok();
}
}
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
JavaScript
var documents = [];
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(documents),
success: function(a, b) {
alert("Done");
}
});
Result

try this,
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: {
document: documents
},
success: function(a, b) {
alert("Done");
}
});

Related

Javascript : Pass complex object to my controlleur (asp core)

Trying to send object to my controller :
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () {},
error: function (xhr, status, error) {}
});
In debug mode, my data is :
{"Id":"47","Guest":[{"Key":"","Pseudo":"Lolo01500","Del":false,"Add":true}]}
My Action in controller :
[HttpPost, ActionName("Invite")]
public IActionResult Invite(GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}
And Targets object classes :
public class ItemInvite
{
public string Key { get; set; }
public string Pseudo { get; set; }
public bool Add { get; set; }
public bool Del { get; set; }
}
public class GroupInviteVM
{
public int Id { get; set; }
List<ItemInvite> Guest { get; set; }
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
When execute, only the Id is updated ...
Somebody could help me ?
T.Y.
When execute, only the Id is updated ...
That is because the Guest property is not public.Add public modifier like below:
public class GroupInviteVM
{
public int Id { get; set; }
public List<ItemInvite> Guest { get; set; }//change this
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
The whole demo:
View:
<script>
var UserInvited = {
Id: 1,
Guest: [{
Key: "aaa",
Pseudo: "asd"
}]
};
console.log(JSON.stringify(UserInvited));
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () { },
error: function (xhr, status, error) { }
});
</script>
Controller:
[HttpPost, ActionName("Invite")]
public IActionResult Invite([FromBody]GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}

Sending data with post ajax to asp.net MVC controller

I am tried sent a data from view with ajax (POST) to controller in JSON format. From console.log, data is correct but data in controller missing...
Here is controller:
[HttpPost]
public ActionResult SavePermission(TestData testData)
{
return Json("DONE");
}
Here is model:
namespace INTRANETv4.Models
{
public class TestData
{
public string id { get; set; }
public bool read { get; set; }
public bool write { get; set; }
public bool delete { get; set; }
}
}
Here is javascript function from View:
function Save() {
var rows = document.getElementById("userTable").getElementsByTagName("tr");
var output = [];
for (i = 1; i < rows.length; i++) {
output.push({
id: rows[i].id,
read: rows[i].getElementsByTagName("td")[2].getElementsByTagName("input")[0].checked,
write: rows[i].getElementsByTagName("td")[3].getElementsByTagName("input")[0].checked,
delete: rows[i].getElementsByTagName("td")[4].getElementsByTagName("input")[0].checked
});
}
var myJSON = JSON.stringify(output);
console.log(myJSON);
$.ajax({
type: "POST",
contentType: "application/json",
data: myJSON,
url: "/Files/SavePermission",
dataType: "json"
});
}
Here is console.log of myJSON:
And here is content of testData from controller while debugging:
When i used string testData, because i worried about to convert, string was null. Thank you for any advice.
try
you model change to List<TestData> testData
and data change to JSON.stringify({ testData: output }),
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify({ testData: output }),
url: "/Files/SavePermission",
dataType: "json"
});

My insert method isn't working

I'm using dapper to map my database with my mvc project, i have debugged my code to know what's going on and my ReceiveData method isn't receiving the data for some reason when it sends it to my GeoCreate it shows nothing, also i might me wrong because i placed my cursor on my Geo.RouteID, Geo.Latitude,etc and the data was there then it goes to my geography class and after that it's supposed to go to the if statement but it stops there, i'm sending json data with postman.
Here's my ReceiveData method
public bool ReceiveData(Geography Geo)
{
int GeoCreate = this.conn.Execute(#"INSERT GEOGRAPHY([ID_ROUTE],[LAT],[LONG],[BATTERY],[DateCreated],[DEVICE_ID]) values (#Lat,#Long,#Battery,#DateCreated,#Device_ID)",
new { RouteID = Geo.RouteID, Lat = Geo.Latitude, Long = Geo.Longitude, Battery = Geo.Battery, DateCreated = Geo.ObtainedDate, DeviceID = Geo.Device_ID });
if(GeoCreate > 0)
{
return true;
}
return false;
}
Here's the action for calling the ReceiveData method:
[Route("GeoCreate")]
[HttpPost]
public bool StoreLocation(Geography Geo)
{
return GD.ReceiveData(Geo);
}
Here's the javascript code that works for sending my data:
<script>
$(document).ready(function () {
var Geograph = {
Latitude: $("#Latitude").val(),
Longitude: $("#Longitude").val(),
Country: $("#Country").val(),
ObtainedDate: $("#ObtainedDate").val()
};
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.parse( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
});
</script>
And my Geography class:
public class Geography
{
[Key]
public int RouteID { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Battery { get; set; }
public DateTime ObtainedDate { get; set; }
public int Device_ID { get; set; }
}
Here's the JSON data i'm sending:
{
"Latitude": 19.435547,
"Longitude": -81.77856,
"Battery": 100,
"ObtainedDate":"\/Date(1522600449000)\/",
"Device_ID": 1
}
I'm not setting the RouteID because it fills automatically in the database.
In your ajax call you should use JSON.stringify rather than parse method
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.stringify( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}
You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})
I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

How To access and display the data from database using ajax jquery asp.net mvc

I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me
Model:
public class EmployeeModel
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
Controller :
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
public ActionResult GetUser()
{
return View();
}
public JsonResult GetAllUser(int EmpId)
{
List<EmployeeModel> employee = new List<EmployeeModel>();
string query = string.Format("Select * From Employee", EmpId);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
employee.Add(
new EmployeeModel
{
EmpId = int.Parse(reader["EmpId"].ToString()),
EmpName = reader.GetValue(0).ToString(),
Age = int.Parse(reader["Age"].ToString()),
Salary = int.Parse(reader["Salary"].ToString())
}
);
}
}
return Json(employee, JsonRequestBehavior.AllowGet);
}
}
ajax:
#{
ViewBag.Title = "Home Page";
var EmployeeModel = (List<second_day.Models.EmployeeModel>)Model;
}
<div id="id"></div>
<div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('p#getEmployee').click(function () {
GetEmployeeUsingAjax();
});
});
function GetEmployeeUsingAjax() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data:{"EmpId":EmpId},
dataType: 'json',
success: function (data) {
console.log(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
Here i Need to fetch the data when its success else through error if it doesnt
Am new to this platform can anyone help me
function GetEmployeeUsingAjax() {
var EmpId = 2;
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data: { "EmpId": EmpId },
dataType: 'json',
success: function (data) {
alert(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
// your code
}
plus string.Format("Select * From Employee where empid = {0} ",EmpId)
Please Check Below code :
var var EmpId = 2;
var abc = {
"EmpId": EmpId
};
$.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});
And Action Should Be :
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
}
Happy !!

Categories