ajax upload file form - javascript

I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>

Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.

I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>

Related

How to submit a form with multiple fields having a same name attribute using ajax?

I have a HTML form
<html>
<head></head>
<form>
<input type="text" name="question[]" />
<input type="text" name="question[]" />
<input type="file" name="image" />
<input type="submit" name="save" />
</form>
</html>
Now to submit form with ajax
I have ajax code but its not working. It's get only one value.
$("#submit").click(function() {
var que_id = $("input[type='text'][name='question[]']").val();
$.ajax({
type: "POST",
url: "action.php",
data: {"que_id": que_id},
success: function(result) {
$("#question_wrap").html(result);
}
});
});
How do I do it?
Send form data to php file using ajax
add enctype to your form
<form id="questionForm" action="" method="post" enctype="multipart/form-data">
<input type="text" name="question[]" />
<input type="text" name="question[]" />
<input type="file" name="image" />
<input type="submit" name="save" />
</form>
Pass form data to php file using serialize
$.ajax({
url: 'action.php',
data: $("#questionForm").serialize(),
method: "post",
success: function (result) {
$("#question_wrap").html(result);
}
});
access form values in PHP file using the field name
<?php
foreach($_POST['question'] as $key => $value){
// your logic
}
$filedata= $_FILES['image'];
?>

AJAX for redirecting to external domain when submitting form

I have a form as so, which submits data to an outside domain:
<form action="https://EXTERNALdomain.com/register" id="form_register" method="POST">
<input type="text" id="first-name" name="first-name" value="" placeholder="First Name" required/>
<input type="text" id="last-name" name="last-name" value="" placeholder="Last Name" required/>
<input type="email" id="email" value="" name="email" placeholder="Email Address" required/>
<input type="password" id="password" name="password" placeholder="Password" required/>
<input type="submit" value="Create Account" />
</form>
However, I'm trying to be able to submit the form AND redirect it to a different page, also externally. So far, my attempts have been unsuccessful with AJAX.
<script type="text/javascript">
function sform() {
$.ajax({
url: "https://EXTERNALdomain.com/home",
data: $('#request').serialize(),
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e) {
alert('Error: '+e);
}
});
}
I've then been calling the form as so:
<form onsubmit="sform()" id="request">
This isn't working. I just get a long URL, and the form doesn't actually post, the page just reloads
This is because you're letting the form submit, which changes the page url and POSTs data there.
From "submit the form AND redirect it to a different page" I assume you want to submit the form to https://EXTERNALdomain.com/register and redirect to https://EXTERNALdomain.com/home. To do this, you need to use $.ajax to submit the form, them change the location on success.
function sform() {
$.ajax({
url: $('#request').attr("action"),
data: $('#request').serialize(),
type: $('#request').attr("method"),
success: function (resp) {
location.href = "https://EXTERNALdomain.com/home"; // redirect
},
error: function(e) {
alert('Error: '+e);
}
});
return false; // cancel default action
}

<keygen> element empty in POST after form submit

I have a form as follows:
<form name="signupForm" id="signupForm" method="POST" ng-submit="create()">
<input type="hidden" name="username" id="username" value="mtest">
<input type="text" placeholder="Account name" name="webid" ng-model="account.webid" ng-focus="isFocused" ng-blur="isFocused = false"><br>
<input type="text" placeholder="Full name" name="name" ng-model="account.name"><br>
<input type="text" placeholder="Email" name="email" ng-model="email"><br>
<input type="text" placeholder="Picture URL" name="pictureURL" ng-model="account.pictureURL"><br>
<keygen id="spkac" name="spkac" challenge="randomchars" keytype="rsa" form="signupForm" hidden>
<br>
<input type="submit" id="submit" value="Submit">
</form>
The data is passed to the POST as follows:
$http({
method: 'POST',
url: uri,
data: $("#signupForm").serialize(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-x509-user-cert'
},
withCredentials: true
}).
Once I submit the form to send it with a POST http request, I get the $("#signupForm").serialize() as follows:
"username=mtest&webid=mtest.databox.me%2Fprofile%2Fcard%23me&name=M+Test&email=mtest%40test.com&pictureURL=picURL&spkac="
Why is the keygen element always empty? Is there anything wrong I am doing?
Any answer is appreciated, thanks in advance.
Solved!
So preparing an HTTP Request to do that doesn't work for some reason. Instead the form action needs to be set and form submitted straight away in order to send the keygen with it. Here the solution:
in the Template the action is parametrical:
<form name="signupForm" id="signupForm" method="POST" action="{{actionUrl}}">
...
<input type="submit" id="btnSubmit" value="Submit" ng-click="completeForm()">
and the Controller sets the action and submits the form as follows:
$scope.completeForm = function () {
$scope.actionUrl = "https://" + document.getElementById("username").value + "...";
document.getElementById("signupForm").submit();
};

jQuery Ajax post to php not printing response

I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console.
Note: I am not yet collecting form data to send until I can actually get the ajax to work.
HTML:
<form id="myForm" action="process.php" method="post">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
jQuery:
$('#myForm').on('submit', function(e){e.preventDefault()});
var request = $.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
});
request.done(function(response){
console.log(response);
});
request.fail(function(){
console.log('fail');
});
PHP:
<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
Your on submit function is not doing anything. You need to have the ajax call inside of it.
Try:
jQuery(document).ready(function ($) {
$('#myForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
})
.done(function(response){
console.log(response);
})
.fail(function(){
console.log('fail');
});
});
});
Also I do not know where you are loading the JS. But you might want to wrap it in a document ready function to make sure your form exist when it is called.
Lastly there is a very nice plugin for forms that will make this easier for you. JQuery.Form.
http://malsup.com/jquery/form/

Javascript/AJAX - Sending a reverse image search request to google

so i've been trying to do a reverse image search request through ajax, and it's giving me 302 errors. looking at the firebug console, i found out that the url in the response header sent back by google is linking me to the results, but i have no idea how to access that and send another ajax query to the new location. any help would be appreciated!
this is the response header:
This is my current code:
<form action="http://images.google.com/searchbyimage/upload" id="contactForm1" method="post"
enctype="multipart/form-data">
<input type="hidden" name="image_url" id="image_url" />
<input type="hidden" name="btnG" id="btnG" value="Search" />
<input type="file" name="encoded_image" id="encoded_image" />
<input type="hidden" name="image_content" id="image_content" />
<input type="hidden" name="filename" id="filename" />
<input type="hidden" name="hl" id="hl" value="en" />
<input type="hidden" name="bih" id="bih" value="507" />
<input type="hidden" name="biw" id="biw" value="1920" />
<input type="button" name="submit" value="Submit" />
</form>
$(document).ready(function () {
$("form").bind("click", "input[type='button']", function () {
var formData = new FormData($("form")[0]);
$.ajax({
type: "post",
url: "http://images.google.com/searchbyimage/upload",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (text) {
console.log(text);
}
});
});
});
I think you should try with this:
var formData = new FormData($(this).closest("form").serialize());

Categories