Javascript AJAX upload of BLOB image using php. $_FILES is empty - javascript

Hi I am trying to upload a BLOB image onto my localhost wampserver through AJAX using Javascript and PHP.
I am trying to obtain the image in $_FILES but for some reason $_FILES is empty. I have set enctype and checked php.ini for file_uploads = On.
Here is my html form:
<h1>CREATE A NEW ENTRY</h1>
<form name="insertForm" method="post" enctype="multipart/form-data">
Name: <input type="text" id="insert_name" /> <br />
Age: <input type="text" id="insert_age" /> <br />
WPM: <input type="text" id="insert_wpm" /> <br />
Sex: <select id="insert_sex">
<option>M</option>
<option>F</option>
</select><br />
Photo : <input type="file" name="photo" id="insert_photo" /> <br />
<input type="button" onClick="insertFunction()" value="UPDATE LIST" />
</form>
<br>
<br>
<div id="preview"><img id="preview_img" src="images/placeholder.png"/></div>
<div id="message"></div>
Here is the javascript that runs the AJAX :
function insertFunction()
{
var ajaxRequest = createAjaxObject(); // checks for browser type and returns corres. ajax object
var name = document.getElementById('insert_name').value;
var age = document.getElementById('insert_age').value;
var wpm = document.getElementById('insert_wpm').value;
var sex = document.getElementById('insert_sex').value;
var image = document.getElementById('insert_photo').files[0];
var imageType = image.type;
alert(imageType);
var match = ["image/jpeg", "image/png", "image/jpg"]
if (!((imageType==match[0]) || (imageType==match[1]) || (imageType==match[2])))
{
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="images/noimage.png"/ alt="../images/noimage.png">';
document.getElementById("message").innerHTML = "<p class='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>";
}
else
{
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="' + e.target.result + '" alt="' + e.target.result + '">';
};
reader.readAsDataURL(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + image;
ajaxRequest.open("POST", "insert-example.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dataString);
document.getElementById('insertDiv').innerHTML = "processing...";
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4)
{
var insertDiv = document.getElementById('insertDiv');
insertDiv.innerHTML = ajaxRequest.responseText;
}
}
}
}
And here is the php that updates the localhost.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "ajaxtutorial";
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
echo "Connection failed: %s" . mysqli_connect_error();
}
mysqli_connect($dbhost, $dbuser, $dbpassword) or die(mysql_error());
mysqli_select_db($link, $dbname) or die("Cannot connect to database");
$name = mysqli_real_escape_string($link, $_POST['name']);
$age = mysqli_real_escape_string($link, $_POST['age']);
$wpm = mysqli_real_escape_string($link, $_POST['wpm']);
$sex = mysqli_real_escape_string($link, $_POST['sex']);
// Image file code below
if (false)
{
$photo = $_FILES["photo"];
echo $photo;
}
else
{
echo var_dump($_FILES);
}
}
?>
The output I get from the var_dump is :
array (size=0)
empty
Could someone please tell me what is going wrong with my code?

