I am retrieving an image from a user's gallery, and trying to post the base64 encoded version to a server using php and mysql. The base64 string returned is:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCAPAAhwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDsRgU4DIpi5FOBrZnOhwUClxxSDkU8UhkLLUTKQfrVlhTCAecU0xNEBUYppT0NTFcim7TirTE0QkEGlANPK+1AXFVcVhuCD9aeB0IpwFBGORU3HYUA0o4pAec05aljQBjijINKAKQildAKppQKRVJp2MCgEGBTWxTs5oIyKSYyJlzmo9pHGeKnK0m2rTE0QZINOV8jB608q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AuXLhc8HJ5x34rSmtSamxnzECQAAgdeetDMQCBnkg4pZ3VrvJPygnBPfNV2lAckk4/lWrRkmPFwVOD8wAwQagmj80b4xuBzgHg8dh602Vh55AOQTjIoVWy0ZJznIweQfUUJWBu5SMpB54XoQOmP8AEU5nKSAg5wM59RSuFlOxwElzw3Yn0NRMSYxG64lQ9e5HpWuhmxVYGQN2J5q/vLQxLnjBPH1rKJxyBwasxyYUEdhihrQExZGDx4I+bAOfcUSfMEccMAB/9eopDiQ46Z4pNxYEe1ILk7OWAJ+8CDk0vmkXAccHA5qJWyAecjqKMc5HTpTsCZNMd0gYdxipY1yQcdqZGuVxjtxVhFKgYGSTgCpZSRPCC7BQOBjH1rQ8ramAeBUNoB5uMYxxk1obd4z0HX61DZaRHBDlTxnA5q/aW4AAA+pPc0trAWAGOD3rStoCDz0PSpbLSJbeDjkdavRxBQAO1RRYxgdqnU0ITHgYI96fTc0oPPSmZsetLk00EAUZBpktDs46mlyPWoyc0uaLhYloooqyQooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACkxkYNLiigCBzsUL2JwP/AK9YuqAKowMHJNbkgBxkZ5rE1yMxQ7uoINKWw46M5+VgoMhOQAQB6msWZ5JSEJAycDjkZrQmfEaqex4x79apYDXAGMYOSfUVCRsPtCRO2QML8q+59a27LIhyepOaxVISfA5wCT9TxW3ageWC
The code used to post (base64 string is cameraPic):
$.post("https://www.domaintopostto.co.uk/API/users.php", { user: usernamePost, userID: result.id, gender: gender, image: cameraPic }, function (data) {
console.log(data);
console.log("HERE");
if (data.result = "Added") {
window.location = "sportsSelector.html";
}
});
PHP code on the server:
$image = $_POST['image'];
$base64img = str_replace('data:image/jpeg;base64,', '', $image);
$sql = "INSERT INTO userActivityLocation(user, userID, gender, image)VALUES('$user', '$userID', '$gender', '$base64img')";
The base64 string does not appear in the db. In fact, the image: cameraPic pasrt of the request entirely disappears.....it isnt there in the network view in chrome. The other fields fire off okay and show up in chrome. No errors in console, none echoed from the server.
Any advice would be greatly appreciated thankyou!
i tried to replicate your scripts and this is working for me :
var cameraPic = "yourverylongencodedstring";
$.post("query.php", { image: cameraPic }, function (data) {
console.log(data);
});
on query.php i have :
<?php
$image = $_POST['image'];
$base64img = str_replace('data:image/jpeg;base64,', '', $image);
echo $base64img;
?>
and i can see the correct response string in network panel in chrome;
so i am wondering:
-you're passing an empty cameraPic var?
-if it doesn't show up after the sql query, the sql field is large enough for the string?
-you have not whitelisted "www.domaintopostto.co.uk" ?
Trying to guess!
Related
I have a page with multiple forms on, where each form is processed with PHP in the backend that sends data to a MySQL database, but on the front end it uses Javascript's fetchAPI to prevent the page refreshing when an instance of the form is completed and data is sent to the database.
I have some PHP server side validations that take place that still work in terms of not sending the data to the database, although on submission the instance of the form completed does disappear from the page (due to javascript shown below), but re-appears when refreshed if it failed the validations.
The main code example below includes this code block that would normally output the error message:
<?php
// echo form validation error messages
if(isset($error)) {
foreach($error as $msg) {
echo "<p>** {$msg}</p>";
}
}
?>
In terms of outputting these error messages is it possible to still use this PHP code (currently not working), or now I'm using the javascript fetchAPI in conjunction with PHP, will I have to also write validations in JavaScript to output the errors on the front end, in addition to the PHP ones which securely prevent the form failing the validations? It should be noted there are multiple instances of the form on the page which are outputted with a while loop, each one is in relation to a specific post.
<?php
if(isset($_POST['upload-submit'])) {
// note $imageTitle is a variable given to the title of a post submitted via an HTML form
if(!preg_match('/^[a-zA-Z0-9\s]+$/', $imageTitle)) {
$error[] = "Post Title can be letters and numbers only";
}
if(empty(trim($imageTitle))){
$error[] = "Image Title cannot be blank";
}
// if no errors process submission
if (!isset($error)) {
try {
// PDO prepared statements that update the database
} catch (PDOException $e) {
echo "There is an error: " . $e->getMessage();
}
}
}
?>
Also here is the javascript fetchAPI code that works on the page.
var forms = document.querySelectorAll('.image-upload-details-form'),
forms.forEach(item => {
item.querySelectorAll('[type="submit"], button').forEach(button => {
button.addEventListener("click", e => item._button = button); //store this button in the form element
})
item.addEventListener("submit", function(evt, btn) {
evt.preventDefault();
const formData = new FormData(this);
if (this._button) //submitted by a button?
{
formData.set(this._button.name, this._button.value);
}
fetch("upload-details.php", {
method: 'post',
body: formData
}).then(function(response){
return response.text();
}).then(function(text){
console.log(text);
}).catch(function (error){
console.error(error);
})
// removes form when submitted
item.remove();
})
})
Many thanks in advance for any help / advice.
My understanding is after making the fetch request you want to show the error message.
Your php code is incomplete. On pdo execption, you are outputting a string. On your validation, you are storing in an array.
Not clear about the output, if the validation fails.
(Recommended is output a string with html tags, so you can overcome the complexity of running a loop and creating dom nodes at js end)
While communicating with backend, best way is to use JSON format, to identify whether the response success or error
<?php
// echo form validation error messages // from php
if(isset($error)) {
foreach($error as $msg) {
echo "<p>** {$msg}</p>";
}
}
<div class="error-messages"></div> // for fetch error messages. leave it blank
?>
const errorElement = document.querySelector(".error-messages"); // capture error element
errorElement.innerHTML =''; // clean previous errors
fetch("upload-details.php", {
method: 'post',
body: formData
}).then(function(response){
const echoed = response.text(); // assuming you are captuing the text
if(echoed.includes("There is an error: ")){ // it is an error
errorElement.innerHTML = echoed; // insert the error message into the div
return;
}
return response.text();
}).then(function(text){
console.log(text);
}).catch(function (error){
errorElement.innerHTML = "Error communicating with server.Contact administrator"
console.error(error);
})
First you have not give full php function code post method.
you have to write proper code in php which will give proper response of ajax call like below
<?php
if (isset($_POST['username'])) {
// do user authentication as per your requirements
// ...
// ...
// based on successful authentication
echo json_encode(array('success' => 1));
} else {
echo json_encode(array('success' => 0));
}
after that you have to add code in javascript for handle error and success based on your php reponse.
function(response)
{
var jsonData = JSON.parse(response);
// user is logged in successfully in the back-end
// let's redirect
if (jsonData.success == "1")
{
location.href = 'my_profile.php';
}
else
{
alert('Invalid Credentials!');
}
}
This is proper way for ajax call request. Use proper code for that and your problem will solve
You need to echo you error(s) all in one time, otherwise you'll get the 1st echo only... ;
<?php
// echo form validation error messages
$echo = [];
if(isset($error)) {
foreach($error as $msg) {
$echo[] = "<p>** {$msg}</p>";
}
echo implode(PHP_EOL, $echo);
}
?>
And for you other block :
<?php
if(isset($_POST['upload-submit'])) {
// note $imageTitle is a variable given to the title of a post submitted via an HTML form
if(!preg_match('/^[a-zA-Z0-9\s]+$/', $imageTitle)) {
$error[] = "Post Title can be letters and numbers only";
}
if(empty(trim($imageTitle))){
$error[] = "Image Title cannot be blank";
}
// if no errors process submission
if (!isset($error)) {
try {
$success = false;
// PDO prepared statements that update the database => success = true ?
echo $success;
} catch (PDOException $e) {
echo "There is an error: " . $e->getMessage();
}
}
echo $errors; // form 'user' errors
}
?>
or smthg like that
When you catch PDOException you make echo (but not throw new Exeption).
So in JS it goes to then(function(response), not to catch(function (error).
You should check response in then(function(response).
Example:
.then(function(response){
if (response.includes('Error:') {
// do something
}
I am trying to upload image to an Etsy listing via their API v2. Their documentation have code example of image upload in PHP, in which the POST request body parameter is given like this
$params = array('#image' => '#'.$source_file.';type='.$mimetype);
How would I go about replicating this in JavaScript? I have tried sending the image blob as the image parameter but it does not seem to be working.
Edit: I am using npm oauth package. Here is my complete code that I am using to call the API.
var oauth1 = new OAuth1.OAuth(
'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r%20listings_w%20listings_d',
'https://openapi.etsy.com/v2/oauth/access_token',
'api_key',
'api_secret',
'1.0A',
null,
'HMAC-SHA1'
);
oauth1.post(
'https://openapi.etsy.com/v2/listings/915677000/images',
req.user.etsy.oauth_token,
req.user.etsy.oauth_token_secret,
{
'listing_id': 915677000,
'image': <image has to go here>
},
'multipart/form-data',
function (e, data, response){
if (e) console.error(e);
// let body = JSON.parse(data);
console.log(data);
res.redirect('/create-listings')
});
I'm trying to save my canvas image (generated by the user in the template) in my database. I've been through a lot of sources here, majority I've combined everything on it and got pretty much confused.
Steps that I'm trying to make:
Html form where provides different choices asked from the user (done)
Each time the user selects his/her choice, beside of it is the canvas that displays the image. (done)
A button that displays the summary of his choices and the canvas image generated through modal (done)
A button to Submit his order with the image in database using php and mysql No error! But it doesn't store my image
I don't need to download it, i just want it to directly store in my database once submitted
So where I'm stuck is in the STEP 4
I'll give a summary choice on my codes: (it works fine in my file, just giving you the outcome idea)
/*This retrieves my data my JS w/c is same file with my HTML: */
$('#review').click(function () {
$('#shape').html($('input[name="shape_design"]:checked').val());
$('#color').html($('input[name="color_design"]:checked').val());
//in this part, i am getting the image displayed in the canvas based on the user's choice
var canvasSource = document.getElementById('myCanvas');
var contextSource = canvasSource.getContext('2d');
var canvasShow = document.getElementById('show_canvas');
var contextShow = canvasShow.getContext('2d');
var image = contextSource.getImageData(0, 0, canvasSource.width, canvasSource.height);
contextShow.putImageData(image, 0, 0); });
});
$(function () { //this function converts the canvas to image, so it is now called as "Show Canvas" , it display well in my modal... not sure if its the right code
$("#submitBtn").bind("click", function () {
var base64 = $('#myCanvas')[0].toDataURL();
$("#show_canvas").attr("src", base64);
$("#show_canvas").show();
});
});
//After reviewing it, this part will perform to store it in the database.. which is quite I'm confused
$('#submitOrder').click(function(confirm){
swal({ //sweetalert style
title: "ORDER SENT", },
function(submit){
setTimeout(function(){
$('#showchoices').submit(); }, 500); //"showchoices" is the name of the Html form, it will proceed to ordersent.php
});
});
For my php which I'm not sure what I'm doing.
Ordersent.php
<? php
$shape_design = $_POST['shape_design'];
$color_design = $_POST['color_design'];
$upload_dir = "upload/"; //what does this do?
$myCanvas = $_POST['myCanvas']; //myCanvas is the name and id in my form
$myCanvas = str_replace('data:image/png;base64,', '', $myCanvas);
$myCanvas = str_replace(' ', '+', $myCanvas);
$data = base64_decode($myCanvas);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
$dbc = #mysql_connect('localhost' , 'root', '');
#mysql_select_db('order_tbl', $dbc);
$query1 = "INSERT INTO choices_tbl VALUES (NULL,'$shape_design','$color_design', '$myCanvas')";
if(#mysql_query($query1,$dbc))
{ Header("Location: /home.php"); }
else { print 'error!! '.mysql_error().''; }
?>
I tried following the instructions most of the tutorial, but it doesn't work on me.
I wanted to save it in my database using PATH , my my data type in my tables are
order_tbl
designID INT(6) NOT NULL ,
shape_design VARCHAR(20) ,
color_design VARCHAR(20) ,
myCanvas VARCHAR(150) ,
am I missing an attribute?
thanks for the help in advance! Thanks for bearing with me.
UPDATE:
I've found out what's been causing this problem. The webpage has a piece of Javascript contained inside its body which is preventing the Javascript body onload= function from executing in Firefox, Safari and IE. Chrome is able to run both without problems. To solve this I've tried moving the script inside <head>..</head> however that script will not work for me there, it seems like it needs to be inside the body (I've tried calling it from an external .js file too but it won't work from there either). This is the body onload function along with the problematic script:
<html>
<head>
//some Javascript & Style files are included here..
</head>
<body onload="getUserDetails()">
<script>
window.onload = function() {
$('#selectAllFriends').change(function(){
if (this.checked) {
$('#mfsForm :checkbox').each(function() {
this.checked = true;
})
}
else {
$('#mfsForm :checkbox').each(function() {
this.checked = false;
})
}
});
}
</script>
//rest of page body is contained here...
</body>
</html>
This script is needed as part of a Facebook Multi-Friend Selector. I think maybe the problem is to do with running window.onload and body onload= at the same time? Is there a way to maybe delay the Multi-Friend Selector script for a couple of seconds to let the body onload= function to run first, and would that resolve the problem?
Original Question:
I have a Javascript function which gets called on page load. Inside this function there’s a call to Facebook’s Graph API, this call gets user details from Facebook, and then passes them by an AJAX post to a PHP script.
This is the Javascript I'm using:
function getUserDetails() {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
if (response.error) {
console.log('Error - ' + response.error.message);
}
else {
var userid = response.id;
var userfirst_name = response.first_name;
var userlast_name = response.last_name;
var useremail = response.email;
var usergender = response.gender;
$.ajax({
url: 'insertdetails.php',
data: {'userid' : userid,
'userfirst_name' : userfirst_name,
'userlast_name' : userlast_name,
'useremail' : useremail,
'usergender' : usergender},
type: "POST",
success: function(response){
if(response==1){
alert( "Insert Successful!");
}
else{
alert( "Insert Failed!" );
}
}
});
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
Originally the PHP script contained two basic Insert statements which inserted these details into two tables in my database. This worked perfectly, but it wasn’t secure, so yesterday I wrote a PDO prepared transaction statement instead. I later found out that my database engine (MyISAM) doesn’t support PDO transaction statements, so I decided instead to run two queries (that would insert data into the two tables) inside the same PHP script instead (I know this isn’t best practice but I couldn’t find a way to get PDO transactions to work with MyISAM).
This is the part that’s confusing to me: when testing the new PHP file, I find that it works perfectly when I open the page in Chrome, however it doesn’t work with Firefox, IE, or Safari.
The PHP script
<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters for 1st insert
$stmt = $conn->prepare("INSERT INTO user (fb_id, f_name, l_name, email, gender)
VALUES (:fb_id, :firstname, :lastname, :email, :gender)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':firstname', $userfirst_name);
$stmt->bindParam(':lastname', $userlast_name);
$stmt->bindParam(':email', $useremail);
$stmt->bindParam(':gender', $usergender);
// insert a row
$userid = $_POST['userid'];
$userfirst_name = $_POST['userfirst_name'];
$userlast_name = $_POST['userlast_name'];
$useremail = $_POST['useremail'];
$usergender = $_POST['usergender'];
$stmt->execute();
// prepare sql and bind parameters for 2nd insert
$stmt = $conn->prepare("INSERT INTO orders (fb_id, cb, gb, invite)
VALUES (:fb_id, :cb, :gb, :invite)");
$stmt->bindParam(':fb_id', $userid);
$stmt->bindParam(':cb', $cb);
$stmt->bindParam(':gb', $gb);
$stmt->bindParam(':invite', $inviteo);
// insert a row
$userid = $_POST['userid'];
$cb = "1";
$gb = "10";
$inviteo = "0";
$stmt->execute();
echo "1";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Once the insert statements are completed I send an echo back to the Javascript function, and then a Javascript alert appears on screen to tell me if the insert was successful or not. This works perfectly in Chrome, but I don’t get any alert with the other three browsers, and nothing gets entered into the database when I try to use them. The fact that there’s no alert telling me it’s not successful makes me think that the error is in the Javascript not working with the browsers, but then again, it was working perfectly on all browsers before I switched the PHP to PDO.
I've made sure that Javascript is enabled, pop-ups aren't blocked, and I've tried looking at the console in Firefox but I don't see what could be wrong.
Any help or advice on this would be great. Thank you in advance!
I am using Froala editor for my website. This editor have built in image upload function - image upload is working fine, but I am having trouble with response.
This is from the documentation:
The server processes the HTTP request.
The server has to process the upload request, save the image and return a hashmap containing a link to the uploaded image. The returned hashmap needs to look like: { link: 'path_to_uploaded_file/file.png' }
This is my function for returning link:
public function froala_upload()
{
header('Content-type: application/json');
$folder = 'public/img/media';
$slika = $this->site->single_upload($folder, 'jpg|jpeg|png|bmp|JPG|JPEG|PNG|BMP');
$link = array("link" => $slika);
echo json_encode($link);
}
This is JS code:
$('textarea').editable({
inlineMode: false,
imageUploadParam: "userfile",
imageUploadURL: "<?php echo base_url() ?>admin/froala_upload",
// Set the image error callback.
imageErrorCallback: function (data) {
// Bad link.
if (data.errorCode == 1) {
console.log(data);
}
// No link in upload response.
else if (data.errorCode == 2) {
console.log(data);
}
// Error during file upload.
else if (data.errorCode == 3) {
console.log(data);
}
}
});
When I upload image I get following error:
Object { errorCode=1, errorStatus="Bad link."}
And this is response that I get:
{"link":"7d59d61.jpg"}
What seem to be a problem?
Froala image upload documentation
You must return the absolute image path :
$link = array("link" => '/img/media/'.$slika);
Because Froala looks for it to http://example.com/7d59d61.jpg
The problem is that the image cannot be loaded from the returned link. You'd have to make sure that the image can be accessed from it. Froala Editor uses the link you return for src attribute from img tag. I think you'd have to do something like:
$link = array("link" => $slika . 'public/img/media');