Bind event after login - ajax

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';
}
}
});

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);
}
});

Wordpress, doing AJAX request before admin submit a post

I need to do some server-side checking, before admin may submit a post form:
$('body').on('submit', '#post', function(e) {
if (e.originalEvent === undefined)
{
return true;
}
var thisForm = $(this);
$.ajax('/check.php', $(this).serialize(), function(answer) {
// if answer was ok...
thisForm.submit();
});
return false;
});
actualy it works good, but in case when my post is "draft", I cant put it "public". Nothing changes, I guess some other JavaScript is affraing in the background.
BUT if I do a synchronous verion:
$('body').on('submit', '#post', function(e) {
var error;
$.ajax({type: 'POST', url: '/action.php', data: $(this).serialize(), async: false, success: function(answer) {
// if answer was ok...
error = true OR false;
});
return !error;
});
it all works GOOD! But you all know, one doesnt made synchronous ajax calls...

Duplicate entires into database while using ajax to insert

I am trying to user ajax to insert into the database for my laravel project but each time i insert i see duplicates of every item with a unique id.
Inserting normally with the form itself, this behavior doesn't repeat.
My ajax code s below.
`$('#saveCat').on('click', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = '/admin/storecat';
var type = "post";
var data = {spec: $('#cat').val() };
$.ajax({
type: type,
url: url,
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
$('#catform').trigger('reset');
//show success alert msg
$('#alert-suc').html(data);
$('#ac-alert').show('slow', function () {
setTimeout(function () {
$('#ac-alert').hide('slow');
}, 3000);
});
},
error: function (data) {
console.log('Error:', data);
}
});
});
My controller action here
public function storeCat(Request $request) {
$Category = new Category;
$Category->name = $request->spec;
$Category->save();
return response()->json('New service category ' . $request->spec . ' has been added.');
}
try to use:
e.stopImmediatePropagation();
stopImmediatePropagation will prevent any parent handlers and also any other handlers from executing.

What is callback function in AJAX? How to implement a callback function in PreSaveAction function of SP2013 list NewForm?

I want to store the value of a variable and use it outside the ajax call. But being an asynchronous call it is giving me initial value of that variable. I am implementing my custom code for some validations in PreSaveAction function since I have to do validations on Save button click of SharePoint NewForm,Following is my code,
<script type="text/javascript">
var titleItem;
var flg=0;
var dataFromServer;
function PreSaveAction()
{
titleItem = $("input[title='Title']").val();
$.ajax({
url:"http://sp13dev:4149/Appraisals/_api/web/lists/GetByTitle('SkillMaster')/items?$select=Id,Title&$filter=Title eq '"+titleItem+"'" ,
type: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
if(data.d.results.length>=1)
{
flg=1;
$("#labelTitle").html("Skill already exists. Please enter another name.");
}
else
{
flg=0;
$("#labelTitle").html("");
}
},
error: function (error) {
alert(JSON.stringify(error));
}
});
if(flg==1)
{
// $("#labelTitle").html("Skill already exists. Please enter another name.");
return false;
}
return true;
}
</script>
It seems like you have misplaced your return call. You should have your return placed inside your
if(data.d.results.length>=1)
statement inside the success callback function.

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

Resources