jQuery / AJAX success function if statement not working? - javascript

I have a section of code I am using to check if the desired username is available using a jQuery AJAX call:
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
}, error: function() {
// Not sure what to put here...
}
});
}
The script works as expected -- I check the MySQL database on _check_username.php, and I successfully return a "pass" if the name's available, or "fail" if the name is already taken, and store it in the JS variable does_it_pass_or_fail.
However, regardless of whether does_it_pass_or_fail contains "pass" or "fail", I ONLY get the response "That username is available!"
So, the AJAX / PHP / MySQL portion seems to be working fine, but this simple JavaScript if statement has me stumped!

try using this:you had some syntax error in your code close to alert.try logging error also.
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
console.log(data);
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail );
}
}, error: function(erro) {
console.log(error);
}
});
}

Use firebug to debug the ajax request.
place
console.log(data);
in the success function.

success: function(data) {
console.log(data)
}
This may help you in debugging your ajax issues.

Thank you all for leading me in the direction of further inspecting the AJAX call.
As it turns out, my '_check_username.php' script was returning a newline before returning "pass" or "fail" -- so, naturally, "\npass" is a different string than "pass". Once I realized this I was able to repair the script.

Related

Display openweathermap (API) data on website using AJAX and PHP

when i want enter a city here, nothing happens, no error in my console, i don't know why
this is my code :
ajax.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
$.post('PHP/controller.php', {variable: city});
//check not empty
if (city != ''){
$.ajax({
url: "PHP/router.php",
// url :"http://api.openweathermap.org/data/2.5/weather?q=" + city +"&lang=fr"+"&units=metric" + "&APPID=697edce53ba912538458a39d776ca24e",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].description);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return "<h3>Témpérature: "+ data.main.temp +"°C"+"</h3>" + "<h3>"+ data.weather[0].description +"</h3>";
}
this is my router.php, my js call the router
<?php
require('../PHP/controller.php');
if (isset($_GET['city'])) {
return getWeatherCity($_GET['city']);
}
else {
echo'Error';
}
?>
i know that i can do this only with js or only with php but i want use both of them.
Do you have any request happening in the "Requests" tab of your DevTool?
You should see a request towards PHP/router.php and the associated status code. Given that you might collect clues to debug what's going on.

How to send data to the server via Ajax?

The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure
This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});

Ajax event only working once

when i enter the wrong details and run it. it pops up with the error message, but if i then enter the correct details and click run it again. the sign in button changes to "Connecting..." as it should but then nothing else happens
$(document).ready(function() {
var width = ( $(".main").width() - 5);
if (width < 300) {
$(".logo-img").css({"width":width});
};
$("#error").hide();
$(function() {
$('#login').on('click', function(e){
e.preventDefault();
var token = $('#token').val();
var username = $('#username').val();
var password = $('#password').val();
var remember = $('#remember:checked').val();
$.ajax({
url: 'core/functions/ajaxLogin.php',
method: 'POST',
data: { 'username' : username,
'password' : password,
'remember' : remember,
'token' : token },
dataType: 'html',
cache: false,
beforeSend: function() { $('#login').val('Connecting...') },
success: function( data ) {
if (data == 'success') {
setTimeout( "window.location.href='backorderbook';", 500 );
} else if( data == 'userorpass' ) {
$('#error').fadeIn();
$('#error_message')
.html('username or password were entered incorrectly');
$('#error').delay(3500).fadeOut();
$('#login').val('Sign In');
};
}
});
});
});
});
Reason behind working once.
when your ajax fired, first thing to do is show connecting.. then when you get response which is data your statement says
if data == success //redirects
elseif data == userpass //show you have invalid username/password and clear html
So what if your data is not succes / userpass
it will just run your ajax beforeSend() and not will remove connecting that seems to you running once.
I recommend that your data should be an object and check if there's an error with the message on it , in short have it on your backend and just jquery show that message
There is a token generated when the login page is loaded and sent with the Ajax. But my PHP token system doesn't like the same token being sent over and over and blocks the request.
run your function with Fiddler .. and/or add the error parameter to your ajax... odds are your web request isn't a success.

How to achieve the same behaviour in Ajax

$usrname = $this->session->userdata('username');
$password = $this->session->userdata('password');
$data = array('userName'=>urlencode($usrname),'password'=>urlencode($password));
$data_string = json_encode($data);
$datanew = "loginemployee=". $data_string;
$method = 'post';
$format = 'application/json';
$this->rest->format($format);
$login_url = $this->login_url;
//print_r($login_url);
//exit;
$result = $this->rest->{$method}($login_url, $datanew);
Can anybody please assist me with this. This is actually a PHP script to login into a website, I need to achieve the same on my Cordova app which uses only HTML and JQuery, so please provide me info on how to do this.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee=". $jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
$.ajax({
type: "POST",
url: "http:// i know URL", // URL
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
alert(data);
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
You have done some mistakes in code and I listed those thing below.
Don't use $('#username').attr('value'). Instead of use $('#username').val(). Because $('#username').attr('value') return the value of the element while the html created. But $('#username').val() will return the current value. Same as change $('#password').attr('value') to $('#password').val(). For more information check this post.
Concatenation operator in javascript is + not .. And also u added a variable like $jsonString.
In your Server php code, if your using $_POST['loginemployee'] to retrieve the post values means don't use contentType: "application/json; charset=utf-8",. Because it will use the entire content including key as invalid json like loginemployee={"userName":"cloud","password":"cloudnine"}. If you need like that means u need to use file_get_contents('php://input') to retrieve the post content. But better don't use contentType in ajax. So you can able to easily get the post content using $_POST['loginemployee'].
And also if the reply is json means use dataType in ajax, else dont use that. For more information about contentType and dataType check this post.
So, I updated the code. Check and reply back if there is any issues. Hope it will work as your wish.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').val(); // get username
var password = $('#password').val(); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee="+ jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
console.log(datanew);
$.ajax({
type: "POST",
url: "http://url_to_post", // URL
// contentType: "application/json; charset=utf-8",
// If reply is json means uncomment the below line.
// dataType: "json",
// send username and password as parameters
crossDomain : true,
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});

Page redirect with successful Ajax request

I have a form that uses Ajax for client-side verification. The end of the form is the following:
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
EDIT: this is my mail3.php file dealing with errors:
$errors=null;
if ( ($name == "Name") ) {
$errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
$errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
$errors .= $spamError; // spam error
}
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
//header ("Location: thankyou.html");
echo "Your message was successfully sent!";
//instead of echoing this message, I want a page redirect to thankyou.html
} else {
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?
Thanks!
Amit
Sure. Just put something at the the end of your success function like:
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
where your server returns the response no_errors when there are no errors present.
Just do some error checking, and if everything passes then set window.location to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
You can just redirect in your success handler, like this:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
}
});
In your mail3.php file you should trap errors in a try {} catch {}
try {
/*code here for email*/
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
}
Then in your success call you wont have to worry about your errors, because it will never return as a success.
and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.
I posted the exact situation on a different thread. Re-post.
Excuse me, This is not an answer to the question posted above.
But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.
Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?
In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...
Just my 2 cents. :)
I think you can do that with:
window.location = "your_url";
I suppose you could attack this in two ways;
1) insert window.location = 'http://www.yourdomain.com into the success function.
2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/
Another option is:
window.location.replace("your_url")

Categories