Upload Image and insert in Database MySQl withAjax - php

i m user JQuery mobile and PHP and Ajax to upload Image and insert it in Database,but i have a probleme in insert the name of image in a database,the result in database is :"C:fakepathLighthouse.jpg",i would insert just the name of image after upload it.
Mu code in php
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
£fichier=basename($file['name'];
$uploaddir = 'photo/';
foreach($_FILES as $file)
{if(move_uploaded_file($file['tmp_name'], $uploaddir. $fichier)))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
my code script:
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
console.log('nom de l image:' + '&filenames[]=' + value);
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
my initial page(index.html)
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var latt = position.coords.latitude;
var lngg = position.coords.longitude;
var nom=$('input[id=nom]').val();
var photo= $('input[id=file_upload]').val();
var ville= $('input[id=ville]').val();
var pays= $('input[id=pays]').val();
long.value="Longitude: " + lngg;
lat.value="Latitude: " + latt;
//var adr="Sousse";
codeLatLng(latt, lngg);
// var adresse=codeLatLng(latt, lngg);
var sendAjax = $.ajax({
type: "POST",
url: 'api.php?rquest=insertMosque',
data: 'lat='+latt+'&lng='+lngg+'&nom='+nom+'&pays='+pays+'&ville='+ville+'&photo='+photo,
success: handleResponse
});
function handleResponse(){
$('#answer').get(0).innerHTML = sendAjax.responseText;
//console.log(data);
}
}
function errorFunction(){
alert("Geocoder failed");
}
}
code api.php
private function insertMosque() {
if ($this->get_request_method() != "POST") {
$this->response('', 406);
}
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
$photo=$_POST['photo'];
//$photo = addslashes($file['name']);
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
if ($query) {
$data['success'] = 'Insertion avec success';
} else {
$data['errors'] = 'failed';
}
$this->response($this->json($data), 200);
}

You could use the explode function in your api.php to parse the filepath you are getting from POST:
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
//for example, say $_POST['photo'] = "C:/my/fake/directory/testfile.jpg"
$photopath = explode("/", $_POST['photo']);
//print_r($photopath) results in Array ( [0] => C: [1] => my [2] => fake [3] => directory [4] => testfile.jpg )
$photo = end($photopath); //gets last result in the array (your filename)
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
Please note that this may not be the most efficient method of getting the filename from a path, and your delimiter ("/" in the example above) might need to change based on how you are getting your path. If you have any questions feel free to ask.

Related

Call to a member function getClientOriginalExtension() on string

