This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 6 years ago.
I have tried to convert my php code using php to javascript ajax. Could you please correct me what supposed to gone wrong since my php code is still activate.
html code:
<form method="post" enctype="multipart/form-data" action="testadd.php">
<input type="file" name="image" id="image">
<br/>
<input type="submit" name="submit" value="upload" id="submit">
</form>
php:
<?php
if(isset($_POST['submit'])){
if(getimagesize($_FILES['image']['tmp_name']) == false){
echo "Please select an image";
echo "<br/>";
}else{
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveImage($name, $image);
}
}
displayImage();
function saveImage($name, $image){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("INSERT INTO images(id, name, image) VALUES(38836929, '$name', '$image') ON DUPLICATE KEY UPDATE image='$image', name='$name'");
$stmt->execute();
}
function displayImage(){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("SELECT * FROM images");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_OBJ)){
echo '<img height="24" width="24" src="data:image;base64,' . $result->image . '">';
echo '<br/>';
echo $result->name . ' ';
}
}
?>
javascript:
$(document).ready(function(){
$("#submit").click(function(){
var image = document.getElementById("image").value;
alert(" " + image);
if(image == ""){
alert("please select image");
}else{
$.ajax({
type: "POST",
url: "testadd.php",
data: "image=" + image,
success: function(data){
if(data == success){
alert("test");
}else{
alert("fail");
}
}
});
}
return false;
});
});
Could you please check what supposed to be the problem in order to be fixed.
AJAX must have content Type , ProcessData to upload the image files
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});
Related
I'm having a problem with my Ajax. It seems to not be sending the data to my php file even though it worked properly 2 days ago. HTML:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button type='submit'>Comment</button>
</form>
My ajax code:
$('#comment').submit(function(event) {
var form = $(this);
var method = form.attr('method');
var url = form.attr('action');
info = {
comment: $('textarea').val()
};
console.log(method);
console.log(url);
console.log(info);
$.ajax({
type: method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I'm doing this for a friend and I'm using this exact same Ajax code (slightly modified) on my website and it's working flawlessly.
I think the biggest red flag here is that in my php file I have an if-else that should send an alert in case the textarea is empty but for some reason it's not doing that here even though nothing is getting through. I used console.log on all the variables to see if their values are correct and they are. The alert(data) just returns an empty alert box.
EDIT: As requested, PHP code from process.php
<?php
session_start();
include_once 'db_connection.php';
date_default_timezone_set('Europe/Zagreb');
if(isset($_POST['comment'])){
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
$conn -> query($sql);
$conn -> close();
}
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
SQLInsert($id, $date, $komentar, $conn);
} else {
echo '<script>';
echo 'alert("Comment box is empty.");';
echo '</script>';
}
?>
EDIT: Problem solved, thanks for the help everyone.
You are no getting alert because you are no displaying anything as response in php file. Add the insert function out side the if condition too
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
if($conn -> query($sql)){
return true;
}else{
return false;
}
$conn -> close();
}
if(isset($_POST['comment'])){
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
$insert = SQLInsert($id, $date, $komentar, $conn);
//On based on insert display the response. After that you will get alert message in ajax
if($insert){
echo 'insert sucess';
die;
}else{
echo 'Error Message';
die;
}
}
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button id="submit_button">Comment</button>
</form>
starting from this html you have to trigger your function as:
$("#submit_button").click(function(e){
I have added an id to your button for simplicity and removed the type because it is useless in this case.
If you want to catch the submit event of the form you have to change your html as:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<input type='submit'>Comment</button>
</form>
and then you can keep the same javascript
This here is the issue. Have you tried providing a "method" ?
$.ajax({
**type: method,**
method : method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
Also if this doesn't solve it. show me the console output
<form name="fileInfoForm" id='comment' method="post" enctype="multipart/form-data">
<textarea id="textarea"></textarea>
<button type="submit"></button>
</form>
<script type="text/javascript">
$('#comment').submit(function (e) {
e.preventDefault();
var textarea=$('#textarea').val();
var form=document.getElementById('comment');
var fd=new FormData(form);
fd.append('textarea',textarea);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'action.php',
data: fd,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data);
}
})
});
</script>
in action.php
$textarea= $_POST['textarea'];
echo $textarea;
I found a solution on internet on how to upload multiple files using ajax and php. In ajax request, I am passing form with files selected to upload, but I need to add one more parameter, but when I am doing it, it is not working. Im not good at php, and I tried pass second parameter in many ways but none worked. How can I pass second parameter so everything will be still working?
html:
<form method="post" enctype="multipart/form-data">
Select files to upload:
<input name="file[]" type="file" multiple>
<input type="button" onclick="upload(this)" value="Upload"/>
</form>
javascript:
function upload(element) {
var formData = new FormData($(element).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
success: function (callback) {
// some code
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
php
<?php
$mysqli = include 'connection.php';
$total = count($_FILES['file']['name']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
for ($i = 0; $i < $total; $i++) {
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
$location = 'uploads/';
$target_file = $location . basename($name);
if (isset($name)) {
if (empty($name)) {
echo 'Please choose a file' . "\n";
} else if (file_exists($target_file)) {
echo 'File already exists.' . "\n";
} else if ($size > 1000000) {
echo 'File is too large' . "\n";
} else {
$tmp_name = $_FILES['file']['tmp_name'][$i];
$statement = $mysqli->prepare("INSERT INTO files (name, subjectId) VALUES (?, ?)");
$str = '1'; // here I would like to set variable using $_POST
$statement->bind_param('ss', $name, $str);
if (move_uploaded_file($tmp_name, $location . $name)) {
if ($statement->execute()) {
echo 'File successfully uploaded :' . $location . $name . "\n";
} else {
echo 'Error while executing sql' . "\n";
}
} else {
echo 'Error while uploading file on server' . "\n";
}
}
}
}
}
So what I would like to get is in javascript add second parameter:
data: formData, mySecondParameter
and then in php when I am binding params for sql, I would like to input there variable that I passed from javascript:
$str = $_POST['contentOfMySecondParameter'];
You can use FormData.append() to add more parameters.
var formData = new FormData($(element).parents('form')[0]);
formData.append('mySecondParameter', contentOfMySecondParameter);
Then use $_POST['mySecondParameter'] in PHP to get this parameter.
Easiest way to do it, add
<input type='hidden' name='contentOfMySecondParameter' value='???' />
to html. You will get $_POST['contentOfMySecondParameter'] in php.
Only one object can be passed there. If you want another variable just append it to formData like this:
var formData = new FormData($(element).parents('form')[0]);
formData.append("mySecondParameter", mySecondParameter);
$.ajax({
...
data: formData,
...
So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";
So far I have HTML:
<div id="box" style="width:400; height:400; margin-left:auto; margin-right:auto; margin-top:100;">
<h2>Enter a word</h2>
<input type="text" id="input" ></input>
</div>
<div id="suggest">
</div>
Javascript:
<script type ="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
var input = $("#input").val();
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: "input"+input,
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
});
});
</script>
PHP:
<?php
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
$input = $_REQUEST['input'];
$input = mysql_real_escape_string(trim($input));
$sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";
$data = mysql_query($sql);
$arrcnt = -1;
$dataArray = array();
while ($temp = mysql_fetch_assoc($data))
{
foreach($temp as $key=>$val) {
$temp[$key] = stripslashes($val);
$arrcnt++;
}
$dataarray[$arrcnt] = $temp;
}
$list = "<ul style='width:100;height:auto;'>";
foreach($dataArray as $val) {
$list .= "<li>".$val['DesiredColumnContainingDesiredData']."</li>";
}
$list .= "</ul>";
echo $list;
?>
Now, these codes are supposed to work together to autocomplete the div with id="suggest" then populate the text field with id="input" when selected ... I keep getting alert that reads: <ul style='width:100;height:auto;'></ul>
change ajax code like this,
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: {"input":input},
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
The issue is because in php your variable name is different . You added $dataarray instead of $dataArray
Additionally for ajax
You can pass data as a string or as an object
data:{"input":input}
or
data:"input="+input
add type: 'POST' in ajax
I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});