PHP and AJAX: AJAX is working, PHP is not implementing query - php

Slowly but surely, I'm going to get AJAX. I've got a form that uploads a text field and a file to a database. I had the query working in PHP earlier, but not the AJAX. Now the AJAX is working but not the PHP. And I know that some will find it objectionable to load an image to a BLOB, but the query itself works, so I'd like to focus on the problems I'm having getting my javascript to talk to my PHP. I've researched the issue like crazy and tried a lot of things, but the thing I've come away with is that uploading files is complex.
Questions
1. Correct me if I'm wrong, but if javascript and jquery implement a "POST" call, the passed parameters shouldn't show up in the page's URL? Because they are.
2. Why is my PHP file not parsing out the sent data and sending it on to the database? I can see in the URL and in Firebug (although I'm slowly learning Firebug as well) that data is being passed. I ran a test php file and I am connecting with the database with that file.
Thanks!
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script src="jquery.validate.js"></script>
<script src="jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#addForm').validate();
function addRecord() {
$("#aTable").hide('slow', function () { //this is not working
alert('Working on it.');
});
$("#tableText").hide('slow', function() {//this is not working
alert('Working on it.');
});
var output = document.getElementById("message");
var nAname = document.getElementById("aname");
var nAInfo = new FormData(document.forms.namedItem("addForm"));
nAInfo.append('aname', nAname);
$.ajax({
type: "POST",
url: "addPhoto.php",
data: nAInfo
});
});
</script>
</head>
<body>
<form id="addForm" name="addForm" onsubmit="addRecord()" enctype="multipart/form-data">
<label>Name: </label>
<input type="text" id="aname" name="aname" class=required/>
<br>
<br>
<label>Photo: </label>
<input type="file" id="aimage" name="aimage" class="required">
<br>
<br>
<input type="submit" value="ADD" />
<br>
</form>
<div id="message" name="message"></div>
<br>
<br>
<div id="image_display"></div>
</body>
</html>
PHP
<?php
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
error_reporting(E_ALL);
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $_SERVER['REQUEST_METHOD'];
$aname = $_POST['aname'];
$errorinfo = $_FILES["aimage"]["error"];
$filename = $_FILES["aimage"]["name"];
$tmpfile = $_FILES["aimage"]["tmp_name"];
$filesize = $_FILES["aimage"]["size"];
$filetype = $_FILES["aimage"]["type"];
$fp = fopen($tmpfile, 'r');
$imgContent = fread($fp, filesize($tmpfile));
fclose($fp);
if (!($filetype == "image/jpeg" && $filesize > 0)) {
echo "Import of photo failed";
}
if ($filetype == "image/jpeg" && $filesize > 0 && $filesize < 1048576) {
if (!($stmt=$mysqli->prepare("INSERT INTO actor_info (aname, aimage_data) VALUES (?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ")" . $mysqli->error;
}
if (!$stmt->bind_param("ss", $aname, $imgContent)) {
echo "Binding parameters failed: (" . $stmt->errno .") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->close();
}
else {
echo "Image must be under 1 MB";
}
echo mysqli_error();
mysqli_close($mysqli);
?>

$("#aTable").hide('slow', function () { //this is not working
alert('Working on it.');
});
$("#tableText").hide('slow', function() {//this is not working
alert('Working on it.');
});
The above code is not working because you don't have any elements with id '#aTable' or '#tableText' in your html code.
Try print_r($_POST) to see whether all the values get to server or not.
Also using JQuery's Ajax function will make your code easier...below is a sample
$.ajax({
url : $domain + "/index/email/" + "?" + $arguments, //add your args here...
cache : false,
beforeSend : function (){
alert('sending....');
},
complete : function($response, $status){
if ($status != "error" && $status != "timeout") {
if($response.responseText == "200"){
alert('done');
} else {
alert($response.responseText);
}
}
},
error : function ($responseObj){
alert("Something went wrong while processing your request.\n\nError => "
+ $responseObj.responseText);
}
});

Related

php image upload will not work

I have asked this question before I made changes to my code and my image upload is not working at all I have checked username password, and Root they are all correct. my code will not show any errors I dont know what to do anymore can someone please help me? I have changed my connection for security reasons
<?php
$con = mysqli_connect("localhost", "torcdesi_jone45", "password", "torcdesi_amazing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_image = 'INSERT INTO shirt_table (images3)
values( "' . $_FILES['file3']['name'] . '")';
?>
<?php
include("configur.php");
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file3"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file3"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("shirtimgs/" . $_FILES["file3"]["name"])) {
} else {
//move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file3"]["tmp_name"],"shirtimgs/" . $_FILES["file3"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into shirt_table";
if(mysqli_query($link, $query_image)) {
echo "Stored in: " . "shirtimgs/" . $_FILES["file3"]["name"];
} else {
echo'';
}
}
}
}
}
?>
As I stated in comments, your form is missing a proper enctype to handle files.
This I know, since I saw your other question that did not contain it in the form.
<form enctype="multipart/form-data" action="__URL__" method="POST">
As per the manual:
http://php.net/manual/en/features.file-upload.post-method.php

Having error in saving image link to the database using pdo [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
I want to do is make a image uploader system and send the image to upload folder and save the link to the database.
My problem is I got this to errors in my images.php can anyone help me with this please.
html:
<form method="post" enctype="multipart/form-data">
<img id="picture" data-src="#" /> <br />
<input type='file' name="image" id="imgInp" accept="image/*" /><br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>
script:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
var data = {};
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "images.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
</script>
images.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$image = addslashes(file_get_contents(#$_FILES['image']['tmp_name']));
$image_name = addslashes(#$_FILES['image']['name']);
$image_size = getimagesize(#$_FILES['image']['tmp_name']);
move_uploaded_file(#$_FILES["image"]["tmp_name"], "upload/" . #$_FILES["image"]["name"]);
$location = "upload/" . #$_FILES["image"]["name"];
$q = "INSERT INTO students( image ) VALUES( :image)";
$query = $dbc->prepare($q);
$query->bindParam(':image', $location);
$results = $query->execute();
?>
script for image upload:
<script type="text/javascript">
$(document).ready(function() {
var currentSrc = $('#picture').attr('src');
if(currentSrc==null || currentSrc==""){
$('#picture').attr('src','http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg');
$("#picture").on('click', function() {
$("#imgInp").trigger('click')}
)}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#picture').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
</script>
The simplest thing to get rid of the error messages is to actually place a conditional that checks if $_FILES has anything in it. But past that, unclear on the root cause of $FILES being empty. In my experience Ajax file uploading with a PHP receiver on the other side just doesn’t work consistently at best. Anyway, here is my version of your code with a conditional in place:
if (!empty($_FILES)) {
$image = addslashes(file_get_contents(#$_FILES['image']['tmp_name']));
$image_name = addslashes(#$_FILES['image']['name']);
$image_size = getimagesize(#$_FILES['image']['tmp_name']);
move_uploaded_file(#$_FILES["image"]["tmp_name"], "upload/" . #$_FILES["image"]["name"]);
$location = "upload/" . #$_FILES["image"]["name"];
$q = "INSERT INTO students( image ) VALUES( :image)";
$query = $dbc->prepare($q);
$query->bindParam(':image', $location);
$results = $query->execute();
}
Try this approach, it might look like too many if statement, but you need to have checks if you want solid code:
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
//PDO
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO students( image ) VALUES( :image)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':image', $full_path);
$results = $stmt->execute();
if($results){
echo "Insert successful!";
}else{
echo "Insert failed!";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
Few things I would like to point out:
# suppress error, you don't want that when you troubleshoot, even in
production, you still want to be aware of the error.
You should enable error reporting
You didn't check if php script receives the image upload.
The use of file_get_contents is unclear in this case
You don't make use of the $image* variables ? ....

Send data from form with ajax without redirect

It seems this should be a simple thing to do but something is still going wrong. I am using the code of the top answer on this page: jQuery Ajax POST example with PHP
When I submit the form, instead of passing that data to the upvote.php and having it edit the database accordingly, it redirects me to /upvote.php?bar=hfAb1he49kk. It is taking the data that I need & redirecting to the php page and adding the data the url. Why is it doing that?
PHP
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM videos ORDER BY votes DESC");
while($row = mysqli_fetch_array($result)) {
echo "<div class='entry'>";
$id = $row['id'];
echo "<form action='upvote.php'>
<input type='hidden' name='bar' id='bar' value='" . $id . "' />
<input type='submit' value='upvote'/>
</form>";
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . stripslashes($row['id']) . '" frameborder="0" allowfullscreen></iframe>';
echo $row['votes'];
echo "</div>";
}
?>
JQuery
<script>
var request;
// bind to the submit event of our form
$(form).submit(function(event){
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/upvote.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
upvote.php
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bar = $_POST['bar'];
mysqli_query($con,"UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'");
mysqli_close($con);
?>
function postData(event){
event.preventDefault()
$.ajax({
type: "POST",
url: "yourfile.php",
data: $('#myForm').serialize()
}).done(function( result ) {
// do something
});
}
<form id="myForm">
<input type="submit" onclick="postData(event)" value="submit">
In a php file
$bar = $_POST['bar'];
$query = "UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'";
echo $query; //will echo you query to the done function of the ajax
exit();
mysqli_query($con,$query);
mysqli_close($con);
maybe add
event.preventDefault();
to prevent the form action
$("#foo").submit(function(event){
event.preventDefault();
Seb

File upload input from AJAX retrieved file not being detected

I made a dynamically changing HTML form where I can change the type of input of the form between a file upload or a drop down box that is populated from a remote database. The function that calls which input type to be displayed is in AJAX. When I submit the form using the drop down box, the form submits without any problems and performs the update to the database that I programmed it to do. However, when I try to submit the form while trying to upload the file, my error checking script (which are simple if... statements) tells me that it BOTH doesn't detect any file being uploaded and the file already exists on the database. However, when the "already exists on database" error appears, it doesn't return the name of the file that I'm trying to upload like I programmed it to do, so I suspect that my file isn't being submitted properly.
Can someone tell me what I did wrong?
Here's the script I have so far:
File 1: test.php
<html>
<body>
<head>
<script>
function getInput(value)
{
var xmlhttp;
if (value=="")
{
document.getElementById("display").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("display").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","grabtest.php?q="+value,true);
xmlhttp.send();
}
</script>
<?php
// connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
// if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
</head>
<form enctype="multipart/form-data" action="test2.php" method="POST">
<select id='SelectInput' onchange='getInput(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New File</option>
<option value='E'>Existing File</option>
</select>
<div id="display"></div><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($_POST)){
if ($_FILES["file"]["error"] == 0){
$target = 'PathName/TargetFolder/';
$target = $target . basename($FILES['file']['name']);
if (file_exists('PathName/TargetFolder/' . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists on server. ";
}
else{
$upload = $_FILES["file"]["name"];
$select = mysqli_query($con, "Select Files from DB_Table where Files = '$upload'");
if (mysqli_num_rows($select) > 0){
echo $_FILES["file"]["name"] . " already exists in database. ";
}
else{
//script for moving the uploaded file to the proper storage location on the server and adding it to the database
move_uploaded_file($_FILES["file"]["tmp_name"], $target . $_FILES["file"]["name"]);
echo "Stored in: " . $target . $_FILES["file"]["name"] . "<br>";
$insert="INSERT INTO DB_Table (Files) VALUES ('$upload')";
if (!mysqli_query($con,$insert)){
die('Error: ' . mysqli_error($con));
}
echo "Your data has been added to the database";
}
}
if ($_POST['recipe']=="" and !file_exists($_FILES['file']['tmp_name']) and !is_uploaded_file($_FILES['file']['tmp_name'])){
exit("Please select or add the file.");
}
}
mysqli_close($con);
?>
File 2: grabtest.php
<?php
//connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q=$_GET["q"];
if ($q==""){
echo "";
}
elseif ($q=="N"){
echo "Select recipe to upload: <input type='file' name='newfile'>";
}
elseif ($q=="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from DB_Table");
echo 'Files: <select name = "Files">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Files"] . '</option>';
}
echo '</select><br>';
echo '</form>';
}
//after script is executed, close connection to database
//this improves security by ensuring the connection to the database does not remain open when there is no activity being done to change the data
mysqli_close($con);
?>

Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.

Categories