POST an image to PHP in AJAX - php

I would like to send an image to a php file using AJAX.
Here's my JS code:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: "img=" + img
})
And That's my PHP
<?php
if ( !empty( $_POST["img"] ) )
{
move_uploaded_file( $_POST["img"], "image.png" );
}
?>
but it doen't work.
I also tried to replace move_uploaded_file by imagepng or imagejpg but still no result.
How can I save the image on my server ?
Thanks

If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into four simple steps, that basically look like this:
Look for //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.
On the Hayageek web page, study the upload.php example on the Server tab.
Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code -
Click on Image Example

If your sending your data using a post,
The data property should be a json:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: {img: img}
})

Instead of sending the image, the right approach would be to send image in base64 encoded format. On the server side you'll have to decode the base 64 encoded string and save as an image. Follow this link to get a better insight on how to send encoded image.

Related

XAMPP PHP file works but no result?

I have installed XAMPP to run PHP files on my computer, here is my PHP file I am attempting to execute
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Here is my basic HTML file
<html land="en">
<head>
<meta carset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css";
</head>
<body>
<!-- Document Ready Event -->
<input id="text" type="text" /><input id="submit" type="button" value="Submit" />
<div id="feedback"></div>
<script src="../jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</body>
</html>
And here is my JS file
//Pass a value to a PHP file and taking the contents and showing the contents
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'C:/xampp/htdocs/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
When the button is clicked Chrome tells me the this.
Header is
Request URL:file:///C:/xampp/htdocs/amit/reverse.php?input=Hello
Query String Parametersview sourceview URL encoded
input:Hello
and the Response is
<?php
if(isset($_GET['input']))
{
$string = $_GET['input'];
echo strrev($string);
}
?>
Now I have put a different file on my XAMPP PHP side and it works fine, but this one just doesn't response, can anyone see what I am doing wrong at all?
You need to pass the files to your webserver -- make the GET request to a URI on your web server instead of making the request to a file on your computer.
So, change the line:
C:/xampp/htdocs/amit/reverse.php
to
http://localhost/amit/reverse.php
Alternatively, if all your files are in the same directory with a structure as follows:
-- htdocs
- amit
- <somefile>.html
- script.js
- style.css
- reverse.php
Then, you could simply use reverse.php instead of specifying the full path.
Full code as an example:
$('#submit').click( function()
{
var text = $('#text').val();
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
});
You need to get the file through a request to your XAMPP server. Try something like
$.get( 'http://localhost/amit/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Use relative path instead of local path on your-drive. Just type the filename (if filename is in root-directory). Try not to use absolute paths (like http://localhost/reverse.php) because then you would have to change it when uploading/changing it to another server and that is not a sustainable solution.
$.get( '/reverse.php', { 'input': text }, function( data )
{
$('#feedback').text( data );
});
Secondly, I would recommend using other variable names. I think you're getting problems using text a variable because text() is function in jQuery.
Try:
var textOfElement = $('#text').val();
$.get( '/reverse.php', { 'input': textOfElement }, function( data )
{
$('#feedback').text( data );
});
An in some cases it's fine to be generic about naming, but input and text is far to genereic. Those names doesn't say a bit about the actual context.

YUI 3 Uploader isuse in IE

I am using YUI 3 Uploader.
I take this example from given reference url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
I have IE.8 version.
I have created a php file say test.php and written the script from the given url as
given below:
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
<script>
YUI({filter:"raw"}).use('uploader', function(Y) {
Y.one("#overallProgress").set("text", "Uploader type: " + Y.Uploader.TYPE);
if (Y.Uploader.TYPE != "none" && !Y.UA.ios) {
var uploader =
new Y.Uploader({width: "250px",
height: "35px",
multipleFiles: true,
swfURL: "http://localhost.com /test/flashuploader.swf?t=" + Math.random(),
uploadURL: "http://localhost.com/test/test.php",
simLimit: 2,
withCredentials: false
});
});
When I open this page in the IE, nothing happens, no file dialog box opens to select file.
If anyone has already fixed this issue, please suggest me how can i solve?
Thanks,
I have used all source code from below url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
and
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
to create instance the uploader.
We need to just replace another version file of yui-min.js file as below
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
Apart from js file we need to change these
swfUrl: http://mudomain.com/test/flashuploader.swf
UploadeUrl: http://mudomain.com/test/uploader.php
To Upload file on the server, just write the script in the given above page in
the uploadUrl "uploader.php" as
<?php
$uploadedPath = 'Uploaded_Files/';
foreach ($_FILES as $fieldName => $file) {
move_uploaded_file($file['tmp_name'], $uploadedPath.$file['name']);
}
?>
Now you will see all selected files will be uploaded.
But there is limitation in the IE, We can upload 1 to 5 files at a time.

Get value from remote php server in javascript

I have two sites, site A is just html and javascript, and site B has php. What I need is to get variables from site B in site A.
EX:
site A is like
<html>
<head>
<script>
//this script has to get the values from siteB
</script>
</head>
<body>
<div><!-- here i will do something with the data of site B --></div>
</body>
</html>
Site b is like:
<?php
var1= "something";
var2= "somethingElse";
?>
I was thinking to use JSON or Ajax but i do not understand exactly how.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "filename.html",
dataType: "json",
success: function(data) {
// data will contain var1 and var2
},
error: function(data) {
alert("Problem - perhaps malformed JSON?");
}
});
});
and change your PHP file to be something like:
{
"var1" : "something",
"var2" : "somethingElse"
}
Confirmed to work.
Make sure that your file is a well-formed JSON, otherwise "success" won't be fire.
Note - I am implying usage of JQuery here. Your HTML file should include:
<script type="txt/javascript" src="jquery-1.8b1.js"></script>
File B
<?php
$array[var1] = 'Something';
$array[var2] = 'else';
echo json_encode( $array );
File A (jQuery)
$.getJSON( $( 'file.php', function( data ) {
$( 'div' ).html( data.var1 + ' ' + data.var2 );
}
Edited -- As mentioned, can't do this cross domain without doing some other measures.
Javascript cannot use ajax cross site, for security reasons. The only way to make this happen is to have but one php file on site A that can redirect.
<?php echo file_get_contents($_GET["url"]); ?>
And the javascript can call the url:
/redir.php?url=http://siteb.com/valuetoget.php
There is no way that I know of to do this with no php on the calling website.

jQuery/JavaScript ajax call to pass variables onClick of div

I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>

AJAX Post to self in PHP

I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});

Categories