How to display file upload error message on ajax error? - javascript

I'd like to display file upload error on an ajax alert error message.
This is my ajax:
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
if (data.result != 0) {
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.success('UPLOAD SUCCESS', 'Attention...');
if(activeid != 0){
if($("#tl_responder").val() != "" && $("#tl_dept").val() != "" && $("#tl_jawab").val() != ""){
toastr.success('MAIL IS SENT', 'ATTENTION...');
}
}
} else { window.location.href = "<?php print base_url(); ?>complaint/detail?id=" + data.result + "#reloadafteradd"; }
},
error: function (jqXHR, textStatus, errorThrown, data)
{
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.error(errorThrown, 'Error...'); //THIS IS THE AJAX ERROR ALERT
if(!errorThrown){ toastr.error(data.upl_error, 'Error...'); }//This is not working
}
});
The AJAX error alert only shows alert when AJAX is not working. I'd like to display the file upload error here.
This is my controller that handle file upload when not uploading:
if ( ! $this->upload->do_upload('file')){
$response_array = array ('upl_error' => $this->upload->display_errors());
echo json_encode($response_array);
//return false;
}

You need to send a flag to specify if file uploaded successfully or not to do this send a success flag from your php code like this:
PHP CODE
if ( ! $this->upload->do_upload('file')){
// file not uploaded
$response_array = array ('success'=0,'upl_error' => $this->upload->display_errors('', ''));
echo json_encode($response_array);
}
else
{
// file uploaded
echo json_encode(array("success"=>1));
}
And then in your ajax success callback function you need to check that success flag like this
jQuery CODE
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
// if file upload success
if (data.success == 1) {
alert("File uploaed success");
}
// file not uploaded
else {
alert(data.upl_error);
}
}
});
I hope it will help you.

In success function to check response content, or use http_response_code(500) in php script to trigger ajax error function.

The AJAX error alert only shows alert when AJAX is not working. This is working fine because, the case your file is not uploading is not an ajax error, its a normal code flow.
To handle it, you have to return some status to manage it in success of ajax like:
success: function(response)
{
if(response == 1)
{
// do some thing
}
else
{
// do some thing
}
}
PHP:
if( check here file uploads or not )
{
echo 1;
}
else
{
echo 0;
}

Related

JSON encode alert message

How do I alert a json_encode() message and reload the page? The function below only displays an undefined alert message
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
data = $.parseJSON(data);
alert(data.response);
location.reload();
}
});
});
You're trying to get a undefined index response
Provided that your PHP script returns:
{
"msg": "<your-message-here>"
}
In your javascript you can do it:
$.ajax({
type : "POST",
url: "transferProduct.php",
dataType: 'json',
success : function(response) {
alert(response.msg);
location.reload();
}
});
Use code in this way
transferProduct.php
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
code page
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
datas = $.parseJSON(data);
alert(datas.msg);
location.reload();
}
});
});
or you can use $.getJSON in place of $.ajax
$("#transfer").click(function() {
$.getJSON("transferProduct.php",function (data){
alert(data.msg);
location.reload();
});
});
I think you should format the return to correctly identify in the background:
{"success":true,"message":"---------"}
then in JavaScript: data.message

Sending PDF file to server (PHP LARAVEL) using AJAX

