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'] ;
Related
Good evening, I am a beginner, I am on an application where the client has to download one of the xml files, but when the file is in local folder it downloads it and when it is elsewhere, it says:
GET https://localhost/dossier/data.xml 404 (Not Found).
How to make it accept the file no matter where it is?
This is the code:
<form id="parcourir">
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">Parcourir</button> <br>
<span id="custom-text">Aucun fichier selectionné</span>
</form>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
})
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
console.log(location.href);
console.log(customTxt.innerHTML);
myFunction(this);
} else {
customTxt.innerHTML = "no file choosen yet";
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", customTxt.innerHTML, true);
xhttp.onload = (response) => {
console.log(xhttp.response);
}
xhttp.send();
})
function myFunction(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
}
</script>
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);
}
I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>
something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});
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();
}
?>
I have an expensive form action that builds a zip file on the server and returns it to the browser.
<form action='/download' method='post'>
<input type='submit' value='download'/>
</form>
I want to block the page on click of the button so that the user doesn't repeatably hit the button.
However I want to unblock the page after the form returns.
How can trigger an event on successful completion of the form?
(I know I can trigger this by changing the form to be an ajax submission but then the save file dialog does not appear...)
Any suggestions?
Thanks
One way you could handle this without using AJAX could be submitting the content of the form to an iframe element. If you attach an onsubmit function to the form that disables further submissions and attach an onload function to the iframe, you should be able to disable the user from submitting the form multiple times.
Example HTML:
<form action="/download" method="post" target="downloadFrame" onsubmit="return downloadFile();">
<input type="submit" value="download" />
</form>
<iframe style="width: 0px; height: 0px;" scrolling="no" frameborder="0" border="0" name="downloadFrame" onload="downloadComplete();"></iframe>
Example Javascript:
var downloading = false;
function downloadFile() {
var isDownloading = downloading;
downloading = true;
return !isDownloading;
}
function downloadComplete() {
downloading = false;
}
It appears no one has yet found a way to detect the post return in the browser itself, but there is another possibility using AJAX. It is a bit more involved though:
<script type="text/javascript">
$(function () {
$('#submitbtn').click (function () {
window.setTimeout (dldone, 100);
return true;
});
function dldone () {
$.get ("/downloadstatus?rand="+$('#rand').val (), function (data) {
if (data == 'done') {
// data generation finished, do something
} else {
window.setTimeout (dldone, 100);
}
});
}
});
</script>
<form action="/generatedata" method="post">
<input type="hidden" id="rand" value="[RANDOMVALUE]">
<input type="submit" id="submitbtn" value="Download Data">
</form>
On the server, you would have to do some inter-process-communication to signal when the data generation is done. Since I already have a database, I did it like this:
public function downloadstatusAction () {
if ($this->db->fetchOne ("SELECT rand FROM dlstatus WHERE rand = ?", (int) $_GET["rand"])) {
$db->delete ("dlstatus", array ("rand = ?" => (int) $_GET["rand"]));
print "done";
} else {
print "loading";
}
}
public function generatedataAction () {
// generate data
$this->db->insert ("dlstatus", array ("rand" => (int) $_POST["rand"]));
// output data
}
I am sure there are more elegant ways to do this, but you get the idea. This appears to work fine in all browsers I tested.
I used this:
function generatePdfZipViaWS_ajax(theUrl) {
//=========================
// testé avec Chrome 37.0.2062.124 m, Firefox 32.0.3
// ça block avec IE9 à cause du xmlHttp.overrideMimeType
//=========================
var xmlHttp = new XMLHttpRequest();
var alert = document.getElementById("alertError");
block_UI();
var url = "undefined";
xmlHttp.open("GET", theUrl, true);
xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlHttp.overrideMimeType("application/octet-stream");
xmlHttp.responseType = "blob";
xmlHttp.onload = function(oEvent) {
if (xmlHttp.status == 200) {
deblock_UI();
// a mettre apres un certain temps: window.URL.revokeObjectURL(url);
} else {
alert.style.display = "block";
deblock_UI();
// console.log("Error " + xmlHttp.status + " occurred downloading your file.<br \/>");
}
};
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == xmlHttp.DONE) {
if (xmlHttp.status == 200) {
var contentDisposition = xmlHttp.getResponseHeader("Content-Disposition");
var type = xmlHttp.getResponseHeader("Content-Type");
var reponseType = xmlHttp.responseType;
var pos1 = contentDisposition.indexOf("archive");
var pos2 = contentDisposition.lastIndexOf(".zip") + 4;
var fileName = contentDisposition.substring(pos1, pos2);
if (fileName === null) {
fileName = "archivexxxxxxxxxxxxxx.zip";
}
console.log("fileName:" + fileName);
var blob = xmlHttp.response;
url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.style = "display: none";
a.href = url;
a.download = fileName;
a.type = type;
document.body.appendChild(a);
a.click();
//a.delete();
deblock_UI();
} else {
var msg =" Une erreur " + xmlHttp.status +" est apparue pendant que votre demande était traitée.\n"
msg = msg + "Merci de réessayer plus tard!";
alert.innerHTML = msg;
alert.style.display = "block";
deblock_UI();
console.log(msg);
}
}
};
xmlHttp.send();
}
I don't have time to write a proper answer right now, but since nobody else has a good answer, I think a "Mutation Observer" would work... https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver