how to replace div content with $.ajax like a $.post - c#

The Objective:
Change my $.post to an $.ajax in order to syncronize it and display the message until request has finished.
I would like to know exactly how I could do that with an ajax request, my big problem is when I try to replace div content as what I have done it here using $.post
The code:
The view
function NewVersion() {
$.ajax({
url: "/Valoration/NewVersion",
type: "POST",
async: false,
success: function (data, status, xhr) {
if (data.success) {
$.post(data.hvmHeaderPartialView, function (partial) { $('#divHvmHeader').html(partial); });
MessageNewVersionSucced();
}
},
error: function (xhr, status, err) {
alert(err);
}
});
The controller
public ActionResult HvmHeaderPartialView()
{
return PartialView("_HvmHeaderPartialView,", DetailHvmModel);
}
private ActionResult NewVersion()
{
var result = hvmService.addNewVersion(hvm);
var HvmHeaderPartialView = Url.Action("HvmHeaderPartialView,");
return Json(new
{
success = result,
hvmHeaderPartialView= HvmHeaderPartialView,
});
}

Do you need to keep it async=false?
You could use $.load() to replace div content instead of using $.post. For example:
$('#divHvmHeader').load('ajax/test.html');
With a callback function:
$('#divHvmHeader').load('/Valoration/NewVersion', function() {
MessageNewVersionSucced();
});
Note: MessageNewVersionSucced will execute only after the ajax call to '/Valoration/NewVersion' completed.

You stated
Change my $.post to an $.ajax in order to syncronize it...
I am not sure if you are using jQuery 1.8 but the jQuery site states
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is
deprecated; you must use the complete/success/error callbacks.
Your request will not be performed synchronously. This may be the root of your problem.

Related

jQuery AJAX always executing error: {}

I'm working on a webapplication, ASP.Net MVC 4.0 with entityframework 6.0, trying to update database as per user selection. Data is sent to controller's action using jQuery AJAX. Below given is C# code to update entity which in turn updates database.
public void modidyProduct(Productdetail prodData)
{
try
{
using (SampleTrialEntities entity = new SampleTrialEntities())
{
var data = entity.Productdetails.Where(p=>p.ProductID == prodData.ProductID).FirstOrDefault<Productdetail>();
data.ProductName = prodData.ProductName;
data.ProductNumber = prodData.ProductNumber;
data.CategoryName = prodData.CategoryName;
data.ModelName = prodData.ModelName;
entity.Entry(data).State = System.Data.Entity.EntityState.Modified;
entity.SaveChanges();
}
}
catch (Exception)
{}
}
And here's jQuery AJAX call for that controller action method.
function updateProduct() {
var productData = {
ProductName: $('#prodName').val().trim(),
ProductNumber: $('#prodNum').val().trim(),
CategoryName: $('#ctgryName :selected').text(),
ModelName: $('#mdlName :selected').text(),
ProductID: atob($('#editProductId').val())
};
debugger;
$('#divLoader').show();
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (jqXHR) {
//Below line will destroy DataTable - tblProducts. So that we could bind table again. next line - loadData();
$('#tblProducts').DataTable().destroy();
$('#divLoader').hide();
loadData();
$('#addModal').modal('hide');
$('#editProductId').val('');
},
error: function (msg) {
debugger;
$('#editProductId').val('');
$('#divLoader').hide();
alert(msg);
alert("What's going wrong ?");
//alert(jqXHR.responseText);
}
});
}
After executing jQuery AJAX method & controllers action, successfully updates the record in database. Response statuscode - 200 & Status - OK is returned. But only error: { }, code block is executed every time in AJAX method.
Debugging screen capture with status-OK; statuscode - 200
This part of your $.ajax method call
dataType: 'json',
It tells jQuery that, the ajax call code is expecting a valid JSON response back but currently your server method's return type is void. That means it won't return anything and the $.ajax method is trying to parse the response (assuming it is a valid JSON), and hence getting the typical "parsererror"
When the datatype is json and the response is received from the server, the data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected.
The solution is to simply remove the dataType property in the call.
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8'
}).done(function() {
console.log('Success');
})
.fail(function(e, s, t) {
console.log('Failed');
});
Or you can update your server action method to return a json response.
[HttpPost]
public ActionResult ModidyProduct(Productdetail prodData)
{
try
{
//to do : Save
}
catch (Exception ex)
{
//to do : Log the exception
return Json(new { status = "error", message=ex.Message });
}
return Json(new { status="success"});
}
Now in your client side code, you can check the json response to see if the transaction was successful
$.ajax({
url: '#Url.Action("ModidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
}).done(function (res) {
if (res.status === 'success') {
alert('success');
} else {
alert(res.message);
}
console.log('Success');
}).fail(function(e, s, t) {
console.log('Failed');
});
You do not need to necessarily specify the dataType property value. If nothing is specified jQuery will try to infer it based on the mime type of the response coming back, in this case, the response content type will be application/json; charset=utf-8. So you should be good.

