I met a problem that when I make a POST request, the server responses with 404 error, while making GET request, it responses with 200.
Here are the methods that I have tried:
$.ajax({
type:"POST",
url: "script.php",
data:{
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
And:
var data = new FormData();
data.append("data" , dataURL);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', 'script.php', true );
xhr.send(data);
Further more I have tried to include:
header("HTTP/1.0 200 OK", true);
header('Access-Control-Allow-Origin: *');
in the php script. But none of them works.
Anyone has idea? Thanks!
EDIT:
Here is the php script. By the way, I am using nodejs...
<?php
// requires php5
header('Access-Control-Allow-Origin: *');
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I am new to nodejs and finally I found that I should write a function in server.js to process the get request.
Related
I am working on Reactjs and Php, Actually i am trying to upload image to server, Image is uploading but whenever i try to open image then showing "we dont support this file format", How can i fix this ?
I am sending formdata with multipart form data and in php (api) i am using base64 image for upload image to server
Is my apporach for sending image to axios (api) is correct or something wrong with php code
Here is my nextjs code
const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
var imagefile = document.querySelector('#file');
formData.append("file", imagefile.files[0]);
const response = await axios({
method: "post",
url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('respone is '+ response.data.msg);
}).catch(function (error) {
alert('respone is '+ error);
console.log("failed to get recommend playlist");
console.log('error is '+ error.msg);
});
}
And following is my Api code in Php side
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode(explode( ',', $files)[1]);
define('UPLOAD_DIR', 'uploads/');
$file_ext = strtolower( end(explode('.',$file_name)));
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.'.$file_ext;
file_put_contents($file, $image_base64);
The issues is from the PHP. You can just simplify it by using pathinfo() to get the extension and move_uploaded_file() to move the uploaded file to the server.
Try this
define('UPLOAD_DIR', 'uploads/');
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$file_name = UPLOAD_DIR . uniqid() . time() . '.' . $file_ext;
move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
I am using recorder.js library and want to send the recorded message to my gmail account using PHPMailer. I have done everything but the only problem that I am getting is that when I send the file as an attachment and download it from my mail, it is corrupted (or whatever) and my system says "The file is unplayable". Moreover, when I check my local uploads/ folder where I am writing all the files, they are unplayable too. I don't know what seems to be the problem and I am stuck on this since past two days. Thanks in advance.
My JS call to upload.php
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
and my upload.php
<?php
require "php-mailer-master/PHPMailerAutoload.php";
define('UPLOAD_DIR', 'uploads/');
$a = $_FILES['audio_data']['name'];
$a = str_replace('data:audio/wav;base64,', '', $a);
$a = str_replace(' ', '+', $a);
$data = base64_decode($a);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Please note that I have skipped the part of code which is actually sending mail because I believe that is irrelevant.
I have a form, the form has text fields and a canvas in it that preforms as a signiture pad.
link to the form
I use ajax in order to send the form.
What I have troubles doing is to confirm that the form is inserted to the database.
I think that there is a collision between the ajax and the php I use in order to insert the form data to the mysql db
how can I do it?
This is the content of the js file
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
alert(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
};
xhr.send(fd);
This is the content of the upload_data.php file:
<?php
require 'inc/inc.php';
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$idNo = $_POST['idno'];
$name = $_POST['fname'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() ."-" . $idNo . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
$suc = new Form;
$suc->insert_data($name, $file, $idNo);
?>
This is the insert_data() php function content
public function insert_data($name, $file, $idNo){
$query = $this->dbh->prepare("INSERT INTO signitures (name, file, idno) VALUES(?, ?, ?)");
$query->bindparam(1, $name);
$query->bindparam(2, $file);
$query->bindparam(3, $idNo);
try {
$query->execute();
if ($query) {
echo "success!! ";
} else {
echo "Failure conncting db!";
}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
I know that if $query->execute(); returns true than the data was inserted.
How can I notify the user that the data was really inserted to the database?
Even pass the user to a new page is an option.
Actualy, redirect the user to a new page will be great!
Hi you need to add in the function insert_data on the try{ at the end} a echo of your success to send to ajax script as response so a simple.
$success['success'] = "You request just sending to the server ...";
echo json_encode($success);
In your fonction ajax
xhr.onload = function(data) {
console.log(data);
console.log(data.success);
};
You need to adapt, this method show you how send data PHP to JS regards.
You can also send the response inside a "body" key-value pair, and put the success/error indication inside the HTTP status code:
$success["body"] = "You request just sending to the server ...";
header("HTTP/1.1 200 OK", true, 200);
And receive it in js:
xhr.onload = function(data) {
console.log(data.status);
console.log(data.body);
};
see:
Set Response Status Code
or:
http://php.net/manual/de/function.http-response-code.php
explanation of codes:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I have this function from a GitHub repo that outputs a drawn signature on canvas to a DataURL(). When I inspect it, it comes back as a string of encoded data(a .png).
The user clicks the save button and this happens:
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
saveSignature(signaturePad.toDataURL());
}
});
function saveSignature(dataURL) {
$.ajax({
type: "POST",
datatype: "json",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
signaturePad.clear();
}
Then it triggers a PHP script in the same folder, called script.php.
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I can't find out why it's causing a 500 server error.
The console isn't printing 'unable to save file', nor 'saved.'
You have error in script.php you are receving data in $img while write using $data so need to replace variable
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $img); //<---- change here
print $success ? $file : 'Unable to save the file.';
?>
I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';