jQUery ajax code alerts an empty string - javascript

I send an ajax request when the user fills the email input, here is the code:
_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
},
});
}); // end of email blur
Then the php returns a string on success, and one on failure (CodeIgniter Controller)
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo (json_encode("thanks"));
}
else
{
echo (json_encode("Ranks"));
}
}
PROBLEM: it seems ajax request is successful, but the message it alerts is not appropriate since it alerts an empty string.

i'd look at this:
json_encode("thanks")
I havent coded any PHP for a long time but shouldnt json_encode be for encoding associative arrays? eg
json_encode(array("message" => "thanks"))

as you are using json_encode you could try this after the if else statement
exit(json_encode($respond));
return $this->output->set_output(json_encode($respond));
where $respond is the message you want to display.

_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
}
});
});
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo "thanks";
}
else
{
echo "Ranks";
}
exit;
}
For resonse in json you should use data type like:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

php code:
json_encode(array("content" => "thanks"));
js code:
success: function(message)
{
alert(message.content);
}

Related

userName verification with jQuery

Username Availability
I want to make an Ajax call that will read data from an input box in html, then call taken.php, which checks if this username is already taken.
My idea is that it will write to GET parameter like this:
taken.php?value=something
Does anybody know how to this with jQuery?
$(document).ready(function(){
$("#userName").change(function () {
var userName = $("#userName").val().trim();
if (userName != "") {
$("#userNameError").show();
$.ajax({
url: 'checkUserName.php',
type: 'get',
data: {key: "userName"},
});
}
});
});
This is what I've done so far.
pass username to checkUserName.php using get request
var userName = $("#userName").val().trim();
$.ajax({
type: "GET",
url: "checkUserName.php",
data: {
key: userName
},
success: function (data) {
alert(data);
}
});
in PHP file you can get like this
<?php
$name = $_GET['key'];
echo $name;
?>
it looks like you have everything but the return there. I personally prefer post but what you have with a boolean return should suffice
$(document).ready(function(){
$("#userName").change(function () {
var userName = $("#userName").val().trim();
if (userName != "") {
$("#userNameError").show();
$.ajax({
url: 'taken.php',
type: 'get',
data: {key: "userName"},
}).done(function(d){
//this is your callback.
//this will return the value echod by taken.php
//with a get of key = username
});
}
});
});
I would prefer a post like:
$.post('taken.php',{
key:$("#userName").val().trim();
},function(d){
// this is your callback
}

How can I display alert only once in javascript?

My case like this :
if(window.location.pathname == '/shop/payment/checkout' || window.location.pathname == '/shop/detail' || window.location.pathname == '/shop') {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
If the url accessed meets the condition of if then it will delete session by ajax and redirect to the url /shop
My problem is if redirect to url /shop, it will check again and display alert message again. So on and on
I want if the alert message appears and reload to the url /shop, it does not check anymore and displays the alert message
How can I do it?
EDIT:
After the answer given, I wrapped my code like this:
if (localStorage.getItem("cartCache") !== null) {
...
}
else {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
}
It does not work as intended.
Before removing, you could first check if the local storage data is still there. Put this before the alert:
if (localStorage.getItem("cartCache") === null) return;
... assuming this code is within a function. But you get the idea. Or you can combine it with the if you already have (a bit improved):
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.

How do I throw an error message within AJAX?

For some reason I can't throw an error message to say whether or not an email exists inside of my user table. I understand that because AJAX is async I can't use try and catch error messages inside the complete function. But I tried splitting it into functions and it still doesn't work.
Try, Catch Function (I do call this else where in my code)
try {
// Check fields are not empty
if (!firstName || !lastName || !aquinasEmail || !sPassword || !sCPassword || !Gender) {
throw "One or more field(s) have been left empty.";
}
// Check the email format is '#aquinas.ac.uk'
if(!emailCheck.test(aquinasEmail)) {
throw "The email address you entered has an incorrect email prefix. ";
}
// Check there are not any numbers in the First or Last name
if (!regx.test(firstName) || !regx.test(lastName)) {
throw "First Name or Last Name is invalid.";
}
// Check the confirmation password is the same as the first password
if (sPassword != sCPassword) {
throw "The two passwords you've entered are different.";
}
if(duplicatedEmail()) {
throw "Sadly, your desired email is taken. If you have forgotten your password please, Click Here";
}
} catch(err) {
if (!error) {
$('body').prepend("<div class=\"error alert\">"+err+"</div>");
$('.signupInput.sPassword').val('');
$('.signupInput.sCPassword').val('');
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {$('.error.alert').remove();});
}, 2600);
}
event.preventDefault();
}
AJAX Function:
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
}
});
}
verifyReg.php
<?php
header('Content-Type: application/json', true);
$error = array();
require_once '../global.php';
$_POST['aquinas-email'] = "aq142647#aquinas.ac.uk";
// Check if an email already exists.
$checkEmails = $db->query("SELECT * FROM users WHERE aquinasEmail = '{$_POST['aquinas-email']}'");
if ($db->num($checkEmails) > 0) {
$error['emailTaken'] = true;
} else {
$error['emailTaken'] = false;
}
echo json_encode($error);
?>
to handle the error with jquery ajax function add error callback like this
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function() {
//Your Error Message
console.log("error received from server");
}
});
}
to throw an exception in your PHP:
throw new Exception("Something bad happened");
Looking at your AJAX Function, and these two answers here and here, you need to make a small change to how you are returning the synchronous result:-
function duplicatedEmail() {
var result;
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
result = data.emailTaken;
}
});
return result;
}
use ajax error function..
function duplicatedEmail() {
// Use AJAX function to do verification checks which can not be done via jQuery.
$.ajax({
type: "POST",
url: "/login/ajaxfunc/verifyReg.php",
dataType: "JSON",
async: false,
data: $('.signupForm').serialize(),
success: function(data) {
if (data.emailTaken == true) {
return true;
} else {
return false;
}
},
error: function (result) {
alert("Error with AJAX callback"); //your message
}
});
}

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources