How to upload image using AJAX - php

How can I send an image on my server using AJAX to a remote PHP server which is also mine? I don't know how to send and how to save using PHP. I tried to put the image in an iframe and send its content using AJAX like below but nothing happened as you might guess... It returns a message that show it is receiving some stuff and creates a very small broken image.
...
var url = "www.xyz.com/AJAX.php?content=" + document.getElementById('iframe').contentWindow.document;
...

here is a good example you could use Ajax Image Uploading

Have you had a look at jQuery yet? Its really easy doing ajax calls with it.
For your Image Uploading you might wanna have a look at jquery Forms, it has some sample codes in it here : http://www.malsup.com/jquery/form/#getting-started

Related

Download picture from database to display via JavaScript?

I am developing mobile applications, and I was thinking, if I need to download a picture from a server, I cannot actually run the PHP natively (I am using a PhoneGap type setup), so how could I download a picture from a database, run it though JavaScript and then display it to the user?
I would imagine something like:
Ajax request,
Return HTML string of binary data
Do some stuff to that?
Or
Ajax request,
Return a HTML string of reference to the picture, for example: picture1.jpg.
In JavaScript, write something like document.write <img src="http://blahh/img/"+imagePath
I'm not sure what the best way to do this is.
To my mind, the simplest way to dynamically load external pictures is to get a JSON object from a PHP script containing the picture URL (like http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID).
Server side
<?php
$pictureUrl = 'http://example.com/pictures/picture.jpg'; //You can get it with a database query
$pictureName = 'Foo';
$pictureAltText = 'Bar';
// You can do some stuff here.
// At the end of the script, write result.
echo json_encode(compact('pictureUrl', 'pictureName', 'pictureAltText'));
?>
Client side
<script type="text/javascript">
// With jQuery
$.getJSON('http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID', function(data){
console.log(data.pictureUrl, data.pictureName, pictureAltText);
var img = new Image();
img.src = data.pictureUrl;
img.setAttribute('alt', data.pictureAltText);
img.onload = function(){
// Displaying picture when download completed
$(img).appendTo('body');
}
});
</script>
If you don't use jQuery, you have to use XMLHttpRequest to get the JSON encoded response and to parse it (you can see the MDN documentation at https://developer.mozilla.org/en-US/docs/JSON).
You can do this, but not purely in JavaScript.
Since you mentioned PHP, I will go in that direction:
make table in database in which you will store all images. You need
to have some kind of image_content field and load every image in
some baseline64 encoder like:
http://www.motobit.com/util/base64-decoder-encoder.asp. And store
returned string into that image_content field.
Or you can write some script that will convert all images you want
to Base64 directly in PHP by using http://php.net/manual/en/function.base64-encode.php.
make a PHP file. For example, giveme_encoded_img.php in that file you
need to have one parameter in the URL like gimme_encoded_img.php?image_name=header_bg.
Then get image_name with $_REQUEST and do a MySQL query with that
data in the WHERE statement so that you can select an encoded image string
from the database.
After that, just print it.
When you do an Ajax request to a file above, just update the desired
image src with the response. The best way for doing this is to take the response
and get some element by id, like
var header_bg = document.getElementById('header_bg'); header_bg.src
= response;
The final HTML needs to look something like this:
img alt="Embedded Image" id="header_bg" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."
Baseline64 embedding is really good, especially if you need to embed images in emails, then a lot of email clients show them by default instead of hiding the remote images from your server.
I hope I was clear enough.
Still this is not a purely JavaScript solution.

Is there any way to get an html content/value with php?

Can i get the content or value of the tag with php?
I know i can get it with javascript:
$(function() {
$('class or id').text();
});
But i would like to get it with php, so i can send it back in another query to my sql table.
function changeContentToId(id) {
$("#spanContent").html(id); }
<?php echo "<span onclick='changeContentToId($ob->ID)'>...</span>"; ?>
<span id="spanContent"></span>
This is my code right now, any tips on how to write the top code in php?
thanks. :)
No way : PHP is server-side, and your data is on the client.
Then you have 2 alternatives : getting the information before sending it to the browser (output buffering is a good way), or after, via an AJAX call.
Hope this helps !
Why don't you send it in a 'normal' way ? Like putting the content inside a form then submit it to PHP.
Or get it using Javascript then submit it using AJAX.
PHP won't access client-side information(HTML) once it is in your client(after the content is delivered) you can use client-side manipulation(Javascript) or send it back to server then use it there.
Regards
The simple answer is you cannot do that. PHP is executed on the server before the page is rendered. JavaScript, which updates the content, is executed in the browser after the page is rendered. Hence by the time your content is ready to be read, there is no PHP any more.
The way around it would be to use AJAX to read the info with JavaScript and then send it to another PHP script.
get it with javascript and send it uing ajax to the server.
Just if you really need to, because i don't see any reason since it's generated with php the first time. so you should use the word you want before rendring the html page.

HTML 5 Drag & Drop upload with jQuery and PHP

