Upload image using jquery - php

I have a working php code to upload image in the database. Is it Possible to transform it to jquery? If so, what do I need to do? I am new to jquery btw. Thanks
This code works just fine. But I need to do it in jquery.
<form action = 'upload.php' method = 'post' enctype="multipart/form-data">
<input type="file" name="image" > <br>
<input type= 'submit' value = 'Add' id = 'Add' name = 'Add'>
</form>
<?php
if(isset($_FILES['image']))
{
$target_Path = "images/";
$target_Path = $target_Path.basename($_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
$name = $_FILES['image']['name'];
}
if(isset($_POST['Add']))
{
if($_POST["Add"] == "Add")
{
$add = "Insert Into img(path) Values('$name')";
$up = mysql_query($add);
$status = "Upload success!";
print '<script type="text/javascript">';
print 'alert(" '.$status.' ")';
print '</script>';
}
}

<form action='upload.php' method='post' enctype="multipart/form-data" id="formupload">
<input type="file" name="image"/> <br>
<input type='submit' value='Add' id='Add' name='Add/>
</form>
You need to first setup a callback for the submit event of the form.
$("#formupload").on("submit", upload_image);
JQuery selectors work a lot like CSS; $("#formupload") selects the element whose id is formupload.
on is used to register a handler for an event.
Here, we are setting up a handler(the upload_image function) for the submit event of the element whose id is formupload.
Make an AJAX call to the php script.
function upload_image(event){
event = event || window.event;
// Prevent the default form action i.e. loading of a new page
if(event.preventDefault){ // W3C Variant
event.preventDefault();
}
else{ // IE < 9
event.returnValue = false;
}
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData($('#formupload')[0]),
success : function(data){
// Show success message
},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false
});
}
You can prevent the default action of form submission, which is to load the POST response, which is what the first few lines of the function is doing.
An AJAX call is made using $.ajax which is the jQuery utility for performing an AJAX call.
The url property is to be filled by that of your PHP script.
Since it is a file upload, specify the HTTP method as POST.
The data property is the payload of the POST request, which is the content of the file you are trying to upload.
You can specify the success callback using the success property, which is the function that will be called on completion of the file upload.

You can make an ajax call instead to submit a form. You can use something like this as well:
https://blueimp.github.io/jQuery-File-Upload/
Although, you still need to have your php code in order to store the file in your server

Related

Gallery delete album with ajax fails on second

I've created a gallery where the user delete an album via ajax, my problem is that when i click the "delete" button it works the first time, everything runs fine and the folder and pictures gets deleted, but when i move on to the second album and try to delete it, ajax gives me success BUT nothing gets deleted! the error: function doesnt give me an error either (in console) the ajax runs like normal...
Here is the button(form) that triggers ajax
<form action='' method='post'>
<input type='hidden' id='album' name='album' value='$albid'>
<center><input type="submit" class="javagalleryAlbumDeleteBtn" name="createAlbum" value="Delete Album"></center>
</form>
Here is the js file containing ajax
// CHECK THAT DOCUMENT IS READY
$(document).ready(function() {
// This is the button we are looking for.
$('.javagalleryAlbumDeleteBtn').click(function() {
// Get values from form
var album = $("#album").val();
// Put the vars in a string
var dataString = 'album='+album;
$.ajax({
type: "POST",
url: "../gallery/deleteAlbum.php",
data: dataString,
cache: false,
success: function(data){console.log(data);},
error: function(jqXHR, textStatus, errorThrown) {console.log(textStatus, errorThrown););
}// End success
}); // End ajax
return false; // avoid to execute the actual submit of the form.
}); // End #login click
}); // End document ready
Here is the deleteAlbum.php file
$getalbumid = $_POST['album'];
$sql = mysql_query("SELECT gallery_address FROM users_galleries WHERE gallery_id = '$getalbumid'") or die(mysql_error());
list($galaddress) = mysql_fetch_row($sql);
if(mysql_num_rows($sql)){
// delete the pictures in the DB
mysql_query("DELETE FROM pictures WHERE picalbum = '$getalbumid' AND picowner = " . $_SESSION['id'] . "")or die(mysql_error());
// delete the album from the DB
mysql_query("DELETE FROM users_galleries WHERE gallery_id = '$getalbumid' AND gallery_userid = " . $_SESSION['id'] . " LIMIT 1")or die(mysql_error());
// Function that deletes all content in folder and the folder
folderDelete($galaddress);
} // end delete
At first - your HTML page can't contain elements with same id, so in form :
<form action='' method='post'>
<input type='hidden' id='album' name='album' value='$albid'>
<center><input type="submit" class="javagalleryAlbumDeleteBtn" name="createAlbum" value="Delete Album"></center>
</form>
try to change on class. And in JS:
// Get values from form
var album = $(this).closest('form').find('.album').val();
this will help you with sending correct value of album ID to server side.
Second thing - look at MySQL injection article - http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

