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

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.

Related

sending form data through Jquery and AJAX is not working as expected

I have a form containing two submit buttons, i want it to update the current page as soon as i submit the form without refreshing the whole page, but the code keeps reloading the page and the page is not even updated.
HTML form
<form id="paymentForm" style="margin-left: 15%;margin-bottom: 15px;margin-top:15px;font-size: 18px;" action="#">
<input class="paymentButton" type="submit" name="COD" value="Cash on Delivery(COD)" style="background-color:#F80;color:white;height: 60px;border-radius: 5px ">
<input class="paymentButton" type="submit" name="POD" value="Paytm on Delivery(POD)" style="margin-left: 25px;background-color: #F80;color:white;height: 60px;border-radius: 5px">
Jquery and AJAX code
$(document).ready(function(){
$("#paymentForm").submit(function(e){
e.preventDefault();
var buttonpressed;
var paymentValue;
$("#paymentbutton").click(function() {
paymentValue = $(this).attr('value') ;
});
$.ajax({
url:"payment.php",
type:'POST',
data:"{
buttonValue:paymentValue;
}",
success:function(data){
getElementById('panel13').innerHTML=data;
}
});
return false;
});
});
PHP script payment.php where data is being sent
<?php
$paymentMode=""
if(isset($_POST["buttonValue"]==POD))
$paymentMode="Paytm On Delivery";
else
$paymentMode="Cash on Delivery";
echo "Your Order is placed succesfully with payment mode as" .$paymentMode;
?>
You have an syntax error in php code
$paymentMode="";
Youre mising semicolon... Next time, each time you send an ajax request. Turn on chrome dev tool -> network -> XHR to see what really haapen with your request. If request has failse. Click on request(i have red color) to see. back end error.. Hope this helpfull...
You are using getElementById, use document.getElementById instead. Hope it helps.

Knob circular progress bar with ajax

I am trying to use Knob with AJAX, and it is working, but the progress bar is not changing, only the number inside real time.
You can check it here: www.skincannon.com
The code is:
HTML:
<input id="val" type="text" value="0" /> <input type="button" value="Change" />
AJAX:
$.ajax({
type: "GET",
url: "currentitemswidth.php",
success: function(msg){
$('#val').val(msg);
}
});
And I am changing the value with ajax, but the bar won't change.
Anybody could help me? If you need further codes just tell me.
I need something like this, but I would like to change it automatically, not by hitting the Change button: http://www.jqueryajaxphp.com/dynamically-animate-jquery-knob/
Thanks
Here i have achieved your requirement with jQuery roundSlider plugin.. I think this is suitable for you, since you can easily customize the appearance and animation style of this slider.. Check the below demo:
Demo
For more details check the demos and documentation page.
Edit:
In the ajax success what value you got, you can assign that value to the slider. Like below:
$.ajax({
type: "GET",
url: "currentitemswidth.php",
success: function(msg){
$('#val').val(msg);
// use the below code to dynamically update the roundSlider value
$("#slider").roundSlider("option", "value", msg);
}
});

How can I upload files and form data with jQuery?

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.

HTML form Ajax post on Success

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.

jQuery form upload error

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.

Resources