FormData cannot appended with File Object - php

Hi i am trying to upload image using AJAX but when i try to append FormData with my file object it didn't work here is my code
var data = new FormData();
$.each(files, function(key, value){
console.log(value);
data.append(key, value);
console.log(data);
});
and in console i got this response
File { size=1626773, type="text/comma-separated-values", name="Prepaid_Rates_01.03.2014.csv", more...}
uploadrates.js (line 17)
FormData { append=append()}
here u can see that File is shown in console but not available in data after append
i also see this type of questions but not find any proper answer that works

I'm not sure if that would work at all. Traditionally, the way to upload files with ajax is to submit the form to a hidden iframe, then give a response along the lines of:
<script type="text/javascript">window.parent.myCallback('Response Received!');</script>
So you would create a multipart form, set the target attribute to your iframe's name, and have all the fields (including the file fields) as form fields in this form, with the iframe after, e.g.
<form method="post" action="/my-upload-url" target="hidden-iframe">
Form fields here...
</form>
<iframe name="hidden-iframe"></iframe>
Then when the iframe loads after processing your form, it will immediately execute the javascript you've outputted as a response, which will call the function myCallback in your main page, so you should create that function as well:
<script type="text/javascript">
function myCallback(message) {
alert(message);
}
</script>
Altogether, your page should therefore be:
<form method="post" action="/my-upload-url" target="hidden-iframe">
Form fields here...
</form>
<iframe name="hidden-iframe"></iframe>
<script type="text/javascript">
function myCallback(message) {
alert(message);
}
</script>

there was a problem of using older jquery version file and by replacing with the latest do the job.
here is the old jquery
<script src="jquery-1.4.4.js"></script>
and the new jquery file is as:
<script src="jquery-1.11.0.min.js"></script>
i have no idea of the changes in both files but when i try the latest version it allow me to upload the file and now i prove that the latest versions are better to use and try to use the latest version;

Related

Posting variables to a php file and opening it in new window, without using forms

