The following is my code.I am unable to send the image file to the php page.I'm using formData and i'm not clear about the concept of it.How do i send it to php page and how do i retrieve The image in php page?
JAVASCRIPT CODE
function UpdateUserDetails() {
var title = $("#title1").val();
var store = $(".search-box").val();
var category= $("#category").val();
var descp=$("#descp1").val();
var url=$("#url1").val();
var id = $("#hidden_user_id").val();
var form = $('#image1')[0];
var formData = new FormData(form);
$.post("update.php", {
id: id,
title:title,
store:store,
category:category,
descp:descp,
data:formData,
url:url
},
function (data, status) {
$("#update_user_modal").modal("hide");
readRecords();
}
);
}
update.php
<?php
include("db_connection.php");
if(isset($_POST))
{
$id = $_POST['id'];
$title=$_POST['title'];
$desc=$_POST['descp'];
$pname=$_POST['store'];
$category=$_POST['category'];
$url=$_POST['url'];
$path = $_FILES['tmp_name'];
$name = $_FILES['name'];
$size = $_FILES['size'];
$type = $_FILES['type'];
$content = file_get_contents($path);
$content = base64_encode($content);
$sql1 = "update products set title='$title',url='$url',store='$pname', product_catagory='$category', image='$content',size='$size',type='$type',descp='$desc' where id=".$id."";
if(mysql_query($sql1))
{
echo"updated";
}
else
echo "Not Updated";
}
?>
Try this:
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_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(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
It works for me.
Related
I have a website where I process signatures. I transfer them to a png and save them to my server using AJAX. I'm trying to save them in a folder with the username of them user using a variable in PHP. I would like to have this variable stored in the session however when I tried it did not work.
I have tried having the session running in both pages
The beginning of the file with the sig pad:
session_start();
$name = $_POST['name'];
$emp = $_POST['empid'];
$_SESSION["name"] = $name;
The submit function:
$(document).ready(function(e){
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true, drawBezierCurves:true, lineTop:90});
});
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
});
session_start();
if(isset($_SESSION['name'])) {
$name = $_SESSION['name'];
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = 'signature';
//Location to where you want to created sign image
$file_name = './contracts'.$name.'/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
}
I am using html2canvas and Canvas2Image to create a png image from canvas and save it to the server with a unique filename.
I would like to know how to retrieve and show the unique filename after it gets generated.
jQuery
$(function() {
$("#convertcanvas").click(function() {
html2canvas($("#mycanvas"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert for sharing
var img = canvas.toDataURL("image/png",1.0);
$.ajax({
url:'save.php',
type:'POST',
data:{
data:img
}
});
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$file = 'images/myfile'.md5(uniqid()).'.png';
file_put_contents($file, $data);
?>
Thanks in advance for any help.
You can get the filename by returning it in your PHP and catching it in the AJAX with a succes method.
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$filename = 'myfile'.md5(uniqid()).'.png'; // <-- Added this because you probably don't want to return the image folder.
$path = 'images/'.$filename;
file_put_contents($path, $data);
echo $filename; // <-- echo your new filename!
?>
jQuery
$.ajax({
url:'save.php',
type:'POST',
data:{
data:img
},
success: function(data) {
alert(data); // <-- here is your filename
handleData(data);
}
});
You can simply give back the filename inside of an array and return it as JSON with json_encode.
PHP
<?php
$data = $_POST['data'];
$data = substr($data,strpos($data,",")+1);
$data = base64_decode($data);
$file = 'images/myfile'.md5(uniqid()).'.png';
file_put_contents($file, $data);
echo json_encode(array('filename' => $file));
?>
And in your script you can specify to expect json data by setting the 'dataType' property to "json". Then you can use the .done() function to do anything you want with the returned data, for example console logging it:
jQuery
var img = canvas.toDataURL("image/png",1.0);
$.ajax({
url:'save.php',
type:'POST',
dataType: 'json',
data:{
data:img
}
}).done(function(data){
console.log(data);
});
I am completely confused:
This is my php script "add_credits.php". It runs perfectly if I create a form and call it via method="post".
$stmt = "UPDATE sites SET credits=:credits WHERE id=:id";
$stmt = $db->prepare($stmt);
$stmt ->execute( array( ":credits" => $_POST['cred'], ":id" => $_POST['id'] ) );
This is my input field that triggers the jquery/ajax.
<input id="<?php echo $row['id']; ?>" type="text" class="credits" value="<?php echo $row['credits']; ?>" />
This is my jquery, which will echo eitther variable in an alert box correctly on success.
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = 'id=' + add_id;
var add_cred = $(this).attr("value");
var info2 = 'cred=' + add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {info:info, info2:info2},
success : function() {
alert(info2);
}
});
return true;
});
So why is it that its reporting success, yet no UPDATE is being performed, as if the php is not receiving the $_POST details? Am I missing something??
You don't have to manually serialize the data like that
$('.credits').on('input', function() {
var req = $.post('add_credits.php', {
info: $(this).attr('id'),
info2: $(this).attr('value')
});
req.done(function(res) {
console.log(res);
});
req.fail(function(err) {
console.error(err);
});
});
On the PHP side of things, make sure you're reading info and info2
// info and info2 were set in the POST request in the jQuery above
$info = $_POST['info'];
$info2 = $_POST['info2'];
do_something($info, $info2);
// respond in some way
header('content-type: application/json');
echo json_encode(['ok'=> true]);
You can name the fields id and cred if that's what you wish. That would change the jQuery data to this
var req = $.post('url', {
id: $(this).attr('id'),
cred: $(this).attr('value')
});
Then make sure you read $_POST['id'] and $_POST['cred'] in the PHP
Use the following jquery code:
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = add_id;
var add_cred = $(this).attr("value");
var info2 = add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {id:info, cred:info2},
success : function() {
alert(info2);
}
});
return true;
});
I have stored the ID of the user in session storage. I need to perform an action using the ID so I am passing it to the server using AJAX but the data is not reaching the server.
AJAX:-
$(document).ready(function(){
$('#coupon_code').hide();
$('#coupon_status').hide();
var id = sessionStorage.getItem('user_id');
$('#generate').click(function(){
$.ajax({
type : "POST",
dataType : 'json',
url : 'http://127.0.0.1/ionic/generate.php',
data : id,
beforeSend : function(){
console.log(sessionStorage.getItem('user_id'));
console.log("data sent");
},
success : function(data){
console.log(data);
console.log(data.code);
console.log(data.value);
}
});
});
});
PHP script:-
<?php
require 'db_connect.php';
header('Access-Control-Allow-Origin: *');
$id = $_POST['id'];
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($i = 0; $i < 5; $i++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id,'$string',1)";
$res_ins = mysqli_query($con,$ins);
if($res_ins)
{
echo json_encode(array("status" => "done", "code" => $string,"value" => "1"));
//echo $string;
}
else
{
echo "NO";
}
?>
EDIT :-
Firebug result
You are only sending value in json data - you need to send key-value pair - so through key you will get data at server
This should work for you - also you can debug data in firebug what is going to server or not
You need to replace
This line data : id,
with this line data : {'id' : id},
$(document).ready(function(){
$('#coupon_code').hide();
$('#coupon_status').hide();
var id = sessionStorage.getItem('user_id');
$('#generate').click(function(){
$.ajax({
type : "POST",
dataType : 'json',
url : 'http://127.0.0.1/ionic/generate.php',
data : {'id' : id},
beforeSend : function(){
console.log(sessionStorage.getItem('user_id'));
console.log("data sent");
},
success : function(data){
console.log(data);
console.log(data.code);
console.log(data.value);
}
});
});
});
There is also a bug in insert query -
$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id,'$string',1)";
(')single quote not closed for '$id
$ins = "INSERT INTO `coupon_code` (id,code,status) VALUES ('$id','$string',1)";
I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.