HTML form Ajax post on Success - ajax

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.

Related

php post form max input vars strange behaviour

I am posting only 2 variables. If I do a direct POST using the form below it works.
<form action="http://someapi/post_html" method="post" enctype="multipart/form-data">
<input type="text" name="name" >
<textarea name="htmltemplate"> a html template of 3000 characters
</textarea>
<button type="submit">Submit</button>
</form>
When I use ajax to post the data I actually get a response back from the server max_input_vars limit of 1000 exceeded. How is it possible when I'm only sending 2 variables using ajax that I get that message?
I also tried using curl to do a POST and ended up receiving the same message.
$('form.ajax').on('submit',function() {
var formData = $('form.ajax').serialize();
formData += CKEDITOR.instances.textboxwyswygs.getData();
event.preventDefault();
$.ajax({
url: "http://someapi/post_html",
method:"POST",
data: formData,
success: function(response){
console.log(response);
}
})
});
Your formData looks broken - serialize() returns a JSON string and the CKEditor getData() returns a string of HTML.
Try this: synchronize the CKEditor value into the form before calling serialize and then your JSON will be correct. Try to console.log(formData) to check the formData before sending. So submitting the form without the syncrhonziation doesn't actually send the CKE content at all. This should be checked server-side to see what input it is getting.
Also the value of the ajax functions data member is expected to be correct JSON and servers might handle it in weird ways.
Other issues: $('form.ajax') does not actually target your HTML. Is this a correct example?
The event variable looks undefined, try naming it e and adding it as a parameter to .on('submit',function(e){..}.
You don't show the code where you actually replace the textarea with a CKEditor, it would be useful to see.

form data moves through ajax on page load instead of on submit

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.

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How do I render a view after POSTing data via AJAX?

I've built an app that works, and uses forms to submit data. Once submitted, the view then redirects back to display the change. Cool. Django 101. Now, instead of using forms, I'm using Ajax to submit the data via a POST call. This successfully saves the data to the database.
Now, the difficult (or maybe not, just hard to find) part is whether or not it's possible to tell Django to add the new item that has been submitted (via Ajax) to the current page, without a page refresh. At the moment, my app saves the data, and the item shows up on the page after a refresh, but this obviously isn't the required result.
If possible, I'd like to use exactly the same view and templates I'm using at the moment - essentially I'd like to know if there's a way to replace a normal HTTP request (which causes page refresh) with an Ajax call, and get the same result (using jQuery). I've hacked away at this for most of today, so any help would be appreciated, before I pull all of my hair out.
I had a very similar issue and this is how I got it working...
in views.py
from django.utils import simplejson
...
ctx = {some data to be returned to the page}
if ajax == True:
return HttpResponse(simplejson.dumps(ctx), mimetype='json')
then in the javascript
jQuery.ajax({
target: '#id_to_be_updated',
type: "POST",
url: "/",
dataType: 'json',
contentType: "text/javascript; charset=\"utf-8\"",
data: {
'foo':foo,
'bar':bar,
},
success: function(data){
$("#id_to_be_updated").append(data.foo);
}
});
Here's how I did it:
The page that has the form includes the form like so
contact.html
{% include "contact_form.html" %}
This way it's reusable.
Next I setup my view code (this view code assumes the contact form needs to be save to the db, hence the CreateView):
class ContactView(CreateView):
http_method_names = ['post']
template_name = "contact_form.html"
form_class = ContactForm
success_url = "contact_form_succes.html"
There are a few things to note here,
This view only accepts pots methods, because the form will be received through the contact.html page. For this view I've setup another template which is what we included in contact.html, the bare form.
contact_form.html
<form method="POST" action="/contact">{% crsf_token %}
{{ form.as_p }}
</form>
Now add the javascript to the contact.html page:
$("body").on("submit", 'form', function(event) {
event.preventDefault();
$("#contact").load($(this).attr("action"),
$(this).serializeArray(),
function(responseText, responseStatus) {
// response callback
});
});
This POSTS the form to the ContactView and replaces whatever is in between #contact, which is our form. You could not use jquery's .load function to achieve some what more fancy replacement of the html.
This code is based on an existing working project, but slightly modified to make explaining what happens easier.

Uploading Image Using JQuery And Django

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?

Resources