I have a problem that I can not solve (it is probably also your case if you read this).
I would like to send JSON data to a remote server via AJAX. This data contains an image and a string:
{
"question": "Your SquareOff Question",
"photo" : "Your photo" // optional
}
I need to send this JSON to "www.so-staging.herokuapp.com/api/v1/squareoffs?auth_token=qSJPySVk5yMsaAVE6mSu" where "qSJPySVk5yMsaAVE6mSu" is a token that I had previously ask for it and store in the $_SESSION, in a php side.
So I need to send this information to my php page before send it to the remote server. And here is my problem. I can receive the image in my php page, but not re-send it to the remote server.
I show you my code.
On the Html side, nothing special:
On the javascript page:
I don't know and to send the image and the string in the same time so. (if you have a hint, it would be with pleasure but it is not my mane problem).
function upload_photo(){
var photo = document.getElementById('photo');
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append('photo', photo.files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'create_square.php');
xhr.send(formData);
/* Check the response status */
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && client.status == 200){
create_square_xhr();
}
}
}
function create_square_xhr(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'create_square.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && client.status == 200){
// response is a iframe who display my question and my image if I have
// send one. I display it.
}
};
xhr.send('question=' + document.getElementById('question').value;
}
upload_photo();
And on my php page (create_square.php):
if(isset($_SESSION['token']) && isset($_POST['question']) && isset($_FILES['photo'])){
$url = 'https://so-staging.herokuapp.com/api/v1/squareoffs?auth_token=' . $token;
$data = array('question' => $_POST['question'], 'photo' => $_FILES['photo']);
$data = json_encode($data);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n" .
"Accept: application/json\r\n",
'method' => 'POST',
'content' => $data
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo &result;
}
The response is an iframe who dispay my question and my photo if I have send one.
But when I execute this code, there is no image displayed.
I think the probleme is on the php page because I recive the $_FILES['photo'].
If you have any suggestion, I will be grateful. Thank you!
I would suggest adding a check for errors by checking: $_FILES["photo"]["error"], which may tell you if there is an issue with the photo upload.
You also have to remember that when uploading photos with PHP that it is uploaded with a randomly generated name that you typically need to move to the final location before you do anything else with it.
This is typically what you need to do in order to have access to the photo once it has been uploaded.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
echo $_FILES["photo"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"],
"upload/" . $_FILES["photo"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["photo"]["name"];
}
Related
I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest
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 contacted GoDaddy about this, in case it is something on their end, but they couldn't really help.
I'm trying to send a contact form via JSON in a xmlhttprequest, and I'm sending it via a POST request. Unfortunately, and this is something that wasn't happening on another hosting service, it is being received as a get request.
Here is my js code, and what Chrome is displaying after sending it:
code:
function SendJson(values, type){
var xhr = new XMLHttpRequest();
var url = 'http://www.klemequestrianestates.com/processes/mail_form.php';
var data = JSON.stringify(values);
console.log(data);
xhr.open('POST', url);
xhr.setRequestHeader('Form-Type', type);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//success confirmation
}
};
}
Where Values is a js object, and type is either 'sell' or 'buy' (the form has 2 different types of clients that might use it, and sellers and buyers have different fields.
Chrome Debugger:
Here is the PHP file:
<?php
header('Access-Control-Allow-Headers: *');
header("Access-Control-Allow-Methods: POST, GET");
$data_type = $_SERVER['HTTP_FORM_TYPE'];
$raw_JSON = file_get_contents('php://input');
$converted_JSON = json_decode($raw_JSON);
echo var_dump($converted_JSON);
$type = $_SERVER['REQUEST_METHOD'];
echo var_dump($type);
if($data_type === 'sell'){
$first_name = $converted_JSON->div_00;
$last_name = $converted_JSON->div_01;
$phone_num = $converted_JSON->div_02;
$email = $converted_JSON->div_03;
$street = $converted_JSON->div_04;
$city = $converted_JSON->div_05;
$state = $converted_JSON->div_06;
$zip = $converted_JSON->div_07;
$option = $converted_JSON->div_08;
$message = $converted_JSON->div_09;
$to = 'contact#joshualyness.com';
$subject = $first_name.' '.$last_name.', '.$option;
$body = 'From: '.$email.PHP_EOL.PHP_EOL.'Phone Number: '.$phone_num.PHP_EOL.PHP_EOL.'Address: '. $street.PHP_EOL.$city.PHP_EOL.$state.PHP_EOL.$zip.PHP_EOL.PHP_EOL.'Message: '.$details;
mail($to, $subject, $body);
}
Here is the var dump contents:
Any ideas why this is happening? If you need any more details, drop a comment and I'll see what I can do. I know it's a bit of a weird question, I wouldn't be bothering the community if I didn't have any other ideas.
Thanks.
I am using a web labeling tool to generate image from the website, however I want to modify the function so that when I am done with labeling, instead of downloading the image to local, I want it to be uploaded into server. The function is in a javascript file and all the upload associated with JS has to do with submitting forms. There is no form and super globals, how am I supposed to upload a web generated image to server?
here is the code I currently have, it is not in html file, it is in js file.
var file_data = annotator.export();
var formData = dataURItoBlob(file_data);
var fd = new FormData(document);
fd.append("resultImage",formData);
url="upload/";
http.open("POST", url, true);
// headers
http.setRequestHeader("Content-type", "application/x-www-form- urlencoded");
http.setRequestHeader("Content-length", fd.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(fd);
php file
<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Really appreciate your help, thank you.
dataURItoBlob(file_data); by the name of the function it looks like that is going to be returning a blob object. blob/file objects when uploaded to a php script are going to be in the $_FILES global, not $_POST. And you would use move_uploaded_file to move it to your desired destination.
Also you seem to be using the wrong index. You are using hidden_data in your php but you set the name to resultImage in your javascript. You would need to use the same name in php as you did in the javascript.
So your php code should look something like
$upload_dir = "upload/";
$img = $_FILES['resultImage'];
if($img["error"] == UPLOAD_ERR_OK){
//should do other sanitation like making sure the file
//that is uploaded is the actual type of file you expect
$path = $upload_dir . mktime() . ".png";
move_uploaded_file($img["tmp_name"], $path);
}
As a side note, when using and FormData object you do not need to set the request headers like Content-Type as they will automatically be set by the api.
I'm trying to save some xml content (that I receive as plain text) into my site's database. I read about saving XML content and someone suggested it is not a good idea to save XML in a text field (database), so I decided to do it in a blob. The thing is I'm doing it via CORS, through javascript this way:
var formData = new FormData();
formData.append("name", 'myNewFile');
// THE XML CONTENT
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
formData.append("file", blob);
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
resultsContainer.innerHTML = (request.responseText );
}
}
request.send(formData);
On the server, I store it with:
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('$name', '$file')";
It seemed to work, the entry was created in the database but I can't see what's inside the BLOB field. So, I tried to read that from server, using PHP, but I'm retrieving just "0" in the file field.
$sql = "SELECT datetime, name, file FROM ProfileFiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Timestamp: " . $row["datetime"]."<br>";
echo "Name: " . $row["name"]. "<br>";
echo "Content: " + $row["file"];
echo "<br>----------<br>";
}
}
else
{
echo "Nothing";
}
What am I missing? Thanks in advance! I never worked with PHP.
The reason why you don't get anything in $_POST['file'], is that you are sending it as a file. Files that are posted are in the superglobal variable $_FILES not $_POST. $_FILES['file'] will contain an array
array('name' => '...', 'tmp_name' => '...', 'type' => '...', 'size' => '...');
The content will be saved to a temporary file whose name is stored in $_FILES['file']['tmp_name']
You see, you really go astray here... What you have to do is to send the XML data as a POST variable and not a file. When doing this, you can save the data to the database like you tried it, but with prepared statements, it will be something like (assuming you are using mysqli
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES (?, ?)";
$stmt = $mysqli->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param("ss", $name, $file);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
The point of using a prepared statement is this :
If the file contains a ', you get an error in the query. Also your code is vulnerable to sql injection. You need to escape the strings in the query.
I never used mysqli myself, and the code I gave looks a bit clumsy, so here's an alternative :
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('". mysqli_real_escape_string($name)."', '".mysqli_real_escape_string($file) ."')";