Why is Jquery AJAX and AngularJS Http Post returning different results?

I have an action in my controller that does the following:
[HttpPost]
public ActionResult RetrieveTransactionStatuses() {
throw new Exception("Test exceptioN");
return this.Json(this.RetrieveStatusLines());
}
I am calling this method using the $.ajax() using jquery and $http in angular but it is returning different results.
$.ajax({
url: '/Status/RetrieveTransactionStatuses',
method:'POST',
dataType: 'json'
}).done(function() {
console.log('success ajax');
}).fail(function () {
console.log('fail ajax');
});
$http({url: '/Status/RetrieveTransactionStatuses', method: 'POST'})
.then(function (response) {
// success
console.log('on success Angular');
},
function () {
console.log('on failure angular');
});
On my console, I read the results as:
'fail ajax'
'on success Angular'
Why are they returning different results as I expect the angular to fail because the action on the controller is throwing an exception?

Ajax post not working MVC 5

I'm trying to post data into a controller but it doesn't seems to work, I need the post to include the content of the view into a div when done but I cant quite achieve it
Here's my js function:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
And, here's my controller:
public ActionResult Schedule(String number)
{
return View(number);
}
I am a noob in MVC and C#, so any help is welcome.
There are somethings that you should fix to solve the problem.
Change Url to "/Student/Schedule"
You are using "Student/Schedule" as url, so you are trying to call an action named "Student".
Add [HttpPost] to your action.
You should return PartialView("Schedule", number);.
When you use return View(number) it uses the string value of number as your view name. You should explicitly pass view name and model.
Use $('#schedule').html(a);
It's better to add an error function to your ajax call to be able to find errors:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
Your action should return a Partial View, not a View.
Change your action to:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
Then, you'll need to create a partial view named _Schedule.cshtml.
Also, you need to change $('#schedule').load(a); to $('#schedule').html(a); And, I'd suggest that you use a Url.Action to set your url in your ajax call, like this:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '#Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
I had the same issue what i did was adding jquery.unobtrusive-ajax.js to my scripts

Calling action from jquery correctly?

I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});

ASP.Net MVC 3 Ajax query not firing

I have a very simple ajax call to refresh some data on my webpage, but it doesn't seem to fire correctly. The data that the call brings back is the same everytime even if the underlying data changes.
The ajax call looks like this:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
My controller looks like this:
public ActionResult ListByAjax(int Id)
{
var list = db.Address.Where(i => i.Person_Id == Id);
return PartialView("_List", list.ToList());
}
Try setting the cache to false in your ajax call - that will force the browser to send the request through to the controller:
function RefreshContent() {
//create the link
var link = "/Address/ListByAjax/" + $('#Id').val();
$.ajax({
type: "GET",
url: link,
cache: false,
success: function (data) {
$("#Address").html(data);
},
error: function (req, status, error) {
alert('an error occured: ' + error);
}
});
}
Use
ajaxSetup({ cache: false }); });
This turns off caching for all ajax calls made by your app.

Categories

Resources