I am curious to know that is it possible to show a docx file (which is available on server) inside a div without refreshing that page (using google doc viewer API or any other possible way).
Let me clear my requirement:-
HTML+JQUERY code:
<div class="browse-flie col-md-7">
<div class="alert alert-danger" style = "display:none;"></div>
<input type="file" id="uploaddocfile">
<button name="upload" value="Upload" class="btn EditBtn uplaod_file">Upload</button>
</div>
<div id = "myid" style = "height:500px;width:600px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$('.uplaod_file').on('click', function() {
var file_data = $('#uploaddocfile').prop('files')[0];
var ext = file_data.name.split('.').pop();
if(ext == 'docx'){
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
var response = $.parseJSON(php_script_response);
if(response.status == 'error'){
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file upload failed please try again');
}
if(response.status == 'success'){
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
}
});
}else{
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file extension must be docx'); return false;
}
});
</script>
PHP code:
<?php
// A list of permitted file extensions
$allowed = array('docx');
//echo "<pre/>";print_r($_FILES); die;
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
Now:
I have simple file upload code through jquery and php (working perfectly fine).
Now what I want is, after upload file when it comes success as a response then I want to show a doc file using API to my <div id = "myid" style = "height:500px;width:600px;"></div> (without refresh)
So what I tried:
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
(link changed for security reason but docx is available on server and I am able to open it directly)
But obviously it's not going to work.
So how can I do that?
Normally you'd do :
if(response.status == 'success'){
$('#myid').load("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
Instead of .html (which does something else).
However it's unlikely to work because the document you are accessing is not one that is managed by GoogleDocs (there may be cross-origin issues), so make sure you're allowing remote requests from Google to be made.
Instead you could try
if(response.status == 'success'){
$('#myid').html("<iframe src=\"http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true\"></iframe>");
}
In case Google allows embedding of gview in iframes (though they may not).
Related
I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});
In my localhost server, with apache installed, I can upload files fine. But when I move everything to a hosting server (like Altervista.org) files doesn't upload.
Here's the html code:
<form id="fileupload" action="" method="POST">
<input id="filesupload" type="file" multiple name="files" accept=".jpg" accessKey="PDF"/>
<button id="MegaUpload" type="button" class="btn btn-primary start" onclick="conversion()">
</form>
Assuming that HTML Works well, I transfer everything in an AJAX and I can connect fine to the server.
PHP code can receive the input file as well, but when I try to do the upload, it doesn't work.
Here's PHP code:
if (isset($_FILES['fileToUpload'])) {
if (!isset($_COOKIE['users'])) {
setcookie('users', md5(time()/1234), time() + (86400), "/");
}
if (!file_exists('files/uploads/' . $_COOKIE['users'] . '/')) {
mkdir("files/uploads/" . $_COOKIE['users'], 0755);
mkdir("files/uploads/" . $_COOKIE['users'] . "/tmp", 0755);
}
$target_dir = 'files/uploads/' . $_COOKIE['users'] . '\/tmp\/';
for ($s=0; $s <= 10; $s++) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$s]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$s],
$target_file)) {
//ok
}
else{
//something wrong
}
}
}
Again: Assuming that AJAX works fine (because I tested, and server receives the files I input), why in the hosting server it doesn't work?
It creates directories perfectly fine, there are directory permissions too, as you can see, and I checked in FileZilla if every .php files is setted to '0755'.
If you can't understand what's going on, I can post the AJAX part if you wish.
Thank you.
EDIT:
I edited the PHP part, so you know is a loop.
I added the enctype='multipart/form-data' as you said but still no result.
I forgot to put the multiple part on the HTML too.
Here's the AJAX part as you asked:
$("#filesupload").change(function(evnt) {
var fd = new FormData();
for (var s = 0; s < ins; s++) {
fd.append("fileToUpload[]", document.getElementById('filesupload').files[s]);
}
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: fd,
type: 'post',
async: false,
success: function(result){
alert(result);
},
error: function(result) {
alert(result);
}
});
}
I tested with alerts and echos, and I know the servers receives the file(s), but it doesn't upload.
Create a
<?php phpinfo(); ?>
file on the hosting server and check the section file_uploads. This should be on ON.
If it is OFF or FALSE you may have no rights for a file upload. For this you should contact the admin of the hosting server. If you are the root, you can set this status to ON using this link: here
I don't have any idea to copy a file from client system to server.
Short Description
I am using upload folder dialog box to upload a multiple file from particular path.
XML file is mandatory, because i need to extract some information to process
While upload event i read all the information i need to process
$("#myInput").change(function() {
var names = [];
var formData = new FormData();
for (var i = 0; i < $(this).get(0).files.length; ++i)
{
var F_name= $(this).get(0).files[i].name;
var extension = F_name.replace(/^.*\./, '');
if(extension != "xml" && extension != "db"){
formData.append('userfiles[]', $(this).get(0).files[i], F_name);
}
else if(extension == "xml"){
//Gathering info
}} });
User interface fields are filled automatically after this process and user have to fill some more fields. While user click process button in server side i create folder and some new XML files too. Everything is fine except , copy a file from client to server.
//Jquery
$("#process_but" ).click(function() {
$.ajax({
type: "POST",
url: "Asset/PHP/function.php",
data: {action: "action1", DOI:doi, TLA:tla, STITLE:S_Title, SHEAD:S_Head, SLINK:S_Link, LTYPE:link_type, DESC:description, ATITLE:Art_title, JTitle:JOU_title, ANAME:Author_name, FSHARE:Fig_share, FNAMES:filenames, FCOUNT:filecount},
success: function(response) {
if(response == 1)
{alert("success");}
else
{alert("Something goes wrong.....");}
},
error: function() {
alert("Error");
}
});
});
//php
<?php
session_start();
$action = $_POST['action'];
if($action == "action1")
{
//what i have to do
}
?>
I'm running into an issue using move_uploaded_file, specifically that it... doesn't work.
I have an input to upload the pdf:
<div>
Upload Resources
<input type="text" id="doc-name" name="doc-name">
<input type="file" id="doc-upload" name="doc-upload" accept="application/pdf">
<button id="upload-button">Upload</button>
</div>
And some jquery that sends a POST request with that file:
$("#upload-button").click(function() {
if ($('#doc-name').val() == '') {
var formData = new FormData();
var filename = $('#doc-name').val();
var uploaded = $('#doc-upload').val().split('\\');
var path = uploaded[uploaded.length - 1];
var file = $('#doc-upload').prop('files')[0];
formData.append("functionCall", "document-upload");
formData.append("filename", filename);
formData.append("path", path);
formData.append("file", file);
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(e) {
console.log(e);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorMessage);
}
});
)};
This sends to my functions file, which is set up kind of odd (it might actually be standard practice, I've just never seen it like this) in that it's one big switch statement; which case gets run is dependent on the functionCall variable passed in. So here is the function code for that specific case statement:
.
.
.
case "doc-upload":
$filename = $_POST['filename'];
$path = $_POST['path'];
$file = $_FILES['file'];
$uploadQuery = "INSERT INTO uploads (filename, path) VALUES ('$filename', '$path')";
$upload = mysql_query($uploadQuery);
if (move_uploaded_file($_FILES['file']['tmp_name'], 'test/' . $_FILES['files']['name'])) {
echo 'yay';
} else {
echo 'such is life';
}
Everything above the move_uploaded_file line works great, but I keep getting the 'such is life' line returned, and the transferred file does not show up in 'test/'. I know both the test folder and uploaded file are present thanks to a file_exists check. Any ideas about what I might have done wrong?
I am having trouble uploading a picture file via AJAX.
Web:
<div>
<form id="birdi_image_form">
<input type="file" name="birdi_image" id="birdi_image" ></input>
</form>
<input type="text" name="species"></input>
<textarea name="comments"></textarea>
</div>
<div id="debug"></div>
<script type="text/javascript">
jQuery(function($){
$('#birdi_image').change(function(){
var ima = new FormData($('#birdi_image_form')[0]);
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
});
});
</script>
/bird/bird_scripts/fu.php:
<?php
$imagedir = '/images';
$tmpfname = tempnam($imagedir, "b_");
echo var_dump($_POST);
if (move_uploaded_file($_FILES['birdi_image']['tmp_name'], $tmpfname)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
?>
From looking around online I was expecting to find contents in my $_FILES variable, but this is empty. Dumping out the $_POST var to the screen like in the example gives me the following. $_POST['birdi_image'] gives me NULL.
array(68) { ["------WebKitFormBoundaryYCAoI8shwgBavjJP
Content-Disposition:_form-data;_name"]=> string(339) ""birdi_image";
filename="test.jpg" Content-Type: image/jpeg ����JFIFdd��
ExifMMbj(1r2��i��B#'B#'Adobe Photoshop
CS2 Windows2008:06:24 11:11:48��b�g"
["?o��(�ci�\�R��Μꟑ���]T��z���"]=> string(82) "���
f�zߠ����i���/��v��E~��[,�Y
�s�������1l�G����-���߿�enu'=�v�z���=?Ҳ���"
["�{��<o��ӗ�M��ysnʨo87~;l���۔�"]=> string(172) "�<��t�2~���O�S
�����t���㵺C�}E������}��I�d]c���y}#�����C,�Z��־��V��ynʿ��?�g�*����o��ٌ�.}�y����}��z����w^�]�m�u������z>�37�_C긵��K𭪣�Y-{��뺷��M���ul��Y�"
["c�yhHp����"]=> string(152)
"��[-���1�]��|�����۽Q�\�e���o�~��g������u�.���A��t�]�3�W�ד��b���}>�����%��K���Ѳ�3���zX��qZ��}u��sc�
���N� ^-w�7���\r� ����c��=?δX�j" ["C�uw���-��"]=> string(57)
"���m��w��������ѩ���������k��r����m�t�62rIk���m�ߗV��}" ["�"]=>
string(384)
"!�<��B���6*�c��劷Q���uF*��U��������ď,�y{R���������E%���Q����5.��IE���N�����Ο�̿4~R��...............Upload failed.
I have uploaded files before by using a complete form submit. This is the first time I am trying to do it with AJAX. It looks like the data is getting to the server, but I can't seem to make any sense of it from the server side. As you can see in the code I expected $_FILES['birdi_image'] to exist but it doesn't. Am I doing something completely wrong?
Thanks
You have to set the content type to false, otherwise jQuery will set one(the wrong one) for you
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
contentType: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
I struggled with this also - it's just not as easy as it should be. I finally found a guy who did it right, and studied his code.
Ravi Kusuma's jQuery File Upload
In the end, because Kusuma wrote a plugin, I just used his code/plugin. Why re-invent the wheel? He's got everything solved, right down to sending extra data along with the uploaded file.