For one my application, I need to keep image files in database table. I am using AJAX to send the multi-part form data and can view the image file details on action page.
On action page, base64 encoding is working and showing the correct encoded data. Also, I saw the encoded data is showing on UPDATE SQL query by echoing the SQL statement.
But while trying to execute the SQL query statement then every time its only inserting data:image/;base64, and ignoring the base64 encoded full data.
When I submit the form without using AJAX then the system update the database table with base64 encoded data.
Sample code:
JavaScript:
$(document).on("change", "#bird", function() {
var file_data = $("#bird").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data)
$.ajax({
type: 'post',
contentType: false,
processData: false,
data: image_data,
url: "/update-bird.php",
dataType: 'json',
cache:false,
success: function(data) {
// Ajax
}
});
});
PHP:
if(isset($_FILES))
{
$path = $_FILES['file']['name'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($_FILES['file']['tmp_name']);
$birdpic = "data:image/".pathinfo($path, PATHINFO_EXTENSION).";base64,".base64_encode(file_get_contents($_FILES['file']['tmp_name']));
$updateQ = "UPDATE birds SET picture='$birdpic' WHERE name='Yoy'";
if($dbo->query($updateQ))
echo 1;
else
echo 0;
}
I hope, will get some advice to solve this issue. Thanks in advance!
Try this one - Table column must be BLOB or LONGBLOB
$img_data = file_get_contents($img_path);
$type = pathinfo($img_path, PATHINFO_EXTENSION);
$birdpic = base64_encode($img_data);
$updateQ = "UPDATE birds SET picture='$birdpic' WHERE name='Yoy'";
AJAX will not carry the image file, try to use Jquery or submit the form.
Form with enctype="multipart/form-data", I not sure Jquery will work.
Related
I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code
I'm trying to provide data to my MYSQL Database using Ajax, however, for some reason my PHP file is not reading the JSON array that I post to the file. Within the array I also have a file to store an image on my server as well as my database.
Javascript file
$(document).ready(function(){
// Give Data to PHP
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
//formData.append('tax_file', $('input[type=file]')[0].files[0]
var img = $('input[name=img]').prop('files')[0];
var name = img.name,
tmp = img.tmp_name,
size = img.size,
form = $('input[name=form-submit]').val(),
myName = $('input[name=my-name]').val(),
desc = $('input[name=description]').val();
// document.write(name + tmp + size);
var formData = {
'form-submit' : form,
'my-name' : myName,
'description' : desc,
'img' : name,
'tmp_name' : tmp,
'size' : size
};
// document.write(JSON.stringify(formData));
console.log(formData);
// process the form
$.ajax({
url : 'insert-bio.php', // the url where we want to POST
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
data : formData, // our data object
processData : false,
contentType : false,
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
My PHP file
include('../db.php');
$conn = new Database();
echo explode(",", $_POST['data']);
if(isset($_POST['form-submit'])){
// text data
$name = strip_tags($_POST['my-name']);
$desc = strip_tags($_POST['description']);
// picture stuff
$file = rand(1000,100000)."-".$_FILES['img']['name'];
$file_loc = $_FILES['img']['tmp_name'];
$file_size = $_FILES['img']['size'];
$file_type = $_FILES['img']['type'];
// folder for profile pic
$folder = "bio-pic/";
// new file size in KB
$new_size = $file_size/1024;
// make file name in lower case
$new_file_name = strtolower($file);
// final pic file
$final_file=str_replace(' ','-',$new_file_name);
// mysql query for form data
if(move_uploaded_file($file_loc,$folder.$final_file)){
$sql="INSERT INTO bio(img, name, description) VALUES('$final_file', '$name', '$desc')";
$conn->query($sql);
}
} else {
echo "Need data";
}
$query = $conn->query("SELECT * FROM bio");
$results=$query->fetchAll(PDO::FETCH_ASSOC);
$parse_bio_json = json_encode($results);
file_put_contents('bio-DATA.json', $parse_bio_json);
echo $parse_bio_json;
The console shows that I have made contact with my PHP file, but it simply has not read any data.
The error on the PHP file:
Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[]
I had the same issue back in the day. After doing lots of research I found out that JSON cannot have a property that holds a file value. However, you can follow this example. It worked great for me. Hope it helps :)
$('#upload').on('click', function() {
var file_data = $('#sortpicture').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
}
});
});
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']);
}
?>
Credit goes to -> jQuery AJAX file upload PHP
When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get š instead I am getting ? or without using utf8_decode() when sending data from server, I get ĹĄ. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. All other request from database give the right charset. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html" // change to text/html, application/text doesnt work at all
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
$.ajax({
data:{'select_had':select_had},
success: function(data){
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});
JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.
You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.
You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.
To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure
I used jQuery to read from a json file, but when I try to write it to the same file, it won't work.
Here's the code:
$.getJSON(src,function(data){
var about= data.abouttext;
var mail= data.mail;
var phone = data.phone;
$("#about_ta").val(about);
$("#mail_ta").val(e);
$("#phone_ta").val(mp);
$("#wizard_tabs_edit").show();
$("#mask_edit").show();
$("#edit_save").on("click",function() {
data.abouttext = $("#about_ta").val();
data.mail = $("#mail_ta").val();
data.phone = $("#phone_ta").val();
$.ajax({
url: src,
type: "POST",
data: data,
contentType: "application/json",
success: function(response){
alert("aaa");
}
});
$("#wizard_tabs_edit").hide();
$("#mask_edit").hide();
});
});
src is the path to the file (working at the $.getJSON), and it's giving me the alert "aaa" when AJAX succeeds.
But still, the JSON file remains the same.
The only way is to use php or any other backend coding language that can handle the file manipulation for you. Below is an example if you use php5 so you can have a clue:
<?php
// Specify filename
$filename = 'myJsonFile.json';
// Read data transforming them to an array
$data = json_decode(file_get_contents($filename), true);
// Push to the array a new pair
array_push($data, ['key' => 'value']);
// Open file for writing
$file = fopen($filename, 'w');
// Write data as json
fwrite($file, json_encode($data));
// Close file
fclose($file);
?>