I am trying to upload a file (PDF) by AJAX to my server to be handled by a php script in a laravel project. I cannot get the file to send and be received on the server.
In the network I can see that the POST request is getting a 200 response, however it is returning a response of 'file not present', which is the response from laravel.
Also in the post request the Request Payload contains the following
------WebKitFormBoundaryliAmA3wxs0bB32iZ--
Please see the js and html and php below:
html
<form enctype="multipart/form-data">
<input type="file" id="cv" name="cv"/>
<button id="file-send">Add</button>
</form>
js
$('#file-send').bind('click', function () {
$.ajax({
url:"test",
data: new FormData($("#cv")[0]),
type:'POST',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
LARAVEL CODE
public static function uploadingFile(){
if (Input::hasFile('cv'))
{
return "file present";
}
else{
return "file not present";
}
Try this:
JS:
$('#file-send').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
Try This Plugin to upload file
http://malsup.com/jquery/form/#file-upload
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType :'json'
};
$('#file-send').ajaxSubmit(options);
function showRequest()
{
//before uploading file
}
function showResponse()
{
//response after uploading file
}

how can I access the data that I just encoded using "_serialize" in Cakephp

I have this function in my UsersController. I created this JSON response by using the _serialize key:
public function test() {
$arrEmail = $this->User->find('first');
$this->set('foo', $arrEmail);
$this->set('_serialize', array('foo') );
}
Now in the client side, in my phonegap application, I am trying to access this data. So I put the following:
<script>
$( document ).ready(function() {
alert(1);
$.ajax({
url : "http://localhost/database/users/" + 'test.json',
async : false,
cache : false,
crossDomain: true,
dataType : 'json',
type : 'post',
success : function(result) {
alert('success');
alert(JSON.stringify(result));
},
error : function(xhr, status, err) {
//con failed
alert(err+' '+xhr+' '+status);
}
});
});
</script>
The alert gives me the following .
Now I need to access to the username and the other attributes. I tried result.attributename but i always get undefined as a response.
EDIT:
`result.foo.User.id` solved the issue.

How to receive a ajax callback in ajax post

I am using AJAX with my CodeIgniter application.
I've manged to make a "Ajax checkbox", so when I click on my checkbox, in background specific function is called.
But how to make a callback, I mean I would like to know if the operation was done ok, or maybe it was any problem/error.
My HTML:
<input type="checkbox" onClick="change_parameter(<?=$dane_leada['lead_id']?>, 'my_parameter');" >
JS:
function change_parameter(lead_id, parametr)
{
$.ajax({
type : "POST",
url : '<?=base_url();?>leads/change_parametr/' + lead_id,
data : "lead_id=" + lead_id,
data : "parameter=" + parameter,
});
alert("Status changed"); //here should be message "ok" or "error"
}
PHP in Controller:
public function change_parameter($lead_id, $parametr=FALSE)
{
if ($lead_id != "" AND isset($_POST['parameter']))
{
$parameter = $_POST['parameter']; //odczytujemy zmienną wysłaną przez AJAXa
}
if ($data['dane_leada'][$parameter] == '0') $new_parameter = 1; else $new_parameter = 0;
$dane = array(
'lead_id' => $lead_id,
$parameter => $new_parameter,
);
$this->model_leady->mofify_lead($lead_id, $dane);
// return error or confirm
}
Update the script with this:
function change_parameter(lead_id, parametr)
{
$.ajax({
type : "POST",
url : '<?=base_url();?>leads/change_parametr/' + lead_id,
data : {lead_id : lead_id,parameter :parameter},
success: function(response){
if(response){
alert("Status changed"); //here should be message "ok" or "error"
}else{
alert("ERROR :Something Wrong");
}
},
error: function (err) {
alert("ERROR :Something Wrong");
});
});
}
Or You can add error handler.
error: function (err) {
alert("ERROR :" + err.status);
}

AJAX "success" not called

All of this worked before, I haven't changed anything and now it doesn't. I have two elements named with id="live_title" and id="live_game". AJAX purpose is to update them.
My jQuery:
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
for (var prop in data) {
$('#live_'+prop).html(data[prop]);
}
}
});
}
setInterval( tytul, 10000 );
AJAX response as seen in Firebug:
{"title":"Some title title...","game":"Name of the game"}
PHP Code sending stuff:
header('Content-Type: application/json');
// creating assoc array here
echo json_encode(array( 'title' => $title, 'game' => $game));
JavaScript console is empty.
When I visit ajax/getTitle.php in my browser, there is no error and displayed is the same thing as normally in Firebug. Response gives correct header (it's "Content-Type: application/json").
I've added
error : function(data) {
alert(data);
}
To my .ajax() function. It pops [object Object]. for alert(data.title) or alert(data['title']) it's undefined
Try to console your ajax response first and then step forward to further operations
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
//if successfull
console.log(data);
},
error:function(data){
//if error
console.log(data);
}
});
}
setInterval( tytul, 10000 );

Categories