Ajax doesn't get a success response back after file upload - javascript

I just started with Ajax and also tried to find a solution for this.
Here is the problem:
I upload a .csv to a server. This works just fine. But after the upload "success" in the ajax call won't respond. Neither does complete or error. It shows nothing. Not even an empty alert. Just nothing. I also didn't find anything in the logs.
When I click the upload button without chosing a file to upload I get a response from success...
Here is the code:
upload.php
<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
{
//$response['message'] = "File was uploaded!";
$response['message'] = csvToJson($target_file);
}
else
{
$response['message'] = 'Sorry, there was an error uploading your file.';
}
echo json_encode($response);
function csvToJson($file)
{
// open csv file
if (!($fp = fopen($file, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",";");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",";")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
// encode array to json
return $json;
}
?>
upload.js
$(document).ready(function(e)
{
// Submit form data via Ajax
$("#form").on('submit', function(e)
{
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(response)
{
//var json = $.parseJSON(response)
alert(response);
},
error: function(error){
console.log("Error:");
console.log(error);
},
complete: function(response){
alert(response);
}
});
});
});
the form in index.php
<form id=form enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload Excel" name="submit">
</form>
In the end I want a json back with the content of the uploaded file. But right now there is zero output if the file is uploaded.
Thanks for any advice!
EDIT for Solution:
The problem was something way different.
I had to format the output from csvToJson to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}

Solution, but cannot mark it:
The problem was something way different. I had to format the output from csvToJson() in upload.php to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}

Related

How do I get a value that is returned by a php script in Ajax?

I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<!DOCTYPE html>
<html>
<style>
.table_class{
display:none;
}
</style>
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
console.log(formData);
await fetch('file_ingest.php', {
method: "POST",
body: formData,
});
var test = document.getElementById("test");
test.innerText = ('The file has been uploaded successfully.');
//var returned_vals = JSON.parse(formData.responseText);
//console.log(returned_vals);
}
</script>
<body>
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<p id = "test"></p>
</body>
</html>
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<?php
set_time_limit(120);
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
$CSVfp = fopen("uploads/${filename}", "r");
if($CSVfp !== FALSE) {
while(! feoF($CSVfp)) {
$data = fgetcsv ($CSVfp, 1000, ",");
print json_encode($data);
//echo $data;
}
}
fclose($CSVfp);
<?php
set_time_limit(120); // if you need this you may have other problems
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
$response = [];
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
$response['status'] = 'Files Save Success';
// read the file here, if it failed the upload and move
// there is no point trying to read it
if (($fp = fopen($location, "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$response['data'][] = $data
}
fclose($fp);
}
} else {
$response['status'] = 'File Save Failure';
}
// now you can return either an error or a success and data
echo json_encode($response);
Now you need to checnge the javascript to look for the status in the right place and unload the row data from the the right place

json_encode prints data in html

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?
Try to send out the json http header in first place on product.php
header('Content-Type: application/json');

How to retrieve boolean value from php to javascript file

is that possible to retrieve Boolean value from php to javascript?
All I want to do is simple: Retrieve Boolean value from php variable $x into js
Should be true when emails are sent
And False when emails are not sent
Then take that Boolean value with javascript print the appropriate message
Complete code of my work can be found here, on my other case I had opened yesterday
PHP:
if (!$mail->send()) {
$x = false; //when email is not sent
} else {
$x = true; //when email is sent
}
JS Pseudocode
.done(function (data) {
if(php Boolean variable is false) {
("$formText").html("Message sent");
} else (if php Boolean variable is true) {
("$formText").html("Message not sent");
}
});
I am assuming you are already passing data (via AJAX) you just don't know how to encode it.
Use: json_encode()
PHP:
if (!$mail->send()) {
$x = true;
} else {
$x = false;
}
header("Content-type: application/json");
echo json_encode(array('x'=>$x));
Javascript:
.done(function (data) {
if (data.x) {
$("#formText").html("Message sent");
} else {
$("#formText").html("Message not sent");
}
} //end function data
);//end done function
While returning bool value from PHP code use json_encode(). It convert from native PHP types to native Javascript type.
http://php.net/manual/en/function.json-encode.php
using response code and handling them with done and fail
PHP
<?php
// ...
$success = '{"message": "your mail is send"}';
$error = '{"message": "failed sending mail"}';
$code;
$out;
if(mailSend){
$code = 200;
$out = $success;
} else {
$code = 400;
$out = $error;
}
http_response_code($code);
echo $out;
JS
// ...
var data = 'yourData';
$.ajax({
url: 'yourApiUrl'M,
data: data,
method: 'POST',
xhrFields: {withCredentials: true},
crossDomain: true,
dataType: 'json'
}).done(function() {
// mail was send
}).fail(function() {
// error on sending
});
a list of status codes you can find on https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

