I am struggling to pass data to controller through Ajax - javascript

Trying to hit DeleteJobQuote controller through Ajax but no luck. Please guide me if anyone has any idea about it. The code seems OK but not able to do so. I am writing this code to delete a particular record from database.
Controller
[HttpPost]
public ActionResult DeleteJobQuote(int jobQuoteid)
{
using (var db = new KeysEntities())
{
var delJob = db.JobQuote.FirstOrDefault(x => x.Id == jobQuoteid);
if (delJob != null)
{
delJob.Status = "Delete";
db.SaveChanges();
return Json(new { success = true, Message = "JobQuote SuccessFully Deleted!" });
}
else
{
return Json(new { success = false, Message = "Delete UnSuccessFul " });
}
}
}
And JavaScript and Knockout code for this
self.deleteJobQuote = function (jobQuote) {
debugger;
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
};

Change "data : ko.toJSON(this)" to "data: JSON.stringify({ jobQuoteid: 1 })". I have hardcoded jobQuoteid value to 1. Get it from jobQoute object.
complete code:
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ jobQuoteid: 1 }),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});

Related

JavaScript Post and wait for Response JSON

Right now i have the following code below, this code posts some data to my page and waits for a response of status = SUCCESS or Failure. I am trying to understand if this is async or sync. How can I make this JavaScript query wait for the response and then run what is inside success? It doesn't seem to wait for the response of what it is posting to.
Thanks!
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.post('', form.serialize(), function(json) {
console.log(json)
if(json.status === 'SUCCESS') {
console.log('success');
window.open(json.imgid, '_self');
} else {
console.log('failure');
}
}, 'json');
$('#progress_bar').show();
}
I then tried to work on making it work the way i wanted by editing the code below but now its just returning the HTML contents of the entire page rather than the JSON response. Any idea why its not getting the JSON response?
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.ajax({
url: '',
type: 'POST',
data: data,
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
Add dataType: 'json', below data: data,
my.submit = function() {
var form = $('#lines');
//console.log(form)
var data = form.serialize();
//console.log(data)
$.ajax({
async: false,
url: '',
type: 'POST',
data: data,
dataType: 'json',
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
window.open(json.imgid, '_self');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}

How to redirect after successful login from a bootstrap modal page to a different view or a page with the login user information

This is the UI of the demo Application.
I am sending an ajax request to the controller which is verifying the user id and password from the getloginuser method ,the response is coming. I just want to redirect it after successful login to some other page. Can i do anything in callback (jquery).i searched lot of things on net but could not get suitable answer.
Login Image
This is the jquery code
//method
function Login()
{
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
$('#myModal1').modal('hide');
alert('Login Successful');
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
This is the Login Controller Method:
public JsonResult Login(User info)
{
return Json(obj.GetLoginUser(info), JsonRequestBehavior.AllowGet);
}
You can do in your ajax function like this:
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
if(result != null || result != "")
{
window.location.href= "Your redirect url";
}
else
{
alert("login error");
return false;
}
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use window.location to redirect to any location your application. Just Implement it in the success part of your Ajax call.
function Login()
{
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
$('#myModal1').modal('hide');
RedirectToPage();
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
function RedirectToPage()
{
window.location='Your Link Goes here';
}

Use AJAX to handle array of IDs coming as NULL C# and JS

I am trying to take array from string on server side ,but the IDs that I am waiting for are coming as NULL. Please , advice regarding the provided source code above. I am not sure how to handle them in the scope of CompareReturnAllResults(.....).
function compareFilesResult(whlIDs) {
var result = 0;
$.ajax({
url: '/ajax/CompareReturnAllResults',
contentType: "application/json; charset=utf-8",
type: 'GET',
dataType: "json",
data: { ID: whlIDs },
success: function (data) {
if (data != null) {
return result;
}
},
error: function (data) {
return result;
},
fail: function (data) {
return result;
}
});
}
[HttpGet]
public ActionResult CompareReturnAllResults(string [] _IDs)
{
List<Common.Utilities.CompareFilesResult> result = new List<Common.Utilities.CompareFilesResult>();
foreach (var id in _IDs)
{
var whl = WHLConfig.Caches.WHLsCache.Where(w => w.ID == id).First();
var diffResponse = WhlObjects.WHLMethods.CompareConfigs(whl);
Common.Utilities.CompareFilesResult temp = new Common.Utilities.CompareFilesResult(whl.ID, diffResponse.CountDeleted, diffResponse.CountInserted);
result.Add(temp);
}
string diff = string.Empty;
if (result != null && result.Count != 0)
{
return Json(result, JsonRequestBehavior.AllowGet);
}
else
{
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}
}
I think it looks like I need to set traditional to true.
Script:-
jQuery.ajaxSettings.traditional = true
First One:-
$.ajax({
url: 'controller/GetArray',
data: JSON.stringify({
employee: arrEmployee
}),
success: function(data) { /* Whatever */ }
});
****Second One:-****
$.ajax({
type: "POST",
url: "controller/GetArray",
data: {employee: arrEmployee},
success: function (data) { /* Whatever */ }
});
Model:-
public class Employee
{
public int Id;
public string Name;
}
In Controller:-
public ActionResult GetArray(Employee[] employee)
{
// code here what u do
}
Hope Its Work !!
If you have used contentType: "application/json; charset=utf-8", it tells to server that we send a json object. For this you have to use JSON.stringify() method.
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
JSON.stringify() turns a javascript object to json text and stores it in a string.
$.ajax({
url: '/ajax/CompareReturnAllResults',
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
data: JSON.stringify({ _IDs: whlIDs }),
^^^^^^^^^^^^^^^^
success: function (data) {
if (data != null) {
return result;
}
},
error: function (data) {
return result;
},
fail: function (data) {
return result;
}
});
C#
[HttpPost]
public ActionResult CompareReturnAllResults(List<string> _IDs)
{
//code
}
Another method is to use traditional:true property.
$.ajax({
url: '/ajax/CompareReturnAllResults',
type: 'GET',
dataType: "json",
data: { _IDs: whlIDs },
traditional:true,
success: function (data) {
if (data != null) {
return result;
}
},
error: function (data) {
return result;
},
fail: function (data) {
return result;
}
});
C#
public ActionResult CompareReturnAllResults(List<string> _IDs)
{
//code
}

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

ajax call not working with in ajax

I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}

Categories