I am doing a small php project. In this I have one page, which gets values from MySql and display it in HTML tables. Now there is generate pdf button,which generates PDF using MPDF in another php script. I need to send HTML table source code to the page containing php script to convert it into a pdf. I have used the below code to do this.
var html= $("#tblExport").html();
window.open('pdf.php?html='+html, '_blank', 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,fullscreen=yes,status=no');
Problem of above code is that, it is using GET and hence cannot send large string values to other php file.
I have tried to do this post using below code.
$(document).ready(function(){
$("#btnExportpdf").click(function(){
var html= $("#tblExport").html();
$.ajax({
type: "POST", // Methode POST or GET
url: "pdf.php", // PHP file to processing the data
data: { "html": html } // post variables that will handetover to php
})
.done(function( msg ) { // response
console.log(msg) // data retuned from php
});
});
});
Now I am stuck here. I am able to POST parameters, but how to open the php file,to which parameters are posted in a new window.
So the issue is that I want to open a new window with PDF of HTML table, on click of generate PDF button.
Please help me out. Thanks
You may need to use a form or JS.
Here is the form method.
http://www.w3schools.com/TAgs/att_form_target.asp
<form id="pdf_form" action="pdf.php" method="post" target="_blank">
<input id="pdf_html" type="hidden" name="html" value="" />
<input type="submit" value="Get PDF">
</form>
jQuery - you still need the form above, but the submit button may be hidden or removed.
$("#btnExportpdf").click(function(){
var html= $("#tblExport").html();
$("#pdf_html").val(html);
$("#pdf_form").submit();
});

Script Execution with .load()

I have a form inside a DIV (normally the div is hidden using "display:none;")
The user open the DIV with: onclick='$("#Details").show("slow");
Fills out the form and save the data.
I don't want the entire page to be reloaded, and I need only this DIV to be reloaded
I tried:
function(data) {
$('#Detalils').load(location.href + ' #Detalils');
});
and:
$("#Detalils").load(location.href + " #Detalils, script");
and:
$('#Detalils').load(location.href + ' #Detalils', function() {
$('#script').hide();
})
where in #script I put my script
In this div I have some script, and because of the jQuery on load script execution, the script is not executed.
I cannot put the script in an external file, it must be in the page body.
Is there a way to execute the script a well?
Thanks
Your actual Javascript code should not be within the div, that is the issue. If you wish to reload the form for the user to enter new data, then use ID's on the elements within your forms and write your JQuery code outside of it or in an external file, here is a simple example :
Instead of something like :
<form>
<input type="button" onclick="alert('hello');"> Click me ! </input>
</form>
Do something like :
<form>
<input id="myButton" type="button"> Click me ! </input>
</form>
<script type="text/javascript">
$("#myButton").click(function()
{
alert('hello');
});
</script>
You will have to adapt your code to this, of course, but you don't have another choice. HTML code can be removed and added at will, but Javascript code must not be treated the same way. There are many reasons for this, but one reason is that the browser will only load the Javascript functions once, for obvious optimization reasons.
The works within my local environment. Give it a shot in yours.
The HTML:
<div id="wrapper">
Remove
Reload
<div id="Details">my details box</div>
</div>
The jQuery:
<script type="text/javascript">
function mload() {
/*LOAD IN MY EXTERNAL STUFF*/
mtarget = $('#Details'); //the element on your page, that houses your external content
mscript = 'external.js'; //the js script required for your plugin to work
mtarget.load("external.html", function(){
$.getScript(mscript, function() {
//run the plug-in options code for your external script here
});
});
//*/
}
function madjustments() {
/*ADJUST THE LOADING PROCESS*/
//remove the load request on click from your remove button
$('#mremovebtn').on("click",function(e) {
e.preventDefault();
$('#Details').children().remove();
});
//reload the request on click from your reload button
$('#mreloadbtn').on("click", function(e) {
e.preventDefault();
mload();
});
//*/
}
(function($){
mload();
madjustments();
})(jQuery);
</script>
You will obviously need 2 additional files. One called external.html and another called external.js, for my demo code to work. But you can change the naming process to whatever works for you.
Extra:
Set a class in your external html file (on the parent element), for example #external. And by default, set the CSS to display:none in the style sheet. Then when the page loads in, simply show() it in the jQuery code.

Save data to PHP / Mysql with inline edit in CKEditor

