Close Jquery dialog based on resulted validation - ajax

I am loading a PartialView into a Jquery UI dialog and if something went wrong during the post method I reload the PartialView into the dialog again ( ModelState errors for example ) . At this point my ajax sumbit doesn't work anymore. It justs redirect me and it should not.
What is wrong in my code ? Here is what I have tried :
$('#editdialog').dialog({
autoOpen: false,
width: '900px',
modal: true,
open: function (event, ui) {
$(this).load('Controller action', function (html) {
$('#incarcerationForm').submit(function () {
$.ajax({
url: 'Controller action',
data: $("#myForm").serialize(),
type: "POST",
success: function (data) {
$('#editdialog').html(data);
$.validator.unobtrusive.parse($("#myForm"));
if ($("#myForm").valid()) {
GetDetails(#Model.FormModel.ID);
$('#editdialog').dialog('close');
console.log("myForm was edited successfully");
return false;
}
return false;
},
error: function (data) {
$('#editdialog').html(data);
console.log("error at edit myForm");
return false;
}
});
return false;
});
return false;
});
}
});
And my [HttpPost] Controller action :
public ActionResult Create(Mymodel viewModel)
{
return CheckValidBusiness(() =>
{
viewModel.Save(viewModel.FormModel); return true;
})
.Valid(() => PartialView(viewModel))
.Invalid(() => PartialView(viewModel));
}

Replace:
$('#incarcerationForm').submit(function () {
with:
$(document).on('submit', '#incarcerationForm', function () {
so that you subscribe to the submit event of the form in a lively manner which will be resilient to DOM changes. Take a look at the .on() method for more information.

Related

WordPress ajax call with add_filter

I have a WordPress function that works exactly how I want. The function below changes the email recipient in Contact Form 7 to abc#aol.com.
Now I need to use AJAX to update the email recipient to a dynamic value.
function wpcf7_dynamic_email_field($args) {
if(!empty($args['recipient'])) {
$args['recipient'] = str_replace('%admin%', 'abc#aol.com', $args['recipient']);
return $args;
}
return false;
}
add_filter('wpcf7_mail_components', 'wpcf7_dynamic_email_field');
Here's my AJAX call. I do not know how to tell the call to initiate the wpcf7_dynamic_email_field() function. Can that be done?
$.ajax({
url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'update_team_page_contact_form',
'emailAddress' : emailAddress
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});

AJAX call inside Ckeditor widget's upcast function

I would like to use an AJAX call (via jQuery) to change the HTML of a widget during the upcast function of a CKEditor widget. Here is what I have tried:
CKEDITOR.plugins.add('mywidget', {
requires: 'widget',
icons: 'mywidget',
init: function (editor) {
editor.widgets.add('mywidget', {
button: 'My widget',
template: '<p class="mywidget">Initial text.</p>',
allowedContent: 'p(!mywidget)',
upcast: function (element) {
if (element.hasClass('mywidget')) {
element.setHtml('After upcasting.');
$.get('http://example.com')
.done(function (response) {
element.setHtml('Updated text after AJAX.');
});
return true;
}
return false;
},
});
}
});
When the widget is first instantiated, as expected, it says:
"Initial text."
After I click "Source" and then click "Source" again, as expected again, the text has changed to:
"After upcasting"
However, when the AJAX request comes back, the text does not change to "Updated text after AJAX".
Does anyone know how I can get at the element from inside the AJAX callback? If it is too late to access the element from the AJAX callback, is there any way to use the response from the callback to retroactively edit the markup of the already-upcasted widget? Thank you!
$.get() is asynchronous so the .done part is called after the upcasting had already completed. Use $.ajax() instead and set async: false.
The modified widget code:
CKEDITOR.plugins.add('mywidget', {
requires: 'widget',
icons: 'mywidget',
init: function (editor) {
editor.widgets.add('mywidget', {
button: 'My widget',
template: '<p class="mywidget">Initial text.</p>',
allowedContent: 'p(!mywidget)',
upcast: function (element) {
if (element.hasClass('mywidget')) {
element.setHtml('After upcasting.');
$.ajax({
url: 'http://www.example.com',
async: false,
success: function (result) {
element.setHtml('Updated text after AJAX.');
}
});
return true;
}
return false;
},
});
}
});

ajax - request error with status code 200

From client side, I wanna send some data to server and receive some <div> tags which responding from View (another controller).
My ajax code looks like this:
var sortTopic = function () {
var $list = [],
$address = '',
$formData = new FormData();
/* do something here to set value to $list and $address */
$formData.append('Category', $list);
$formData.append('Address', $address);
$formData.append('Tags', '[KM]');
$formData.append('Skip', 0);
$.ajax({
url: '/Topic/Sort',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
if (!data.success) {
$('.jumbotron').html(data.ex);
} else {
$('.jumbotron').html(data);
}
},
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
});
};
In TopicController, action Sort was:
[AllowAnonymous]
[HttpPost]
public ActionResult Sort(SortTopicViewModel model)
{
try
{
if (model.IsValidSortTopicModel())
{
return PartialView("../Home/_Timeline", new TopicMaster().Sort(model));
}
return Json(new { success = false, ex = "Invalid model." });
}
catch (Exception e) { return Json(new { success = false, ex = e.Message }); }
}
I'm sure that the model is valid and method new TopicMaster().Sort(model) was working fine (because I had put breakpoint to view the return data). And the partial view _Timeline is a partial view of HomeController.
My problem is: I don't understand why I get error with status code 200 in ajax:
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
Can you explain to me?
Thank you!
as you told you receive <div> in response that is not json and you mention dataType:"json" in your ajax just remove it. this will solve your problem. error 200 occur when you did not get valid response which is you mention in ajax.
for mor information you can read it documentation

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

Bind event after login

I have made a filter called auth that check if user is logged. If is not logged it redirect on the main page but if is a call ajax? I just checked if is it. If it is i just send an json status "no-log". Now i received my json response "no-log" on my client and i would like open a modal for ask login and password. The solution that i thougth was put easily for each ajax request an if statement to check if the response status is "no-log" and show the function of modal. BUT OF COURSE is not good for future update, I'm looking for a good solution where i can bind this event and if i want on the future add other status. Any suggest?
Route::filter('auth', function()
{
if (Auth::guest()) {
if ( !Request::ajax() ) {
Session::put('loginRedirect', Request::url());
return Redirect::to('/');
} else {
$status = "no-log";
return json_encode(array('status' => $status));
}
}
});
A example of call ajax
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
$.ajax({
type: "POST",
url: '/delete_post/' + USER,
data: { id_post: id_post.attr('id') },
beforeSend: function(request) {
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
},
success: function(response) {
if (response.status == "success") {
id_post.parents('div.shared_box').fadeOut();
}
},
error: function(){
alert('error ajax');
}
});
} else {
console.log("close");
}
});
});
After 10 days of exploring an idea I found a way to override ajax comportment:
It just need you replace every $.ajax() by a custom one.
If I re-use your code:
$(document).on("click", ".delete", function() { // delete POST shared
var id_post = $(this);
bootbox.confirm("Are you sure do want delete?", function(result) {
if (result) {
myCustomAjax({ // In place of $.ajax({
type: "POST",
...
Then this custom function allow you to add some action before or after each ajax callback:
For instance checking the JSON return value in order to decide if I trigger the success callback or I show a warning:
function myCustomAjax(options) {
var temporaryVariable = options.success;
options.success = function (data, textStatus, jqXHR) {
// Here you can check jqXHR.responseText which contain your JSON reponse.
// And do whatever you want
// If everithing is OK you can also decide to continue with the previous succeed callback
if (typeof temporaryVariable === 'function')
temporaryVariable(data, textStatus, jqXHR);
};
return $.ajax(options);
}
If you return a 401 for all not loggedin requests, you can use $.ajaxSetup to handle all ajax errors in your application.
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status == 401) {
window.location = 'your-login-page';
}
}
});

Resources