Try to use jQuery, way more simple: (so replace everything in your js file with this script and keep the HTML and PHP)
$.ajax({
type: 'post',
url: 'update.php', //php script
data: new FormData($('form')[0]), //form data
processData: false,
contentType: false,
success: function (result) {
//do something cool when it is succesfully updated
});
PS: don't forget to include this BEFORE the script because it is jQuery: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js">

try this
var imageData = new FormData(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + imageData;
Sending files using a FormData object

Related

JQuery Autocomplete's source from db using json

I'm trying to make jquery autocomplete input field with source from database, and the data is stored in json. I stored all data I got in one variable, it's look like this :
and when I set source to be value of that sinput field, I got the whole sentece (which is expect from my example)..but now I know to have three words (first - skijanje, second - vodopoad, third - more) so to have three options in my autocomplete. Here is my code for getting data using php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($output);
Here is js code for reading that data :
<script>
var obj, dbParam, xmlhttp,x , txt = "";
var i = 0;
obj = { "table":"tourplan" };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "All data: " + this.responseText;
var myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].title +" ";
}
document.getElementById("demo2").value = txt;
//document.getElementById("demo2").innerHTML = "Only one field: " + myObj[1].title;
}
}
xmlhttp.open("GET", "tourTitle.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<p id="demo"></p>
<input type="text" id="demo2" value="">
for document.getElementByID('demo').innerHTML = "All data: " + this.responseText; I got this:
All data: [{"title":"skijanje","type":"zima"},{"title":"vodopad","type":"jesen - proljece - ljeto"},{"title":"more","type":"ljeto"}]
and here is for making autocomplete:
<script>
$( function() {
var otherPlaces = [
txt
];
$("#search-loged").autocomplete({
source: txt
});
});
</script>
ANy idea for correct that? thanks
Don't use pure ajax, try something like this:
jQuery Ajax
$( function() {
$("#search-loged").autocomplete({
source: 'tourTitle.php',
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
});
HTML
<p id="demo"></p>
<input type="text" id="demo2" value="" name='x'>
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
$response = array();
foreach($output as row){
$response[] = ["value"=>$row['title'],"label"=>$row['title']];
}
echo json_encode($response);

HTML textarea show br

i have a textarea in HTML. In the textarea the blank line is is looks br.
I try to have the value of the some text. And posting with get. After i received with php. And i changed the value of the some text to variabled i get with get.
Like this :
a<br />b c
Code (post with javascript):
<script type="text/javascript">
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function menusec(secilen){
var deger = secilen.options[secilen.selectedIndex].value;
var urunadi = document.getElementById("okulueua").value;
var urunfiyati = document.getElementById("okulueuf").value;
var kargofiyati = document.getElementById("okuluekf").value;
var aciklama = nl2br(document.getElementById("okulueat").value);
alert(aciklama);
window.location.href = "okulue.php?menu=" + deger + "&urunadi=" + urunadi + "&urunfiyati=" + urunfiyati + "&kargofiyati=" + kargofiyati + "&aciklama=" + aciklama;
}
</script>
Code (get with php) :
<?php
if (isset($_GET['menu'])) {
$secilendeger = filter_input(INPUT_GET, "menu");
$urunadiget = filter_input(INPUT_GET, "urunadi");
$urunfiyatiget = filter_input(INPUT_GET, "urunfiyati");
$kargofiyatiget = filter_input(INPUT_GET, "kargofiyati");
$aciklamaget = filter_input(INPUT_GET, "aciklama");
echo($aciklamaget);
?>
<script type="text/javascript">
function br2nl($content){
$content = str_ireplace("<br /> ", "\n", $content);
return $content;
}
function br2nl1($input){
return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);
}
document.getElementById("menusecme1").style.width = "315px";
document.getElementById("okulueua").value = "<?php echo($urunadiget); ?>";
document.getElementById("okulueuf").value = "<?php echo($urunfiyatiget); ?>";
document.getElementById("okuluekf").value = "<?php echo($kargofiyatiget); ?>";
document.getElementById("okulueat").value = "<?php echo($aciklamaget); ?>";
$('select[name^="ms1"] option[value="<?php echo($secilendeger); ?>"]').attr("selected","selected");
</script>
Code (HTML) :
<input type="text" class="okulueuat" name="okulueua" id="okulueua">
<input type="text" class="okulueua2t" name="okulueua2" value="1000" readonly="yes">
<input type="text" class="okulueuft" name="okulueuf" id="okulueuf">
<input type="text" class="okuluekft" name="okuluekf" value="5" id="okuluekf">
<input type="submit" class="tamamb2" value="Tamam" name="submit">
<input type="button" class="iptalb2" value="İptal" onclick="location='okulul.php'">
<input type="file" name="okuluef[]" class="resimeklec" multiple="multiple">
<textarea id="okulueat" name="okuluea"></textarea>
How can i solve this problem?
I need your help.
Note : I don't have a good English. Pardon me. I hope you understand.
Try this:
<textarea>a
b c</textarea>

Posting data without refresh + calling another jquery function

My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});

HTML replaced by php output in browser when multipart form data is submitted to mysql using MAMP

I am getting an unexpected response from my browser when I submit a file using multipart/form-data.
The php script triggered by the action executes perfectly but the file prints echoed statements on a white background to my browser and replaces my HTML.
If I comment out my echo statements I just get a white screen.
I would prefer the script to just run in the background and not override my HTML.
I am using a localhost with MAMP.
Any thoughts?
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>See Me</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="seeMe.css" rel="stylesheet">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="seeMe.js"></script>
<script type="text/javascript" src="compatibility.js"></script>
<div id="signInDiv">
<form id="sign_In_Form">
<div class="form-group">
<input type="text" name="username" class="form-control" id="usernameTextField" placeholder="Username" >
</div>
<div class="form-group">
<input type="text" name="password" class="form-control" id="passwordTextField" placeholder="Password" >
</div>
</form>
<button type="button" class="btn btn-success" onclick="signInUser(this)">Sign In</button>
</div>
</body>
</html>
My JS
var userSignedIn = 0;
var usernameString;
var picsArray;
function signInUser(id){
var u = $( "#usernameTextField").val();
var p = $( "#passwordTextField").val();
//query database for user data and check for match
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var foundUser = xmlhttp.responseText;
if (foundUser == "TRUE" ) {
usernameString = u;
userSignedIn = 1;
showGalleryPage();
}
else{
alert("Username and Password do not match");
}
}
else{
//alert("Could not connect to account. Try again later.");
}
};
xmlhttp.open("GET", "seeMeeSignIn.php?u=" + u + "&p=" + p, true);
xmlhttp.send();
}
function showGalleryPage (id) {
$( "div" ).remove();
alert("about to getPics");
getPics();
}
function getPics (id){
var u = usernameString;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
picsArray = $.parseJSON(xmlhttp.responseText);
var imgagesHTML = "";
for (var i = 0; i < picsArray.length; i++) {
imgagesHTML = imgagesHTML + '<img src=' + picsArray[i] + ' alt="Mountain View" style="width:100px;height:100px;">';
}
var showGalleryHtml;
showGalleryHtml = '<div id="galleryHeader">' +
'</div>' +
'<div id="thumbnailGalleryView">'+
imgagesHTML +
'</div>'+
'<div id="addPicButton">'+
'<form action="seeMeAddPic.php" method="post" enctype="multipart/form-data">'+
'<input type="file" name="file">'+
"<input type='hidden' name='username' value= "+ usernameString + '>'+
'<input type="submit" onclick="showGalleryPage(this)">'+
'</form>'+
'</div>'+
'<div id="picToDisplayLabel">'+
'</div>'+
'<div id="picToDisplay">'+
'</div>'+
'<div id="checkboxToRandomize">'+
'</div>';
var $jshowGalleryHtml = $(showGalleryHtml);
$("body").append($jshowGalleryHtml);
}
else{
//alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "seeMeGetPics.php?u=" + u, true);
xmlhttp.send();
}
My PHP
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "seemedb";
$db = new mysqli($servername, $username, $password, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$file = $_FILES['file'];
$name = $file['name'];
$user = $_POST['username'];
$path = "keepPicsHere/" . basename($name);
if (move_uploaded_file($file['tmp_name'], $path)) {
//echo "Move succeed";
} else {
//echo "Move failed. Possible duplicate?";
}
$sql = "INSERT INTO imageData (userSubmitting, imagePath) VALUES ('".$user."', '" . $path . "')";
if ($db->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $conn->error;
}
$db->close();
?>

Display a php cookie in html

I have set a cookie using php.
Here's my code:
<?php
include_once 'php/config.php';
session_start(); //starting the session for user profile page
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row==1)
{
$_SESSION['username'] = $username;
setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_SESSION['username'];
echo "SUCCESSFULLY LOGGEDIN...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
}
?>
I want display the 'username' cookie in html like Hi ""
.
Please Help.
Tried this javascript:
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
Use echo $_COOKIE['username']; instead of echo $_SESSION['username'];. It will echo out of the second reload of the page. (Why?)
<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</script>

Categories