I want to use "inline edit" of the new CKEditor 4 (http://docs.ckeditor.com/#!/guide/dev_inline-section-2), but can not find any example of how to save the data with PHP / MySQL.
Can you help me?
You need some AJAX magic. Via JavaScript inside the page you get the edited HTML. Then you send it to the server where a PHP script gets it and can pass it onto MySQL.
Here is a simple test case which will show you the ropes.
Let's start with the editable HTML.
<div id='textToBeSaved' contenteditable='true'>
<p>Using the <strong>Terminal</strong> in OS X makes you all-powerful.</p>
</div>
We also need a "Save" button which will be used to start the POST event.
<button onclick='ClickToSave()'>Save</button>
Such a button could well we positioned in the CKEditor toolbar itself, but that would require more coding and I'll leave it to someone who's better at JavaScript than me.
Of course you want to include CKEditor. For my sample code I'll also make use of jQuery, which I'll use for AJAXing the results.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='CKEditor4/ckeditor.js'></script>
Now the script which will execute when you press the "Save" button. It will use CKeditor to grab the edited HTML, then jQuery to send it.
<script type='text/javascript' language='javascript'>
// <![CDATA[
function ClickToSave () {
var data = CKEDITOR.instances.textToBeSaved.getData();
$.post('save.php', {
content : data
})
}
// ]]>
This is it, you don't need anything else clientside.
On the server, you must have the PHP code which will act when the script POSTs the updated HTML. The script must be called save.php and be positioned in the same directory where the HTML is if you use my code verbatim.
My one-liner here will just save your HTML in a temporary file inside the /tmp folder. Feel free to add your MySQL magic instead.
<?php
file_put_contents('/tmp/serverside.html', $_POST['content']);
?>
This is the way I've done it in the past:
The current_page_id relates to the table row we wish to update, otherwise we wouldn't know what record we need to update.
<div id="editable">My body text</div>
<input type="hidden" name="page_id" id="current_page_id" value="10" />
<script type="text/javascript">
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('editable', {
on: {
blur: function( event ) {
var params = {
page_id: $("#current_page_id").val(),
body_text: event.editor.getData()
};
$.ajax({
url: 'php_file_to_post_to.php',
global: false,
type: "POST",
dataType: "text json",
data: params,
success: function(result) {
console.log(result);
}
});
}
}
});
</script>
The inside of your php_file_to_post_to.php PHP file you simply catch the ajax post request and update the row based off of the page_id variable which has also been posted along with the edited content.
This is how you will get text area data
CKEDITOR.instances.editor1.getData()
CKEDITOR is nothing but the object you used to create functionality.
Thanks so much for the code. Try to improve de code with file_put_contents('page.php', stripslashes($_POST['content']));
And add to the div onBlur="ClickToSave()" and now you can to delete de save button.

FileSize through javascript

I want to check the file size of the file selected by user, at the client side by using javascript.The code i am using for this is:
<script type="text/javascript">
var myFile = document.getElementById('myfile');
//binds to onchange event of the input field
myFile.addEventListener('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
</script>
But when i run the code, choose a file, nothing happpens.
Any body tell me what i am doing wrong
Your code works fine (in HTML5 browsers with the File API). Make sure that your <script> block is after the <input> element. In that jsfiddle, it's in the "load" handler.
Works for me using jquery:
http://jsfiddle.net/UUdcy/
$('#myfile').change( function() {
var fileInput = $("#myfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
$('body').append('<p>'+imgbytes+'</p>');
});​
You can't get the file size using javascript. Security in the browser prevents file system access by Javascript. You'd need to use Flash, or ActiveX or something that would be able to be granted permissions to do this I believe.
EDIT: If you are using the HTML5 File API then I guess you can do this - but as you've not indicated that anywhere I didn't assume that this was the case. I will put HTML as a tag on your post.

uploading files with jquery $.ajax and php

I desire to upload files asynchronous when the user select a file in a input file, with $.ajax. But the php that recive the call return index undefined.
The jquery code is the next:
$("#urlimatge").change(function(){
var filename = $("#urlimatge").val();
$.ajax({
type: "POST",
url: "utils/uploadtempimg.php",
enctype: 'multipart/form-data',
data: {'urlimatge' : filename },
success: function(response){
alert(response);
}
});
});
and the php that recibe the call:
$image = new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);
Thanks
you cannot pass the $_FILE from AJAX to PHP.
I would suggest use a plugin
It will make your life easier :) Here is a video tutorial to help too
You might wanna use tools like uploadify for that.
You can't upload files with AJAX, but you can use an iframe so you don't have to refresh the current page.
Many people go strait to plugins but you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Instead of using an AJAX function, have a form submit to a hidden iframe that has a load event handler attached to it so when the form is submitted, you have a callback function that actually includes the server response (the HTML of the iframe after it loads).
Example:
HTML --
<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
<input type="file" name="file" />
<input type="submit" />
</form>
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
JS --
$(function () {
$('form').on('submit', function () {
//check if the form submission is valid, if so just let it submit
//otherwise you could call `return false;` to stop the submission
});
$('#workFrame').on('load', function () {
//get the response from the server
var response = $(this).contents().find('body').html();
//you can now access the server response in the `response` variable
//this is the same as the success callback for a jQuery AJAX request
});
});

Categories