File upload by ajax $.post not working

I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.
HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_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(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

$.ajaxFileUpload successfully uploads file to a folder but wasn't able to pass values to be saved in the database

I have used ajaxfileupload upon form submission of my form. This is also for uploading purposes for image files. The image was successfully uploaded, however other data to be saved to database wasn't been included? Because it leaves my table fields blank, so I was thinking the values wasn't been passed to the category_save.php. I also observed that when I used the $.ajax({}) instead of $.ajaxFileUpload, the data were all successfully passed and saved in the database including the image file name but the actual file wasn't been uploaded at all. But when I used the $.ajaxFileUpload instead of $.ajax({}), it just work reverse, the file was uploaded but the values wasn't been saved in the database. What is the wrong with this? Here are my codes:
product_form.php
<form method="post" name="new_category" id="product_category" enctype="multipart/form-data">
<ul class="add_prod">
<li>Category Title:<input type="text" name="category[title]" id="cat_title" value="" placeholder="Title" /> </li>
<li>Category Description:<textarea rows="4" cols="40" name="category[description]"></textarea></li>
<li>Category Image:<input type="file" name="image_file" id="image_file" /></li>
</ul>
</form>
product1.js
$("#product_category").submit( function(){
event.preventDefault();
var data_category = $(this).serialize();
var image = $("#image_file").val();
$.ajaxFileUpload
(
{
type:"post",
url:"../wp-content/plugins/product_form/category_save.php",
secureuri:false,
fileElementId:'image_file',
dataType: "json",
data:data_category + "&image_file=" +image,
success: function (data)
{
if(data.notify == "Success"){
console.log(data.notify);
}
else{
return false;
}
}
}
);
});
product2.js
$("#product_category").submit( function(){
event.preventDefault();
var data_category = $(this).serialize();
var image = $("#image_file").val();
$.ajax({
type: "post",
url: "../wp-content/plugins/product_form/category_save.php",
dataType: "json",
data:data_category + "&image_file=" +image,
success: function(data){
if(data.notify == "Success"){
console.log(data.notify);
}
else{
console.log(data.notify);
}
}
});
});
category_save.php
<?php
//establish connection
$con = mysqli_connect("localhost","root","","ion2_emagi");
//on connection failure, throw an error
if(!$con) {
die('Could not connect: '.mysql_error());
}
$output_dir = "C:/Users/Employees/Dropbox/emagi/wp-content/plugins/product_form/img/";
$file_name = "image_file";
if(isset($_FILES[$file_name]))
{
//Filter the file types , if you want.
if ($_FILES[$file_name]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["image_file"]["tmp_name"],$output_dir. $_FILES["image_file"]["name"]);
}
}
//get the form elements and store them in variables
$category_values = $_POST["category"];
$image_url = basename($_POST["image_file"]);
$image_field = "image_url";
$data = array();
//unset($view_all_info['Password2']);
foreach($category_values as $field => $val){
$data[] = "`".$field."` = '".$val."'";
}
array_push($data,"`".$image_field."` = '".$image_url."'");
$sql = "INSERT INTO wp_product_category SET ".implode(',', $data);
$ret = mysqli_query($con,$sql);
if($ret){
$notification="Success";
}
else{
$notification="Failed";
}
echo json_encode(array('notify'=>$notification));
mysqli_close($con);
data field should have this format:
data: { data_category: data_category, image_file: image_file }
You are trying to pass it as a URL with parameters instead.
Then you have to retrieve it in PHP with POST by the name of the parameter. For example:
$category_values = $_POST["data_category"];

Categories