I have a form that has both text and file fields. I am trying to submit the whole thing to a php script hosted on the server, and return a validation message. My form looks like this:
<form id="ambassador" method="post" enctype="multipart/form-data">
<label for="name">Name: </label>
<input type="text" id="name"> <br />
<label for="age">Age: </label>
<input type="number" id="age"> <br />
<label for="igram">Instagram Account: </label>
<input type="text" id="igram"> <br />
<label for="photo">Photograph Upload: </label>
<input type="file" id="photo"><br />
<label for="why">Why should you represent Drip Cold Pressed Juice?</label>
<textarea id="why" width="300px"></textarea>
<button type="submit" class="btn">Apply!</button>
</form>
And my jQuery looks like:
jQuery("#ambassador").submit(function(event) {
event.preventDefault
var server = "http://getdripped.com/dev/ambassador.php";
var form = document.getElementById('#ambassador');
var formData = new FormData(form);
alert(formData);
jQuery.ajax({
url: server,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The php contains just a print_r statement for the $_FILES array and another for the $_POST array. However both returned arrays are empty.
You have two problems.
Failing to pass a form to the FormData object
document.getElementById('#ambassador');
The getElementById method takes an id but you are passing it a selector. You need to remove the #. Currently you are passing null to new FormData (because there is no matching element so gEBId returns null).
There is no successful data in the form
<input type="number" id="age">
Form controls can only be successful if they have a name attribute and none of yours do.
Once you correct the ID, you populate the form data object with all the successful controls in the form: but there aren't any.
You need to add a name attribute to each of your inputs.
I would use an iframe as the target of the form.
<form id="ambassador" method="post" enctype="multipart/form-data" target="form_iframe" >
<iframe name="form_iframe" id="form_iframe" ></iframe>
See also How to make Asynchronous(AJAX) File Upload using iframe?
Ignore the downvote, and
Set async to true!
You set the async to false. This means that your success callback won't wait for the reply and finishes therefor long before PHP answers.
Also look at this SO Question as there is an answer already if you get into more trouble.
From the jQuery Documentation:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Quentin was right about the serialize, I deleted the serialize option after further reading.
Related
I have an application for rating a service. A on the form page has inputs for comment, giving it a star etc.
I want to make it in a way that when a user clicks on a star it should send the value of the star input to a php script for processing without having to click on the submit button. I thought of using separate forms for this, however, i just want to use one form because different forms will bring the layout.
HTML Form
<form action="" method="POST">
<input type="text" name="name">
<textarea name="comment"></textarea>
<input type="radio" name="rate" value="1">
<input type="radio" name="rate" value="2">
<button type="submit" name="submit">Submit</button>
</form>
JQuery for the sending rate to php
$("input[name=rate]").change(function(event){
var rating_num = $(this).val();
$.ajax({
url: '../handlers/rating.php',
type: 'POST',
data: rating_num,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
},
success: function (data) {
alert(data);
}
});
})
rating.php
echo $_POST['rating_num'];
The output I get is "undefined index:rating_num"
The above code is just a sketch.
First of all, you can debug your $_POST variable with var_dump function.
However, the reason why you have this error is that you need to put an object in the 'data' parameter.
{
...
data: {
rating_num: rating_num
},
...
}
Also, you could use $.post instead of $.ajax. See examples in jQuery API documentation.
$.post('rating.php', {rating_num: rating_num})
.done(function(data) {
console.log(data);
});
My code is a form where it picks a file from the user, then send the data using jQuery to a PHP file where it gets the image content and displays it and in a success function: it alerts the data received from the PHP file. For example, the image received from the HTML page.
Actually, the code inserts the image into the database, but I plucked the code out and inserted a direct view of image in PHP file without inserting in the database because I wanted to make it short(database insertion code has no error: it inserts other variables provided with image and image stays blank)
Also am using my script on XAMPP localhost. So do not worry about that i am running it like file://... . All is that i can't figure out why the data aren't being passed to php file.
HTML:
<input style="border:none" type="file" id="photo" /> <br>
JavaScript:
$("#submit-form").click(function() {
var formadata = {
"photo": $("#photo").val(),
};
$.ajax({
url: './enter-registration-form.php',
data: formadata,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(val) {
if (val == "done") {
alert("Data Accepted");
} else {
alert(val);
}
}
});
});
PHP:
$i = $_FILES['photo']['name'];
//get the content of the image and then add slashes to it
$imagetmp=addslashes (file_get_contents($_FILES['photo']['tmp_name']));
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagetmp).'" style="width:100px;height:autoborder:none">';
Now I am getting this error message:
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 5
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
Warning: file_get_contents(): Filename cannot be empty in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
I can't figure out why this error is thrown.
Approach
You need to use new FormData() object.
The FormData interface provides a way to easily construct a set of
key/value pairs representing form fields and their values, which can
then be easily sent using the XMLHttpRequest.send() method. It uses
the same format a form would use if the encoding type were set to
"multipart/form-data".
So you don't actually have to declare a form tag and add inputs inside, yes it makes it easier if you have let us make a call assuming that you do not have a form tag.
Problem
The problem in your script is that your formdata is a json rather than a FormData() interface object, which uses formdataObject.append() which appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
See code below which posts email, file label and a file to a PHP page without using form tag for the inputs.
Without <form> tag
Assuming that your html looks like below without a form
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="button" name="submit" value="Stash the file!" />
Your javascript code will look like below
$(document).ready(function () {
$("input[name='submit']").on('click', function (event) {
event.preventDefault();
//START Append form data
var data = new FormData();
data.append(
'userid', $("input[name='userid']").val());
data.append(
'label', $("input[name='filelabel']").val()
);
data.append('file', $("input[name='file']")[0].files[0], 'somename.jpg');
//END append form data
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
And your file.php will look like below
<?php
print_r($_POST);
print_r($_FILES);
This should show you the file inputs and file both of them in the console when you hit the stash file button.
With <form> tag
If you have the inputs wrapped inside the form tag then your code will be changed on the following sections
Change binding of click event to form submit event.
Change button type to submit in the HTML.
Get the form object.
Use form object to initialize the FormData().
See below How your HTML will look like
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
And your javascript will look like below
$(document).ready(function () {
$("form").on('submit', function (event) {
event.preventDefault();
var form = this;
var data = new FormData(form);
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
This should work!
HTML:
<form id="my-upload-form" method="post" enctype="multipart/form-data">
<input type="file" name="required-image" />
<button> Upload </button>
</form>
JS:
$("button").click(function(e) {
/* prevent default form action */
e.preventDefault();
/* get form element */
var formElement = document.getElementById("my-upload-form");
/* collect all form data from Form element */
var formData = new FormData(formElement);
$.ajax({
url: '/path-to-form-handler.php',
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(response) {
console.log(response);
}
});
});
PHP:
<?php
/* for this example, $_FILES["required-image"] would be an array having image details */
echo $_FILES["required-image"]["name"];
echo $_FILES["required-image"]["type"];
echo $_FILES["required-image"]["tmp_name"];
echo $_FILES["required-image"]["size"];
?>
First of all insert your input file tag in a form and use enctype="multipart/formdata"
to send an image otherwise you will not able to send image
SOLUTION: I had to drop the sumbmit button and use a regular button. The rest of this code works. I also dropped the HTML form.
I'm trying to send an image + some text to my php script with ajax using formdata.
This is what i got:
$ajax_uploadImage = function (form)
{
var data = new FormData();
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
$.ajax({
url: '../php/upload_image.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('something');
}
});
}
The form in the function parameters is a normal html form, here is the form in html:
<form enctype="multipart/form-data" id="upload_image">
<label for="title">Title:</label>
<input type="text" id="title" name="title" />
<br />
<label for="comment">Comment:</label>
<input type="text" id="comment" name="comment" />
<br />
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<br />
<input type="submit" value="Upload picture" name="submit">
<hr />
</form>
The alert in success never triggers, can anyone help?
EDIT: Adding the PHP, even though it doesn't do anything:
<?php echo 'something'; ?>
Right now you are storing a jQuery object in the FormData which cannot work. Use the values of those elements instead. In case of the file input you need to use the File object in the files property of the DOM element:
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
Try adding form action like:
<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">
I have a form that's calling a Post a .php file, which i though was the basis of ajax pushing (as opposed to retrieving data with ajax). Unfortunately, my browser will always load my called .php file instead of staying on the page containing the form. I' thinking there's a specific line of code I'm forgetting somewhere. What should I be looking for?
<form id="form-upload" enctype="multipart/form-data" action="_scripts/ajax/cropImage.php" method="post" onsubmit="return checkCoords();" style="min-height:450px; position:relative;">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="ht" name="ht" />
<input type="hidden" id="wt" name="wt" />
<div style="position:absolute">
<h2>Upload a picture</h2>
<input id="input-upload" name="input-upload" type='file' onchange="readURL(this);" /><br/>
<img id="upload-preview" src="" alt="" />
<div style="position:absolute; bottom:0;">
<input type="submit" value="Upload" />
<input type="button" value="Cancel" onclick="$('#fancybox-close').trigger('click');"/>
</div>
</div>
<img id="spinner" style="position:absolute; background-color:transparent; left:49%; top:50%;" src="_images/uploads/ajax-loader.gif" height="32" width="32"/>
</form>
Seems that your understanding of AJAX is a little wrong, don't take me wrong, I suggest you to read more about it and try to implment it using Jquery libraries for Ajax. Those functions are very well documented and have great examples.
I would not use form tag while using ajax.
This is an example function you would use when use "submit" the data:
$.post("_scripts/ajax/cropImage.php", {
"y": yValue,
"x": xValue,
"h": hValue,
...
"input-upload": inputUploadValue
});
Explaining: You will send all values at the object ("y", "x", etc) to "_scripts/ajax/cropImage.php", as POST variables. You can also create a callback function, to receive data from the URL you sended those values, and validate if everything ran well.
It seems you're using the action attribute of your Form and submiting it. Show us all your related code, please. (Text before showing the code)
You can post data the same way you can retrieve data with jquery's ajax library.
See the .post() method.
You can get the contents of your input fields and then send them with ajax. If you want to keep your current form structure, you can use doSubmit(); return false; in an onsubmit event to cancel the original submit, and use your ajax method.
You are using a submit type button.
Change the type to "button", and make the onclick event something like:
onclick="sendData();"
Your sendData() function should contain the proper AJAX.
I see you are using jQuery, so just use the built-in ajax functions:
$.ajax({
url: "_scripts/ajax/cropImage.php",
context: document.body,
success: function(html){
alert(html);
}
});
$('#btnSubmit').click(function() {
// we want to store the values from the form input box, then send via ajax below
var comment = $('#comments').val();
var name = $('#Name').val();
$.ajax({
type: "POST",
url: "contactus.php",
// data: "fname="+ fname +"& lname="+ lname,
data: "name="+ name +"& comment="+ comment,
success: function(response){
$('#mail_sent').html(response);
}
});
});
I have a form that is called via the fancybox plugin login example.
Here is the code I have:
Form:
<form method="post" action="" id="events_form">
<p class="clearfix"><label for="Name">Name:</label> <input type="text" name="Name" id="Name" /></p>
<p class="clearfix"><label for="Company">Company:</label> <input type="text" name="Company" id="Company" /></p>
<p class="clearfix"><label for="Email">Email:</label> <input type="text" name="Email" id="Email" /></p>
<p class="clearfix"><label for="Tel">Tel:</label> <input type="text" name="Tel" id="Tel"/></p>
<p class="clearfix"><input type="submit" value="Submit details" /></p>
</form>
JavaScript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#event_trigger").fancybox({
'padding' : 0,
'scrolling' : 'no',
'titleShow' : false,
});
$("#events_form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/events/index.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
});
</script>
The PHP file returns and empty array. However the Firebug post tab displays the form data.
Also, I noticed that if I do
print_r($_SERVER['REQUEST_METHOD'])
This returns GET, even though I have specified POST.
$(this).serializeArray()
with the name of the form CSS id (#my-form-ID, in this example) like this:
$("#my-form-ID").serializeArray()
Hope that solves it. It worked for me. ;-D
$.ajax expects the parameter data to be an object or a string.
http://api.jquery.com/jQuery.ajax/ scroll down to data.
If you wrap your data in an object e.g. data: {array:$(this).serializeArray()} it may work. I'm not 100% sure on that though.
You are doing an AJAX request on a form submit.
Unless the AJAX request is synchronous (which I wouldn't recommend, anyway) there is a danger that your form will be submitted before there is any chance for the AJAX request will return.
In the line:
$(this).serializeArray()
$(this) is referring to the the form element you have selected in the bind method. I'm assuming this is intended