ajax running error despite response being 200 - javascript

I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?

Related

Calling API | JavaScript to php | How to know if Response != 200, Print Error

Good day!
What I want to achieve is when user clicks the link, it will pass the parameter to javascript, which then using ajax to call the php file where my API is. The API will process the parameter and return a json result.
My code works when the parameter values are given correctly. However I'm stuck at the part where the values are incorrect/invalid and I need to catch the error.
The API document says that if the RESPONSE is 200, then it's a success. Else there is error. My issue is I have no idea how to get this "RESPONSE == 200". Any advise is appreciated!
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
if(res!=200)
{
alert("Invalid Wallet Address!");
}
else
{
alert(res);
}
}
});// ajax
} //end callMS_API
merklescienceAPI.php
<?php
$addr=$_POST['WalAddr']; //Wallet Addr
$cur=$_POST['CryCur']; //Cryptocurrency
$cur_code;
$result = "";
switch ($cur) {
case "Bitcoin":
$cur_code = 0;
break;
case "Ethereum":
$cur_code = 1;
break;
case "LiteCoin":
$cur_code = 2;
break;
case "Tether USD":
$cur_code = 10;
break;
}
require_once('../vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nAddress Risk Level : " . $data->risk_level_verbose;
//Whatever you echo will go to javascript success: function(res), and you can do alert(res)
echo $result;
?>
====================================================================
Edit + Solution
I read and tested further on the Guzzle thingy, and came across this thread. I implemented the Try Catch in the API.php and got my result.
Javascript function
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
alert(res);
}
});//ajax
} //end callMS_API
API.php
try{
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
}catch(Exception $e){
$error = true;
}
if($error == false)
{
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nRisk Level : " . $data->risk_level . " - " . $data->risk_level_verbose;
}else
{
$result = "Invalid Wallet Address!";
}
echo $result;
Thank you everyone for your help!
If you mean status code or HTTP status code 200 you could try add this line to your ajax option:
...
$.ajax({
...
statusCode: {
200: function() {
alert( "200 reaced" );
},
error: function(response) {
if(response.status != 200)
alert(" status code is " + response.status);
}
...
in Ajax
$.ajax({type:'POST',
url:'somefile.php',
data:{
a name:"a value"
} ,
success: <<THIS EXECUTES WITH A 200 RESPONSE>>,
error: <<THIS EXECUTES IF IT GOES BAD>>
});
The success: runs ONLY if the response is 200. for everything else you capture it with error:

Unable to download file in laravel ajax on button click

When I am trying to use the download button to download file in laravel ajax, it is not working properly and I am not able to download file.
Below is my code:
<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';
Controller:
public function downloadReport(Request $request)
{
$request_id = $request->request_id;
$downloadReport = Upload::where('id', $request_id)->first();
$upload_report = $downloadReport->upload_report;
$headers = array(
'Content-Type: application/pdf',
'Content-Type: application/docx',
);
$url= url('storage/documents/request/'. $upload_report);
return response()->download($url);
}
Ajax:
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
}
});
});
Just to pseudo-code it up with trusting your data is coming back as desired I think you need to trigger the download in your success callback with a variation of the following (may need to adjust to your need):
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
const data = res;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
link.click();
}
});
});
you can pass header to force file type and download
$file_path = storage_path('documents/request/'. $upload_report);
$headers = array('Content-Type'=> 'application/pdf');
return \Response::download($file_path, 'file.pdf', $headers);
here you need to add header based on your file type
ref link https://laravel.com/docs/8.x/responses#file-downloads
if(!empty($fileName) && file_exists(($exportDir.'/'.$fileName))) {
$data = route('yourdownloadCSV',['nameFile' => $fileName]);
}
return response()->json([
'status' => 1,
'data' => $data,
'message'=> trans('messages.item_upload_shop_ok'),
]);
public function yourdownloadCSV($nameFile) {
ini_set('memory_limit', '9072M');
ini_set('MAX_EXECUTION_TIME', '-1');
set_time_limit(10*60);
$fullFolderZipFile = public_path().'/export/'.date('ym');
$filePath = $fullFolderZipFile.'/'.$nameFile;
$nameDownload = "test";
if(file_exists($filePath)) {
$byteS = filesize($filePath);
$mb = number_format($byteS / 1048576, 2) ;
if($mb>10){
$filePathZip= ZipUtil::generateZipFromFile($filePath,$fullFolderZipFile,$nameFile);
$nameDownload .=".zip";
}else{
$filePathZip = $filePath;
$nameDownload .=".".pathinfo($nameFile, PATHINFO_EXTENSION);
}
$mimeType = File::mimeType($filePathZip);
return response()->download($filePathZip,$nameDownload,[
'Content-Type' => $mimeType,
'Content-Encoding' => 'Shift-JIS'
])->deleteFileAfterSend(true);
}
return '';
}

Not able to display the JSON success output in the view or alert

I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}

Get Content of ng-file-upload POST DATA

I am using ng-file-upload from Github. I have successfully uploaded and added image on both target folder and database. However, I need a specific data from my client side that will be needed for my query.
Controller.js ---- sample snippet of my upload function.
$scope.upload = function (dataUrl, name) {
Upload.upload({
url: 'php/profile-pic.php',
method: 'POST',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Process-Data' : false
},
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
id: user[0].id
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
console.log(response);
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
console.log(response);
}, function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
PHP ---- relative code on my server side
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
// $id = $data->id;
echo json_encode($data) // returns null
if(!empty($_FILES))
{
$filename = $_FILES['file']['name'];
$destination = '/../images/' . $filename;
if(move_uploaded_file( $_FILES['file']['tmp_name'] , PATH . $destination ))
{
$insertQuery = "UPDATE tblusers SET image = ".$_FILES['file']['name']." WHERE id='???'"; // ??? = the specific data that I need
Image ---- from console.log response
The id is what I need to get for my query.
How can I get that? file_get_contents not working for this one, it returns null.
I got the answer I am looking for.
In my upload function in my controller, I changed the key id into 'id' with apostrophe:
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
'id': user[0].id
}
In my php code, I did this:
$id = $_POST['id'];
I got the idea from Github Repo Issues at the last part of the page.

Uncaught error:Cannot use 'in' operator to search for 'length' in

When I trying to return the inserted image as json I'm getting error like Cannot use in operator to search for length
Ajax code:
$("#imagesform").submit(function(){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content')
}
});
$.ajax({
url :"{{url('addImages/').'/'}}" + imagesProductId,
type: 'POST',
data:new FormData($("#imagesform").get(0)),
contentType:false,
processData:false,
success: function (data)
{
//alert(data);
//alert(json.parse(data));
$.each(data, function( index, value ) {
$("#insertedImages").append('<img src="'+value+'" width="75"
height="75" class="upload2"><br>');
alert(value);
});
},
});
return false;
});
Here the images get inserted into db.But while returning to the view and trying to display it with the div tag shows error..(specified above)
Controller:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images'=>'required'
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
// echo($result);
foreach ($request->images as $photo) {
$filename = $photo->store('public/uploadedImages');
$filename = substr($filename,22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId'=>$imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filename);
}
This is my controller function for inserting array of images and I'm returning the same to the view and trying to append it using div tag.

Categories