Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am working with an ajax PHP upload, the upload works well without ajax jQuery. I went to Google to find more resources on it and adjusted my code several times but still get the same error at the backend that file is empty. This is my code.
At the frontend
<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>
My jQuery code
$(function(){
$("#chatsCard").on('click', '#sendImg', function (e){
e.preventDefault();
//alert("test");
var filedata = $("#file").prop("files")[0];
var recipient = $("#uname").html();
//alert(filedata);
$.ajax({
type:'post',
url:'upload.php',
contentType:false,
processData:false,
cache:false,
dataType:'json',
data:{
//rec:recipient,
filedata
},
success:function(data){
alert (data);
}
});//ajax end
});//click end
});//doc end
Backend
<?php
session_start();
require("assets/db.php");
$logged = $_SESSION['logged'];
//This is always my ajax response.
if(empty($_FILES['file'])){
$response = "No picture selected";
echo json_encode($response);
exit;
}
$imgFolder = "media/";
$fileTpath = $_FILES['file']['tmp_name'];
$fileSize = filesize($fileTpath);
$info = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($info, $fileTpath);
$filetype = explode ("/",$filetype);
$filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");
//rename image.
$newName = uniqid(8);
$newName = "recipient".
$newName. "." . $filetype;
//check file size
if($fileSize > 21464568){
$response = "Picture is greater than 2MB, Resize and try again";
echo json_encode($response);
exit;
}
//check format.
elseif(!in_array($filetype, $allowedFiles)){
$response= "You are only allowed to upload jpeg,jpg or png";
echo json_encode($response);
exit;
}
//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
$response = "Failed!!! Upload again!!!";
echo json_encode($response);
exit;
}
//move to folder.
else{
move_uploaded_file($fileTpath,$imgFolder .$newName);
$recipient = $_POST['rec'];
$time = date("d-M-y")." at ". date("h:ia");
$msg = "media";
//insert to messaging
$q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
$stm = $conn->prepare ($q);
$stm->bind_param("ssss",$msg,$logged,$recipient,$time);
$stm->execute();
//insert media details
$q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
$stm = $conn->prepare ($q1);
$stm->bind_param("sss",$logged,$newName,$fileType);
$stm->execute();
//json response
$response = "success";
echo json_encode($response);
exit;
}
?>
Since I removed the jQuery and the uploading works normally, I assumed the problem is not from the backend so I focused on the jQuery by tweaking it to these
//First change
var fd = new FormData();
var file = $("#file").props('files')[0];
var file data= fd.append("file",filedata);
//This still gives no picture selected.
//Second change
var fd = new FormData($("#mediaPic")[0])
//Passed fd as data but still the same response.
//Tried other stuffs I got on Google to get the image data but still d same response.
You just need to post FormData() object, Append method returns null. Datatype text is preferred. So the final jQuery code would be:
$(function(){
$("#sendImg").on('click', function (e){
e.preventDefault();
//alert("test");
var recipient = $("#uname").html();
var form_data = new FormData();
var file = $("#file").prop('files')[0];
form_data.append('file', file);
$.ajax({
url: 'upload.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
alert(data);
}
});//ajax end
});//click end
});//doc end
To add additional value with form_data, simple use before submitting
form_data.append("rec", "value");
Related
Hi Guys!
Im having isusses with my wordpress plugin. Im trying to upload a file through a form.
The problem is that I can't store my type="file" in the database.
I have some other functions where I put values like text inside my database without any problems.
I dont know if im supposed to change the custom.js function file or what to do...
Can u guys help me out?
thx for helping.
This is my Index.php
<form id="frmCreateFile" class="form-horizontal" action="javascript:void(0)" method="post"
enctype="multipart/form-data">
Select Image File to Upload:
<input id="file" type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
This is my Custom.js
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var postdata = jQuery("#frmCreateFile").serialize()+"&action=crm_request¶m=create_file";
jQuery.post(crm_ajax_url, postdata, function(response){
var data = jQuery.parseJSON(response);
location.reload();
})
}
});
This is my Function.php
global $wpdb;
$param = isset($_REQUEST['param']) ? $_REQUEST['param'] : "";
if(!empty($param) && $param=='create_file'){
$customerId = '358';
// File upload path
$targetDir = VEOSOFT_CRM_DIR . "/uploads/";
echo $targetDir;
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $wpdb->query("INSERT into wpwh_veosoft_crm_file (fileName, uploadDate, customer_Id) VALUES ('".$fileName."', NOW(),$customerId)");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
After clicking on submit my database is inserting a new row in my table with this value:
Id = 51
FileName = (empty)
Date = 2019-12-17
You cannot upload file using normal Ajax or in key value pairs. Files are uploaded using Multipart data.
Please try following Javascript
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
url: crm_ajax_url,
type: 'post',
data: fd+"&action=crm_request¶m=create_file",
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
}
});
}
});
We can generate and save locally a page as pdf with window.print(), but I want to know if I can save a page as pdf in a variable, exactly like window.print() generates a pdf, because I want to send it through ajax after. Thanks.
As i can understand your exact need this can be of your help.
HTML
<button onclick="document.getElementById('opepdf').click();">Read PDF</button>
<input id="opepdf" type="file" name="name" style="display: none;" onchange="PDFReader(event);"/>
Javascript
function PDFReader(e){
var file = e.target.files[0];
var pdfReader = new FileReader();// Create a File Reader
pdfReader.readAsText(file,'UTF-8');
pdfReader.onload = readerEvent => {
var PDFContent = readerEvent.target.result;
console.log( PDFContent );//PDF content in variable
}
}
Don't know if this cross browser or not but it does not need any js plugin.
More elaborate explanation about how you will be using this can improve the answers.
If you want to upload a file through ajax you can use other ways.
EDIT:
If you want to send PDF through ajax to your server use:
HTML:
<form>
Select PDF
<input id="opepdf" name="opepdf" type="file" /><br>
<div id="upload"></div><br>
<input type="submit" value="submit"/>
</form>
JAVA-SCRIPT: need jquery
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
$("#upload").html("<img src='http://crabsheet.com/cs/wp-content/uploads/2012/08/capture-1.gif'>");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
$("#upload").html(response);
}
});
return false;
});
PHP-Serverside: there should be a "uploads" folder relative to script dir
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["opepdf"]["name"]);
$fileName = $_FILES['opepdf']['name'];
$fileType = $_FILES['opepdf']['type'];
$fileError = $_FILES['opepdf']['error'];
$fileContent = file_get_contents($_FILES['opepdf']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
if (move_uploaded_file($_FILES["opepdf"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["opepdf"]["name"]). " has been uploaded.";
} else {
echo "Error uploading your file.";
}
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'MAX UPLOAD SIZE Reached';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'MAX FORM Upload Size Reached';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Could not finish Upload';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'NO upload File';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Servernot configured for file upload';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'CANT WRITE';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Could not finish Upload.';
break;
default: $message = 'Could not finish Upload';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
?>
You know you can save a web page as pdf with window.print() so you want to catch the output of window.print() as var in javascript. But that's not your goal, right? Your end goal is to save your Html page as a pdf and send it through ajax. So you need to ask, is there any other way to save my Html page as pdf besides using window.print()? Now you are on the right track. To convert Html to pdf, you can use jsPDF's .html() PlugIn and html2canvas 1.0.0-alpha.12.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="~/lib/html2canvas/html2canvas.min.js"></script></script>
<!-- html2canvas 1.0.0-alpha.11 up to v1.0.0-rc.1 works, current version may not work -->
<script>
function emailHtml() {
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.body, {
callback: function () {
let obj = {};
obj.pdfContent = pdf.output('datauristring');
var jsonData = JSON.stringify(obj);
$.ajax({
url: '/api/yourapi',
type: 'POST',
contentType: 'application/json',
data: jsonData
});
}
});
}
</script>
You cannot get a value from window.print().
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
This one has really been melting my brain because I'm just not sure why the PHP returns a null set to the front end when it's formatted like this:
<?php
require_once 'tempdbconfig.php';
$email=$_POST['email'];
try {
//if($email = "t*****#gmail.com"){
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql="SELECT users_id FROM photow_users WHERE email_address = '$email'";
$result = $conn->prepare($sql);
$result->execute();
$data = $result->fetchAll();
$catValues = array();
foreach($data as $row) {
$users_id=$row['users_id'];
$category_sql="SELECT * FROM photow_categories WHERE users_id = '$users_id'";
$category_result = $conn->prepare($category_sql);
$category_result->execute();
$category_data = $category_result->fetchAll();
$catValues = array();
$i = 0;
foreach($category_data as $category_row) {
$categories = array();
$categoryid = $category_row['category_id'];
$category = $category_row['name'];
$categories["ID"] = $categoryid;
$categories["Category"] = $category;
$catValues[$i]=$categories;
$i++;
}
}
echo json_encode($catValues);
//}
//else
//{
// echo 'no categories';
//}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
But if I uncomment the if else (the condition is the email that my currently logged in account on the front end is using, so it's akin to me asking if the sky is blue) I get the properly formatted JSON returned to the front end. Am I missing something about PHP or have I made a horrible mistake somewhere?
This is the ajax call in case it's something there that's effecting it - localstorage does contain the correct email address by the way.
var email=localStorage.email;
$.ajax({
type: "POST",
url: "http://w****.azurewebsites.net/getCategoriesjson.php",
data: 'email='+email,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
var html = '';
$.each(data, function(index,value){
html+= '<option value="'+value['ID']+'">'+value['Category']+'</option>';
});
$('#categories').html(html);
}
});
your if miss a "="
use == instead of =
if($email = "t*****#gmail.com")
this means $email always have the value "t*****#gmail.com",
use == instead
I know u doesnt need this check, this is not what you want,try these changes,
change
$email=$_POST['email']; to
$email=$_REQUEST['email'];
And in ajax section
change
data:'email='+email to
data:{email:email}
you must compare values in if block.
Replace this line
//if($email = "t*****#gmail.com"){
with this
//if($email == "t*****#gmail.com"){
Change your ajax data to
data: { email: email },
Also change assignment = operator to compare == operator
if($email == "t*****#gmail.com"){
.
.
.
.
}
else
{
echo 'no categories';
}
use localStorage.getItem.
Also data part of your ajax request should be an object.
And make sure to put the ajax request within document.ready
$(document).ready(function() {
var email = localStorage.getItem('email');
$.ajax({
type: "POST",
url: "http://w****.azurewebsites.net/getCategoriesjson.php",
data: {email: email },
contentType: "application/json",
dataType: "json",
success: function(data){
var html = '';
$.each(data, function(index,value){
html+= '<option value="'+value['ID']+'">'+value['Category']+'</option>';
});
$('#categories').html(html);
}
});
});
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']);
}
?>
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)