jQuery AJAX form submit error working success not - ajax

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"

Related

Joomla Ajax request always return success

I'm trying to login in Joomla! by Ajax with default login module. But it always return success-
$('a.login_submit').click(function(e){
e.preventDefault();
$username = $('#username').val();
$password = $('#password').val();
$.ajax({
type: 'post',
url: 'index.php?option=com_ajax&module=login&method=user.login&format=json',
data: {username: $username, password: $password},
success: function(){
$('.error').hide();
$('.success').show();
},
error: function(){
$('.success').hide();
$('.error').show();
}
});
});
Why this always return true?
It'll be always a success (provided you have a connection with a server). You must analyse the response on success to validate the credentials.
success: function(data){
if ( data === "Correct" ) {
//handle login
}
else {
alert(data);
}
}

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

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

Redirecting after Ajax post

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?
window.APP_ROOT_URL = "<%= root_url %>";
Ajax
$.ajax({ url: '#{addbank_bankaccts_path}',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
dataType: "json",
data: 'some_uri=' + response.data.uri ,
success: function(APP_ROOT_URL) {
window.location.assign(APP_ROOT_URL);
}
});
success: function(response){
window.location.href = response.redirect;
}
Hope the above will help because I had the same problem
You can return the JSON from server with redirect status and redirect URL.
{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
And in your jQuery ajax handler
success: function (res) {
// check redirect
if (res.redirect) {
window.location.href = res.redirect_url;
}
}
Note you must set dataType: 'json' in ajax config. Hope this is helpful.
Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.
$('#checkout').click(function (e) {
e.preventDefault();
$.ajax('/post/url', {
type: 'post',
dataType: 'json'
})
.done(function (data) {
if (data.cartCount === 0) {
alert('There are no items in cart to checkout');
}
else {
window.location.replace('/Checkout/AddressAndPayment');
}
});
});

Ajax in Wordpress plugin

I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}

Resources