returning value from ajax, back to the JS function that it

here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

image upload with ajax and php

I want to use ajax to upload image.
In this module:
On clicking browse and selecting image, it will be uploaded and displayed over file field.
After adding title and description, and clicking on the button, that image will be displayed below and upper image field will be blank
You can't upload files through AJAX. You need to work with IFRAMEs or a Flash-Based uploader.
Actualy you can upload images with the ajax function in Jquery in atleast the lates version of chrome.
HTML:
<form action="/" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="image"/>
<button type="submit">
</form>
JS:
$("form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
return false;
});
This script will send a post request with the created file data to the current page through Ajax. You can change the destination obviously through changing the url parameter.
Try to use JQuery plugin for uploading an image.
May be http://www.uploadify.com/
This will give an idea how to do it.
Assuming you have a handle on the server side.. here is a small function and example on how to implement the 'iframe hack' in javascript.
html
<form name="image-upload">
<input type="file" name="image" /></br>
<button type="submit" name="upload">Upload</button>
<div id="upload-results"></div>
</form>
javascript
var fileUpload = function(form /* HTMLElement */, action /* Form Action URL */, callback /* Callback function */) {
/* vars */
var atribs = {
"target": "upload_iframe",
"action": action,
"method": "post",
"enctype": "multipart/form-data",
"encoding": "multipart/form-data"
}, iframe;
/* iframe listener */
var ilistener = function() {
var results;
listener.remove(this, 'load', ilistener);
if( 'contentDocument' in this ) {
results = this.contentDocument.body.innerHTML;
} else if ( 'contentWindow' in this ) {
results = this.contentWindow.document.body.innerHTML;
} else if ( 'document' in this ) {
results = this.document.body.innerHTML;
} else {
throw "i'm dead jim :/";
}
callback.apply(this,[results]); // call the callback, passing the results
this.parentNode.removeChild(this); // remove the iframe
};
/* create the iframe */
form.parentNode.appendChild(FragBuilder([{"tagName": "iframe","id": "upload_iframe","name": "upload_iframe","style": {"height": "0","width": "0","border": "0"}}]));
/* collect the iframe back */
iframe = By.id('upload_iframe');
/* set the form properties */
for( var attr in atribs ) {
if( attr in form ) {
form[attr] = atribs[attr];
}
}
/* attach the event listener to the iframe */
listener.add(iframe, 'load', ilistener);
/* submitting the form */
form.submit();
};
// get the form, and the results area
var form = document.forms['image-upload'], results = By.id('upload-results');
// listen for the form submit, capture it, and run the iframe upload.
listener.add(form, 'submit', function(e) {
e.preventDefault();
results.innerHTML = 'Uploading...';
fileUpload(this, 'server.php' /* really anything */, function(data) {
console.log(data);
results.innerHTML = "Uploaded!";
});
});
Please note: for simplicity purposes I have used the following utilities.
https://github.com/rlemon/FragBuilder.js DocumentFragment builder from JSON input.
https://gist.github.com/2172100 event listener, and By utility functions.
*these are both easily removed.

Categories