I'm using this code to upload multiple files to imgur at once but its not working. It doesn't even trigger at all;
<form action="imgur.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="file[]" type="file" multiple="multiple" onchange="upload(this.files[0])" />
</form>
<?php
foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
{
?>
<script type="text/javascript">
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); }
function upload(file) {
if (!file || !file.type.match(/image.*/)) return;
document.body.className = "uploading";
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.imgur.com/3/image.json");
xhr.onload = function() {
var code = JSON.parse(xhr.responseText).data.link + '\n';
var editor = eval('opener.' + 'clickableEditor');
editor.performInsert(code);
javascript:window.close()
}
xhr.setRequestHeader('Authorization', 'Client-ID [MY-CLIENT-ID]');
xhr.send(fd);
}
</script>
<?php
}
}
?>
The file name this code is pasted is named as imgur.php
Please help!
Related
I need help with my project, i have to do an 'drag n drop' zone, and, when the image is droped, it must be saved on the server (via PHP, which I succeeded), but also appear on the HTML thanks to the response from AJAX via PHP. I don't know what to do anymore, here is some code bugs. Each time I see the JS alert announces: 'An exception is produced: undefined'. I don't use Jquery or anyting else, it's just vanilla PHP and Javascript, Thanks for your help
Sorry for my bad English, I'm french :)
my code :
<body onload="init()" >
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>Drop file here</p>
<p>or</p>
<p><input type="button" value="Select File" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div> <br>
<img id = "imageSource" src="uploads/"/>
<script type="text/javascript">
var fileobj;
var url = "ajax.php";
function upload_file(event) {
event.preventDefault();
var target = document.getElementById ("drop_file_zone");
for (var i = 0; i < 1; i++) {
var fileobj = event.dataTransfer.files[i];
ajax_file_upload(fileobj);
}}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function init() {
request = new XMLHttpRequest();
var x = document.getElementById("imageSource");
}
function prepareData() {
let url = "ajax.php";
makeRequest( url, fileobj );
}
function ajax_file_upload(file_obj) {
request.onreadystatechange = alertContents;
var formData = new FormData();
formData.append('file', file_obj);
request.open('POST', url)
request.send(formData)
}
function alertContents() {
try {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var reponse = JSON.parse( request.reponseText);
x.setAttribute("src", 'uploads' + reponse.text);
//document.getElementById("imageSource").src = reponse.text;
} else {
alert("Un problème est survenu au cours de la requête.");
}
}
}
catch( e ) {
alert("Une exception s’est produite : " + event.description);
}
}
</script>
</body>
</html>
And my PHP
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'. $_FILES['file']['name']);
$test = '{ "text":"uploads/'.$_FILES['file']['name'].'"}';
echo $_FILES['file']['name'] ;
I am trying to send both form data and a POST variable and I have no idea how to do it. I've tried to do this below:
const formthing = document.getElementById("theform");
function submitfunc(e){
e.preventDefault();
const thing = new XMLHttpRequest();
thing.open("POST", "edit.inc.php", true);
thing.onreadystatechange = function(){
if (thing.readyState == 4 && thing.status == 200){
var message = thing.responseText;
$("#theform").html(message);
}
}
var videoid = "watever";
thing.send(new FormData(formthing), "videoid="+videoid);
}
But it does not work as the php script returns "jo"
<?php
if (isset($_POST['videoid']){
}
else{
echo "jo"
}
?>
When I take a look in network it only looks like it is passing the form:
what I see
If anyone has any ideas, feel free to let me know! If anything needs to be made clear, please ask.
HTML:
<form id="my-form" action="/" method="post">
<input type="text" name="videoid"><input type="submit" value="Submit">
</form>
<div id="output"></div>
JS:
let myForm = document.querySelector( "#my-form" );
let output = document.querySelector( "#output" );
myForm.addEventListener( "submit", function(e) {
e.preventDefault();
let formData = new FormData( myForm );
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200 ) {
output.innerHTML = this.responseText;
}
}
xhr.open( "POST", "edit.inc.php" );
xhr.send( formData );
});
This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}
See the solution at the bottom.
So I obtain a Blob of a .jpg or .png and it stores it on the server I obtain a blob of a psd and it does nothing shows an error the error is "aborted" in firebug. Why does this happen?
Note this works on localhost, but not on live server.
var xxx = 0;
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.open('POST', 'fileupload.php', true);
xhr.onload = function(e) {};
xhr.setRequestHeader ("enctype", "multipart/form-data");
xhr.send(blobOrFile);
xhr.onreadystatechange = function(a) {
//alert("In upload()");
if(xhr.readyState == 4) {
xxx = 0;
}
if(xhr.readyState == 0 || xhr.readyState == 1 || xhr.readyState == 2 || xhr.readyState == 3) {
xxx = 1;
}
};
}
$(document).on("change", "#userfile", (function(f){
var blob = this.files[0];
upload(blob);
}));
The Form
<form action="fileupload.php" method="POST" id="myForm" enctype="multipart/form-data">
<input type="hidden" value="<?php echo ini_get("session.upload_progress.name"); ?>" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile" id="userfile"><br>
<input type="button" id="but" value="Start Upload">
</form>
The file the js xhr posts to
<?php
var_dump($HTTP_RAW_POST_DATA);
$a = fopen("a.psd", "a+b");
fwrite($a,$HTTP_RAW_POST_DATA);
var_dump($_POST);
var_dump($_FILES);
fclose($a);
exit();
?>
The Solution
The file was being rejected due the server accepting only certain content types.
var fd = new FormData();
fd.append( 'file', blobOrFile);
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.open('POST', 'fileupload.php', true);
xhr.onload = function(e) {};
xhr.setRequestHeader ("enctype", "multipart/form-data");
xhr.send(fd);
xhr.onreadystatechange = function(a) {
//alert("In upload()");
if(xhr.readyState == 4) {
xxx = 0;
}
if(xhr.readyState == 0 || xhr.readyState == 1 || xhr.readyState == 2 || xhr.readyState == 3) {
xxx = 1;
}
};
This is pre-pended to the file when sent using the FormData api.
Content-Disposition: form-data; name="file"; filename="a.psd"
Content-Type: application/octet-stream
Im trying to retrieve users from Instagram API whose names contain the certain word from a JSON file , by using this jQuery
I had to make a PHP file as a server in my local host i named it ' get_info.php' and it return an Array of elements
but for some reason I can't seem to display the output after manuplating the data :(
I'm new to Ajax and JSON, could you possibly help me find the error in my code?
here's my JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var jsonObj ;
var q = document.getElementById('keyword').value;
ajaxRequest.open('POST', 'get_info.php?keyword='+ q , true);
// callback function to handle the server response
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
if ((ajaxRequest.status >= 200 && ajaxRequest.status < 300) || ajaxRequest.status === 304) {
var jsonObj = ajaxRequest.responseText;
jsonStr = JSON.parse( jsonObj );
}
}
}
$(document).ready(function () {
$("#submit").click(function(){
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
$.each( jsonStr.data , function(index, element) {
var res ;
res += '<img src="'+element.username+'"/>';
res += '<img src="'+element.profile_picture+'"/>';
});
$("#photos").html(res);
}
});
});
});
}
</script>
The HTML only has these tags.
<form id="form" method="POST" onclick="ajaxFunction();" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>
To avoid confusion, jquery ajax is enough
<script>
$(document).ready(function () {
var q = document.getElementById('keyword').value;
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
var element = jsonStr.data;
var res ;
for(var i = 0; i<element.length;i++) {
res += '<img src="'+element[i].username+'"/>';
res += '<img src="'+element[i].profile_picture+'"/>';
}
$("#photos").html(res);
}
});
});
});
</script>
Remove the onclick from form
<form id="form" method="POST" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>
Check and let me know what you are getting in the console
<?php
//Get data from instagram api
$keyword = $_GET['keyword'];
if(!isset($_GET['count'])) $count = 20;
else $count = $_GET['count'];
//Query need client_id or access_token
$query = array(
'client_id' => '',
'count' => $count
);
$url = 'https://api.instagram.com/v1/users/search?q='.$keyword.'&'.http_build_query($query);
try {
$curl_connection = curl_init($url);
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
//Data are stored in $data
$data = curl_exec($curl_connection);
curl_close($curl_connection);
echo $data;
} catch(Exception $e) {
return $e->getMessage();
}
?>