How can I display alert only once in javascript? - 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.

Related

How to check ajax's response from laravel's controller is empty?

I work on laravel project with ajax. Below is my controller.
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->first();
return response()->json($student);
}
And this is my ajax.
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
if (typeof response.name !== 'undefined'){
console.log(response.name);
}else{
console.log("no data");
}
}
});
I can check the empty response by using typeof response.name !== 'undefined' and it work fine. But I'm not sure that is the best way or not. Any advice or guidance on this would be greatly appreciated, Thanks
You should send the correct response code if the student isn't found, and then handle that in the javascript.
For example:
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->firstOrFail(); // This will cause a 404 if the student does not exist
return response()->json($student);
}
And then in your JS:
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
console.log(response.name);
},
error: function(xhr) {
if (xhr.status === 404) {
// Handle 404 error
}
// Handle any other error
}
});

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.

AJAX showing error message

I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}

jQUery ajax code alerts an empty string

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

Categories

Resources