I would like to upload a file and form data with Jquery. My html;
<form id="kayit" action="" method="post" enctype="multipart/form-data">
<input type="text" name="yazi" />
<input type="file" id="resim" name="resim"/>
<a onclick="kontrolet();" id="yolla">Yolla</a>
</form>
<div id="sonuc"></div>
and my js;
function kontrolet()
{
var veriler = jQuery("#kayit").serialize();
//console.log(veriler);
jQuery.ajax({
type:'POST',
url:'form.php',
data: veriler,
processData: false,
beforeSend: function () {
jQuery("#sonuc").html("Lütfen Bekleyin....");
},
success: function(sonuc)
{
jQuery('#sonuc').html(sonuc);
}
});
}
I have get filename, but this not working. Help ?
You cant upload a file through ajax using simple javascript (one of the reasons is that javascript cannot access the file system at the moment, so it cannot read content to send it on an AJAX request).
For that kind of feature you have to use some plugin that uses action script or java. There are many available online (search ajax file upload), but in my opinion you are better off using an old fashioned POST.
I've used jQuery to upload file in the background using the AjaxUpload plugin - it builds an iFrame in the background, clones your form and submits the clone to that.
Related
I am sure there are things I haven't read out there, but every search I do just turns up purple links. My goal is to have a form that uses ajax in order to avoid page refresh and avoid submit on manual page refresh. I want to both upload a file and insert data into the database table. I actually have this part down. The problem is that the action is started on page load. I think this is because my ajax function uses #multiform).submit, but if I change that to #submit).submit then the ajax script doesn't send the data to upload.php and I just end up with a blank array being passed to upload.php.
I can make the upload work on click with a button instead of an input for the form submit. That's all without using formdata though. I need to use formdata to also upload the file. The below script does work. I just need it to work after clicking submit, and not automatically when the page loads.
As I'm learning, I'm thinking that formObj=$(this) is referring to the multiform and grabbing the objects, so when I change multiform to submit (this) doesn't work anymore. Is it possible that I just need to change that field somehow? I've been working on this non stop for weeks. I keep getting closer, but still not there. Please help me. Thank you.
my form:
<form name="multiform" id="multiform" action="upload.php" method="POST" enctype="multipart/form-data">
Name: <input type="text" name="dname" value="Ravi"/> <br/>
Age :<input type="text" name="age" value="1" /> <br/>
Image :<input type="file" name="photo" /><br/>
<input type="submit" id="submit" value="Ajax File Upload" />
</form>
my js:
jQuery(document).ready(function($) {
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData($(this)[0]);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{ alert(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
});
$("#multiform").submit(); //Submit the form
});
I figured this out by looking at it backwards. I googled how to make the form submit automatically on page load and found out that $(document).submit() makes a form submit on page load, so I took out $("#multiform").submit(); and now it works. An added note to anyone else who might find this and be working on something similar. For some reason, having an id of submit for input type submit causes the name and age variables to be ignored.
I'm a complete noob trying out my hands on Ajax and Jquery. By following an online tutorial, I successfully made a search engine using MySQL as the backend database;
<script>
$(function() {
$(".search_butn").click(function() {
// getting the value that user typed
var searchString = $("#input_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "search.php", //server-side script to db (mysql)
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
<form method="post" action="search.php">
<div id="DIV">
<input type="text" name="search" id="input_box" class='input_box'/>
<input type="submit" value="Search" class="search_butn" />
</div>
</form><br/>
<div>
<div id="searchresults"> </div>
<ul id="results" class="update">
</ul>
</div>
Now I want to go a step further by searching using a RESTful api like this one from Solr http://localhost:9090/solr/select?q=employee%3A%28james+blunt%29&wt=json&indent=true
I need someone to please show me how I can go about doing this.
To create a RESTful API, you could write some PHP code to chop down the url of the request.
You should make Apache - your webserver I suppose - redirect all URLs with a certain prefix to this PHP script.
So, say a user requests http://www.somename.com/my_api/some/shiny?suffix, you want Apache to redirect this URL to the script my_api.php, such that my_api.php can chop down the entire URL and do stuff based on that.
For Apache doing so, read up on apache mod_rewrite: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
For more detailed treatment of RESTful APIs, I can suggest this tutorial: http://www.restapitutorial.com/
As below, I am using a 'Form' and 'AJAX' to post the content of a text area to a URL within my site. I see the POST does work and posts the conetn to the server and on success I have tried to find the element on the page to append it, though it is not working.
Can you please advise?. The function success part of the call should be where I specificy the destination, though how do I append this data, put some ajax in the destination page html, on load etc?
<form id="test" onclick="submitForm();">{% csrf_token %}
<textarea id="red_content" name="content"></textarea>
<p>
<input type="submit" value="Publish" name="send">
</p>
</form>
function submitForm()
{
$.ajax({
url: "http://127.0.0.1:8000/Test/Trial",
data: $('#test'),
type: 'POST',
dataType: 'html',
success: function(data)
{
//$('.content-container5').setFocus();
$('.content-container5').html(data);
}
});
Many Thanks,
Tom
I'm not very familiar with submitting a single field via ajax (or in your case jQuery's ajax function). I did however have to do a similar function in a project I recently had.
I found this plugin:
jQuery Ajax Form Submit
It seemed to work really well. You may want to look into this for your project as well. In this case, instead of submitting your one field, the form will be submitted. This may be easier since you won't have to map the fields yourself. You can post the form to the same page and process it or post it to a given url.
Hope this helps.
Before you continue reading, trust me when I say I have read all the other posts on this subject, and none of them helped.
I am trying to add image upload functionality to my website. I want to upload the image
via an ajax post. I cannot get this working.
Here is what I have:
HTML - i have a special setup so that an image is displayed instead of a stupid button
and the text field. I am also using the onChange event to automatically submit when I have hit "OK" after selecting the image.
<form id="add-picture-form" method="POST" action="/api/upload_image/" enctype="multipart/form-data">{% csrf_token %}
<div class="thumbnails" style="width:400px;">
<label class="cabinet BrandHeader">
<input type="file" class="file" id="upload-photo" onChange="$('#add-picture-form').submit();" />
</label>
</div>
</form>
Jquery:
$('#add-picture-form').submit(function() {
//var filename = $("#upload-photo").val();
var photo = document.getElementById("upload-photo");
var file = photo.files[0];
$.ajax({
type: "POST",
url: "/api/upload_image/",
enctype: 'multipart/form-data',
data: {'file': file.getAsBinary(), 'fname' : file.fileName },
success: function(){
alert( "Data Uploaded: ");
}
});
return false;
});
Finally my django view that is hit when you post to /api/upload_image/
def ajax_upload( request ):
print request.POST
print request.FILES
return http.HttpResponse(simplejson.dumps([True]), mimetype='application/javascript')
I have tried to write the image to binary, but I cannot open that data that has written.
Why is uploading an image using javascript so hard? I am an idiot and just not using a simple solution? If so, please tell me what is the best way to use jQuery to upload an image in Django.
Try the jQuery plugins Uploadify or SWFUpload. Someone even did the Django integration for you, see: https://github.com/tstone/django-uploadify and http://blog.fogtunes.com/2009/11/howto-integrate-swfupload-with-django/.
I'm not that familiar with django but I think the issue is that uploading a file via AJAX isn't as simple as you might think.
There are several methods of getting around this, but I recommend using one that already exists. Since you are using jquery, I would recommend the jquery forms plugin: http://jquery.malsup.com/form/#getting-started
The plugin supports file uploading out of the box, and really all you'll need to do is wire it up to your form:
$('#add-picture-form').ajaxForm();
see also: How can I upload files asynchronously?
I am using this version of jQuery form plugin https://raw.github.com/malsup/form/master/jquery.form.js
getting an error on submit:
error on line form.submit();
SCRIPT87: Invalid argument. jquery.form.js, line 347 character 5
My code:
<form id="ajaxUploadForm" action="#Url.Action("Upload", "Home")%>" method="post" enctype="multipart/form-data" >
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" /></label>
<input id="ajaxUploadButton" type="submit" value="Upload" />
</fieldset>
</form>
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
// $("#ajaxUploadForm").block({ message: '<img src="/Content/themes/start/images/progress.gif" />' });
},
success: function (result) {
// $("#ajaxUploadForm").unblock();
//$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
},
error: function (xhr, textStatus, errorThrown) {
//$("#ajaxUploadForm").unblock();
//$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
I am doing this upload in side simple model dialog.
May be some one may have any ideas how ti fix that?
If the controller action that you are POSTing to is returning JSON you might need to wrap it in a <textarea> tags as explained in the documentation:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads. Please
note, however, that if there is no
file input in the form then the
request uses normal XHR to submit the
form (not an iframe). This puts the
burden on your server code to know
when to use a textarea and when not
to. If you like, you can use the
iframe option of the plugin to force
it to always use an iframe mode and
then your server can always embed the
response in a textarea.