Joomla Ajax request always return success - ajax

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

Related

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

Trying to use react Link within ajax success function

I am doing a simple app with react and flask. At this moment i am trying to implement the routing, with react-router, of a successful registration. I planned on doing this inside the ajax success function but i am struggling a bit.
handleSubmit:function(evt){
var data = {
client: this.state.client,
name: this.state.name,
email: this.state.email,
password: this.state.password,
contact:this.state.contact
};
evt.preventDefault();
$.ajax({
type:"POST",
url: "/api/v1/register",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify(data),
success:function(result){
if(result.result == "That account already exists"){
$("div.notification").html(result.result).show();
}
else if(result.result == "You didnt choose a user type"){
$("div.notification").html(result.result).show();
}
else{
console.log(result.result);
**I tried Link to and push.history.pushState and it didnt work**
}
},
error:function(){
console.log("error with ajax");
}
});
}

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

401 (Unauthorized) error with ajax request (requires username and password)

I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}

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"

Resources