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.
Related
I need to send mail to user after downloading .csv file. I am not sure how to set callback function after file gets downloaded.
$.ajax({
url: '#Url.Action("GetAllCustomer", "Customers")',
type: 'POST',
data: { 'customerIds': strCustomerId },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
} else {
toastLast = toastr.error("No data found", "Generating File");
}
}
});
In above code in first call i am getting all the customers. On success callback i am calling DownloadFile method to download csv file. i have requirement to send mail after downloading file but i am not sure how will i know that file is downloaded. Or Can I achieve with some other way.
Please find my DownloadFile method of controller as below.
public ActionResult DownloadFile(string extension)
{
var dateTime = DateTime.Now.ToString("M.dd.yy");
var fileName = dateTime + " Application File." + extension;
var array = TempData["Output"] as byte[];
if (array != null)
{
var file = File(array, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file;
}
else
{
return new EmptyResult();
}
}
Don't use this line
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
Instead use a ajax request to the Action method
$.ajax({
type: "POST",
url: '#Url.Action("DownloadFile", "Customers")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
//add your sccuess handlings
}
error: function(){
//handle errors
}
});
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.
I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");
My html code is like this :
<i class="fa fa-file-pdf-o"></i>
My javascript code is like this :
function showAjaxPdf(file_path)
{
var file_path = file_path.replace(/\\/g,"/");
//example : file_path = assets/images/myfile.pdf
$.ajax({
type: "POST",
data: 'file_path=' + file_path,
url: "news/test",
success: function(response)
{
$('#test').html(response);
}
});
}
My function test in controller :
public function postTest(Request $request)
{
$file_path = $request->input('file_path');
return response()->download($file_path);
}
When I click on the pdf icon, no response.
I wish, when click on the pdf icon, appear like this:
how to keep when click pdf icon, the image appears like it?
Thank you
What I have done is, written two separate route one to verify and one to download.
On success of one ajax I have triggered window.open(downloadUrl,'_blank') to download in separete window.
It is not the way asked but it prevents any upcoming errors as verify url will sort that
$.ajax({
url: verifyUrl,
type: 'get',
cache: false,
data: null,
error: function (err){$('#ajax_loader_div').hide();},
success: function(response) {
console.log(response);
$('#ajax_loader_div').hide();
if (response.status == 'success')
{
window.open(downloadUrl,'_blank');
}else if(response.status == 'error')
{
//show error
}
}
});
for that you need to set the header with response object.
Please see the below code.
$headers = array(
'Content-Type'=> 'application/pdf'
);
$file_path = $request->input('file_path');
//TODO: you have to split the file name from url
return Response::download($file_path, '<filename>', $headers);
I hope this code will help you
return Response::download($file_path, '<filename>', $headers);
It's return response, not download file!
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);
}