Wordpress, doing AJAX request before admin submit a post - ajax

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...

Related

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

Ajax calls and JQuery: stop previuos ajax calls

In a jsp page, when a user clicks a button, an ajax call is triggered.
If the user clicks again and again the button, I would that only the last ajax call be valid and only its response be considered.
I use:
var lastRequest=null;
$('#button').click(function() {
if (lastRequest) {
lastRequest.abort();
lastRequest = null;
}
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
With Firebug, I see that some request are aborted, but not all.
I think that if an ajax call is triggered, it's not possible to ignore the response, is it?
EDIT
If I set a var in MyAction.do and I read it in the success callback, is it possible to have a conflict in the success callback?
In case, how could I prevent that behaviour?
My experience with aborting ajax-calls is that it can be pretty random when it works.
A workaround that I've used once or twice is counters:
var lastRequest=null;
var started = 0, finished = 0;
$('#button').click(function() {
++started;
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
//Only do stuff on the last active request
if(++finished == started)
response= $('<div/>').append(response);
}
});
});
use object.abort() to discard data that have been called by service
i have add the code as to click on a button to abort service you can try it with respect to your case :)
lastRequest = $.ajax({
type: "POST",
url: "MyAction.do",
success: function (response) {
response= $('<div/>').append(response);
}
});
});
$(document).click(function() {lastRequest.abort() });

jquery form validation before ajax request?

this is a simple code to call the form validation function before submit it with ajax request
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
beforeSubmit: function(){
return $("#categoryForm").validate();
},
success: function(response) {
$('#status').html(response);
}
});
return false;
});
});
it pass the validation and send the ajax request before validating the form
i tried to make the request if the validation true
$(document).ready(function(){
$('#errors').hide();
var serializedData= $("#categoryForm").serialize();
$("#categoryForm").submit(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
}
});
}
return false;
});
});
but this not working too
Dont submit the form in any case, do the check when the submit button is clicked - and then if it succedeed - do the submiting.
Try to do it as follows:
$("#submitButton").click(function(){
if($("#categoryForm").validate()){
$.ajax({
type:'POST',
url: 'actions/add-category.php',
data: serializedData,
success: function(response) {
$('#status').html(response);
//if true:
$("#categoryForm").submit();
}
});
}
return false;
});

jQuery AJAX form submit error working success not

EDIT
Ok, so I can login fine but when I enter false info I'm redirected to the login page, what I need is to stay on the same page and show the error message e.preventDefault(); doesn't seem to work.
$(function() {
$("#login-form").submit(function(e) {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
e.preventDefault();
},
success: function(){
document.location = '/';
}
});
return false;
});
});
Your not actually doing anything with the form, ill try commenting your code to talk you through whats happening.
I'm guessing your using PHP server side for this code.
In PHP you want to check the user credentials and then tell the browser. If the login was successful send back "y", and if it failed "n".
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
},
success: function(data) {
if (data == "y") {
//Login was successful. Redirect statement here?
} else {
//Failed login message here
}
}
});
return false;
});
});
</script>
Edit
Try adding this in your success function. Please let me know what you get for a successful login and a failed login.
success: function(data) {
console.log(data);
}
Edit 2
This is because your ajax call is successful, just that the login failed. This is why your success handler is called.
To sort this you'll need to see what is being returned from the server, is it nothing? In which case try:
success: function(data) {
if (data == "") {
e.preventDefault();
} else {
//Login successful, redirect user.
}
}
You should add:
success: function(data){
/* Validation data here, if authentication answer is correct */
if(data == 'ok')
document.location = '/';
else
/* show error here */
}
the success occur when URL is found and accessible.
and error occur when URL is not found.
if you want check the callback MSG you must print it in the URL page & check data in success.
like this:
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
success:function(data){
if(data=="true"){
alert("success");
}else{
alert("faild")
}
}
});
return false;
});
});
</script>
in login.php
<?php
//check if for true...
echo "true";
//and if it is not true...
echo "false";
?>
the data parameter in success is a string which get back the html content of "/login"

How are people handling AJAX posts to ActionMethods using [ValidateAntiForgeryToken]

Seeing that the __RequestVerificationToken is not sent when using AJAX and ValidateAntiForgeryTokenAttribute is looking for the token in Request.Form, how are people dealing with this problem.
I ended up doing this.
$("#regmember-form").submit(function (e) {
e.preventDefault();
var token = $('[name="__RequestVerificationToken"]').val();
alert($(this).attr('action'));
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: { __RequestVerificationToken: token }
});
return false;
});
Very similar to the accepted answer.
I grab the input off the page and send it back with the form post. This assumes that you include it on the page in the first place.
$('#somebutton').click( function() {
var data = $('[name="__RequestVerificationToken"]').serialize();
$.post('/foo/bar', data, function(result) {
// ...
});
});

Resources