In my laravel controller when i try to upload image i get this error..
My I Know what the problem is
This is inside my controller
$image = $request['images'];
if ($image)
{
$imgfile = $request['images'];
$imgpath = 'uploads/users/images/'.$user->id;
File::makeDirectory($imgpath, $mode = 0777, true, true);
$imgDestinationPath = $imgpath.'/'; // upload folder in public directory
$ext1 = $imgfile->getClientOriginalExtension();
$filename1 = uniqid('vid_').'.'.$ext1;
$usuccess = $imgfile->move($imgDestinationPath, $filename1);
}
This is my jquery code my form id is update profile and i get all the field values by its name
$("#updateprofile").on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var myData = {
name: $(this).find("[name='name']").val(),
gender:$(this).find("[name='gender']").val(),
lastname:$(this).find("[name='lastname']").val(),
email:$(this).find("[name='email']").val(),
mobile:$(this).find("[name='mobile']").val(),
address:$(this).find("[name='address']").val(),
city: $(this).find("[name='city']").val(),
state:$(this).find("[name='state']").val(),
country:$(this).find("[name='country']").val(),
pin:$(this).find("[name='pin']").val(),
images: document.getElementById('imageToUpload').files[0],
}
console.log("data", myData);
$.ajax({
type: "PUT",
url: url,
dataType: 'JSON',
data: myData,
success: function(data) {
console.log(data);
//alert("Profile update successfully")
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
alert("das");
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
Try this (assuming your form input's id and name value is images),
if($request->hasFile('images')) {
$imgfile = Input::file('images');
$imgpath = 'uploads/users/images/'.$user->id;
File::makeDirectory($imgpath, $mode = 0777, true, true);
$imgDestinationPath = $imgpath.'/';
$ext1 = $imgfile->getClientOriginalExtension();
$filename1 = uniqid('vid_').'.'.$ext1;
$usuccess = $imgfile->move($imgDestinationPath, $filename1);
}
In your jQuery code :
try changeing
images: document.getElementById('imageToUpload').files[0],
to
images: document.getElementById('imageToUpload').files[0].value,
and as you are uploading files through your form yous should specify contentType: 'multipart/form-data', in your ajax call

How to extract values from jquery `formData` to insert into Mysql?

My code is about submitting a multipart form, through $.ajax, which is successfully doing it & upon json_encode in submit.php , its giving me this :
{"success":"Image was submitted","formData":{"fb_link":"https:\/\/www.google.mv\/",
"show_fb":"1",
"filenames":[".\/uploads\/homepage-header-social-icons\/27.jpg"]}}
Can someone explain me, in submit.php, how can i extract values from formData, to store in mysql table ? I have tried, so many things including :
$fb_link = formData['fb_link'];
$show_fb = formData['show_fb'];
and
$arr = json_encode($data);
$fb_link=$arr['fb_link'];
and
$fb_link = REQUEST['fb_link'];
$show_fb = REQUEST['show_fb'];
but, nothing seems to work ? Any Guesses ?
Thanks
update :
JS code on parent-page is :
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form#upload_form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
//var data = new FormData($(this)[0]);
$.ajax({
url: 'jquery_upload_form_submit.php?files=files',
type: 'POST',
data: data,
//data: {data, var1:"fb_link" , var2:"show_fb"},
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'jquery_upload_form_submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
UPDATE CODE OF - submit.php :
<?php
// Here we add server side validation and better error handling :)
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = './uploads/homepage-header-social-icons/';
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename($file['name']))) {
$files[] = $uploaddir . $file['name'];
//$files = $uploaddir . $file['name'];
}
else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your image-files') : array('files' => $files);
}
else {
$data = array(
'success' => 'Image was submitted',
'formData' => $_POST
);
}
echo json_encode($data);
?>
If you're using POST method in ajax, then you can access those data in PHP.
print_r($_POST);
Form submit using ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
You can access the data on PHP
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
If you want to access file object, you need to use $_FILES
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
This problem is different in terms that :
1. Its sending MULTIPLE files, to upload
2. Contains a SELECT
3. Contains an INPUT
So, images are serialized & sent via GET . And, rest FORM data is being sent via POST. So Solution is :
var data = new FormData($(this)[0]);
inside : function uploadFiles(event){}
And in submit.php :
print_r($_POST);
print_r($_GET);
die();
This will give you both values. Then comment these & as per the Code, make these changes :
$filename_wpath = serialize($files);
$fb_link = $_POST['fb_link'];
$show_fb = $_POST['show_fb'];
$sql = "INSERT INTO `tblbasicheader`(fldFB_image, fldFB_link, fldHideShow)
VALUES('$filename_wpath','$fb_link','$show_fb')";
mysqli_query($db_conx, $sql);
Works like Charm ! :)

Ajax success function parameter empty?

Im getting an empty success function parameter back (lewa).
But when I change 'lewa' to order (order.vnaam) it works. Could you point out what the problem is?
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'json-users.php',
dataType: 'json',
success: function(naam) {
$.each(naam, function(i, item) {
$('ul').append('<li>Voornaam: ' + item.voornaam + '<br>Achternaam: ' + item.achternaam + '</li>');
});
}
}); //end get data db
}); //end document ready function
function upload() {
var order = {
vnaam: $('.voornaam').val(),
anaam: $('.achternaam').val(),
};
$.ajax({
type: 'POST',
url: 'posttest.php',
/*dataType: 'json',*/
data: order,
success: function( lewa ) {
//When action is a success
$('ul').append('<li>Voornaam: ' + lewa.vnaam + '<br>Achternaam: ' + lewa.anaam + '</li>');
console.log(lewa);
console.log(order);
},
error: function() {
//When action is a failure
alert('error running function');
}
});
}
The following code is posttest.php
$voornaam = mysqli_real_escape_string($connect, $_POST["vnaam"]);
$achternaam = mysqli_real_escape_string($connect, $_POST["anaam"]);
$sql = "INSERT INTO users (voornaam, achternaam) VALUES ('".$voornaam."', '".$achternaam."')";
mysqli_query($connect, $sql);
The following code is json-users.php
$array_user = array();
while ( $data = mysqli_fetch_assoc($result) ) {
$array_user[] = $data;
}
echo json_encode($array_user);
Didnt return anything from posttest.php

PHP doesn't get JQuery serialize() POST parameters

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r

ajax jquery file upload not working

I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?

Categories