I'm currently following this example for HTML 5 drag and drop. I am hoping to use this to upload the dropped files to a remote FTP server with a php script. However, how do my php script access these dropped files ?
With a regular web form, I can use $_FILES.. But I don't suppose I can use $_FILES for the dropped files..
On the example, the script calls handleFiles function after a drop event
function handleFiles(files) {
var file = files[0];
document.getElementById("droplabel").innerHTML = "Processing " + file.name;
var reader = new FileReader();
// init the reader event handlers
reader.onprogress = handleReaderProgress;
reader.onloadend = handleReaderLoadEnd;
// begin the read operation
reader.readAsDataURL(file);
}
I guessing that I can iterate each element of the array list, and send each element to my php script. As I've mentioned above, how can I send this element from the array list to the php script? JSON ? jQuery POST ?
I am aware that there are various jquery plugins available to achieve this, and I have downloaded a few of them... However I'm just curious to know if I can implement the same thing with this example.
I presume by upload you mean upload it in a ajax operation.
file refer to a File object, which is available for you after the user had drop the file. After that you have two options:
Read the file using FileReader, send the text in xhr as post data (not recommend as it only work with text)
Pass the object to FormData then pass the FormData object to xhr to send the file (Doesn't work with Firefox <= 3.6 though)
Check Mozilla Developer Center document for the usage of these interfaces. I have working projects that use these objects, however there are too much bridging code to be a good walk-through demo. https://github.com/timdream/html5-file-upload
Why not use an open source solution for your problem rather than re-inventing the wheel.
http://plupload.com/
Is pretty much all you will ever need. I use it and it works wonders. Also, it falls back onto html 4 form uploading when a browser cannot handle html5.

Sending iframe tag to Mysql via Jquery ajax request

-- EDIT --
Solved by using JSON dataType.
-- QUESTION --
Hello,
I am trying to send iframe video embed code to db. I finally found javascipt's escape() command and it was working if I send only the embed script. Later, I tried to add embed code after some text and it neither gives an error at ajax or mysql nor adds the post.
What is the problem here? Do you have another solution for sending embed code without corruption instead of javascript's escape()? Can I do something with php?
Thank you,
I am getting content from page with var content = escape($('#textarea').html()); and sending with ajax. If I would use JSON type, will it send without corruption?
Sample iframe:
<iframe title="YouTube video player" width="540" height="435" src="http://www.youtube.com/embed/8ImAG94lSOE?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
Solved by using JSON dataType.
The problem could indeed be caused by a special character, I am not too familiar with the escape command of JavaScript, but I do know what you can do with php, make sure your data is going through the Ajax request and try using htmlentities($string) to convert every HTML tag into its encoded version, which will allow you to store it in your database.
Also, in your Ajax request make sure of every step with your string, try using alerts to show that your string is going through or that it is being at least sent to the php file, inside the php file you can try printing or "echoing" the string to see the final result and then alert it in the Ajax request, here's a small example of it in jQuery:
$.post("ajax/edit.php", {id_poll:$('#idPoll').val(),id_css:$('#css_name').val(),css:$('#poll_description_textarea').val()},
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
In the previous example I make an Ajax request in which I send CSS classes from a textbox, inside the php file I verify certain data and in case something goes wrong I return a simple string of "invalid" or "valid" to determine the outcome, along the way in such a request you can throw in an alert or two to verify that your string is being sent since it would be difficult to see an error in your JavaScript.
This might not be too specific but I hope it helps a bit.

jquery load php file - result is not complete

I'm trying to load or better reload a DIV with content from an included php file. so the file is included in the webadmin.php from the location webadmin/pages.php. Then i alter some data in the DB through serializing.
Now I would like to reload the pages.php from the callback of the serialize POST with load();. This all works fine up until the moment the data is supposed to be displayed in the div - i believe its because the php file is loaded from a different location, so the include paths for the DB Connection etc are probably wrong...
Should I really write an extra PHP File for jquery or is there a way to tell jquery where to load it from?
Its the first time I'm doing this - so bear with me for a moment on this one... Thanks!
I guess it wont be much use, but heres the load code:
$("#right").load("webadmin/pages.php");
You can use Firebug, then open Net tab to see if there are response from the AJAX call.
I never use $.load(), instead I use $.get or $.post:
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data){
$("#right").html(data);
});
nbRandom is just to prevent caching in IE. Choose a name that not used in the pages.php
Make sure no error in Firebug, and the page structure is a valid HTML/XHTML. Some bug is occurred because imbalanced tags in page.
Is the load() function returning anything?
The script is not location dependent in terms of the DB includes, etc. Those includes are only relative to the PHP script itself. The ajax function is running client side, so imagine that it's calling the URL relative to the same place as the original page. So if your page is:
http://example.com/stuff/page.php
and you are calling the script at:
webadmin/pages.php
Then the URL the ajax load method is using is:
http://example.com/stuff/webadmin/pages.php
This is the exact same as if you are putting in an href for a link or a src for an image. If the script actually is at:
http://example.com/webadmin/pages.php
Then you need to change the load URL accordingly (same as if an image were in a lower directory) like so:
$("#right").load("../webadmin/pages.php");
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data) { $("#right").html(data); }
);
this code is including php file with using jquery

Categories