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

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.

Related

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.

Ajax html response to div

Hi I am printing the ajax html response to div element and giving radio input option to select the file. after selecting the specific file the another div should show the message. but the ajax html response is not working
Jquery script:
$(document).ready(function()
{
$('#upload').ajaxForm({
beforeSubmit: function() {
$('#Analysis').show();
$('#Content_column').hide();
$('#file_list').show();
$('#trait').show();
$('#trait').html('Submitting...');
},
success: function(data) {
var $out = $('#file_list');
$out.html('&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFile list:');
$out.append('<div id="list">');
$('#list').html(data);
$out.append('</div>');
}
});
});
The output of this script is
<ul class="php-file-tree"><li class="pft-directory">Genotypic<ul><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/jquery.txt" />jquery.txt<br><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/marker.csv" />marker.csv<br></ul></li><li class="pft-directory">Other</li><li class="pft-directory">Penotypic<ul><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/namPheno.csv" />namPheno.csv<br><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/perl.pl" />perl.pl<br></ul></li></ul>
Jquery script:
$('#Penotypic').click(function() {
var $out1 = $('#trait');
$('#trait').show();
$out1.append('Submitted...');
});
this is not showing anything in the div trait. may be the html response is loading as a tesxt so the #Penotypic is not recognised. please help me to fix this.
Thanku
You have many inputs of id="Penotypic". Make every id unique or use classes as function trigger.
I wouldn't use "/" in the name attribute. See: http://www.w3.org/TR/html401/types.html#type-name
Then try if your ajax script does work. If it doesn't work, try if it works from static page (don't use your first jQuery script, but it's output as a static form). You probably need to bind your event trigger. Use jQuery's on().

Strange issue with ajax POST

I have this html page with the form
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
</form>
And this is my javascript function to do the POST call
function post_comment(event,item_id)
{
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}}
Backend is done using Django and this is the return statement
data=simplejson.dumps(data)
return HttpResponse(data, mimetype='application/json')
The referral url is say "/xyz".
The thing is, after the form gets submitted, it is being automatically redirect to the "/status_comment/save" page instead of remaining on the same page.
I tried the get method and it works fine but not the POST method.
I tried debugging it, so changed the url in post call to the referral url, then it refreshs the page instead of doing nothing.
Also the alert() command inside the function above doesnt work, so its probably not being entered into.
Interesting thing I have noticed, when looking at the web developer console, the Initiator for the POST call in this page is being displayed as "Other" while the initiator for GET call and POST call (in other pages, where its working) is "jquery-1.8.0.min.js:2"
Any thoughts? Thanks...
First you really shouldn't try to capture the enter if you can avoid it. Use the submit binding. It makes everything more obvious and easier for your fellow developers (I bet I am not the only one who thought "What the heck is KeyCode 13?").
I'm wondering if perhaps being more explicit might help. Have you tried calling preventDefault and stopImmediatePropagation?
$('#form1').submit(function(evt) {
evt.preventDefault();
evt.stopImmediatePropagation();
// serialize and be AJAXy yada yada yada
If that doesn't work, or for some reason you prefer to handle capturing enter on your own, then you might want to have the above code in addition to your keydown handler. So it would be:
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
...
$('#form1').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function post_comment(event,item_id)
{
event.preventDefault();
event.stopImmediatePropagation();
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}
}
Start by getting rid of the onkeydown attribute from the input:
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" />
</form>
And then simply subscribe to the .submit() event of this form using jquery and perform the AJAX request in there. Don't forget to return false from it to ensure that the default action is canceled and the browser stays on the same page:
$('#form1').submit(function() {
var str = $(this).serialize(); // Gets all the filled details
$.post(this.action, str, function(data) {
alert(data);
});
return false; // <!-- that's the important part
});

Ajax login form - browsers won't save password

I have Ajax login form, which is checking whether given credentials are correct and redirects to another page. The login form itself is built by a HXR call - it isn't built in the login page code.
The problem is that I can't get browsers to prompt for remembering passwords. Once I've got the Firefox to prompt but since the form is being built by XHR call, the Firefox didn't paste the values into the form.
PS. I am using mootools (Form.send) and usual window.location when login was successful.
PSS. The address of the login page is always the same.
The following code is loaded by a XHR within a element (I am using MochaUI):
JavaScript:
$('loginwindow_form').set('send', {
"url": "auth/ajax_login",
"method": "post",
"onRequest": function () {
$("loginWindow_spinner").show();
},
"onComplete": function (response) {
$("loginWindow_spinner").hide();
},
"onSuccess": function (responseText, responseXML) {
window.location = "appinit";
},
"onFailure": function (xhr) {
MUI.notification('onFailure');
}
});
$("loginwindow_form").addEvent("submit", function (e) {
!e || e.stop();
$('loginwindow_form').send();
});
xHTML (notice that the form does not have submit button - the button is elsewhere and has onclick action to send the form with given ID):
<iframe src="auth/blank" id="blankiframe" name="blankiframe" style="display:none"></iframe>
<form action="appinit" method="post" name="loginwindow_form" id="loginwindow_form" class="standardform" target="blankiframe">
<input type="text" name="email" class="input text" id="loginwindow_form_email" />
<input type="password" name="password" class="input text password" id="loginwindow_form_loginwindow_form_password" />
</form>
The sending button (in another, xhr loaded, element):
<button class="button" action="{sendForm: 'loginwindow_form'}">
<div class="accept">Login</div>
</button>
you really ought to post code. it's all very nice doing a .send in your callback, that's fine. still, you need to post how you handle the form and initiate submission in the first place.
the way it should work is if you intercept the form's submit method - but if you--say, have a button with a click handler, it won't be seen as a submission so it won't remember things. also, are you doing event.stop or .preventDefault?
I recomment that you use a traditional sumbit form, but submit into a hidden iframe. (Or the login form itself could be in an iframe). This way you can still send back JS responses to the iframe which will be executed, and the browsers will know that it was a login form.

how to create an function using jquery live?

I am writing a function that well keep the user in lightbox images while he adds to cart.
When you click any image it well enlarge using lightbox v2, so when the user clicks the Add image, it will refresh the page. When I asked about it at jcart support they told me to use jquery live, but I dont know how to do that. T tried this code but still nothing is happening:
jQuery(function($) {
$('#button')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
I also used
jQuery(function($) {
$('input=[name=addto')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
yet nothing worked.
for code to create those images http://pasite.org/code/572
I also tried:
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
and it seems to add to jcart but yet it still refreshes
.live() is to assign handlers to future creating elements. On your site, however, you are re-loading the page so .live would have no bearing. (you are submitting a form)
It sounds like you want to make an ajax request to add the item to the cart and update that display on the site? That would be in the submit of the form and if jcart is dynamically created then yes, live is the answer.
$('.jcart').live('submit', function() {
// aggregate form elements into object and send via ajax
// update the cart on the page, since we haven't reloaded the page the light box is still displayed
});
Regarding comment:
When you send an ajax request, jquery takes an object as an argument. Such as $.post('urlToPostTo.php', { title: 'title of whatever', id: 5 } );
The server sees this the same as:
<form id="myForm" action="uroToPostTo.php" method="POST" >
<input type="text" name="title" value="title of whatever" />
<input type="hidden" name="id" value="5" />
<input type="submit" name="submit" value="submit" />
</form>
So if you were to aggregate the form inputs into an object, there's a few ways (even some jquery plugins to help you out). The primitive way would be:
var $form = $('#myForm'); // instead of finding myForm over and over, cache it as a variable to use
var objToSend = {};
objToSend.title = $form.find('input[name=title]').val();
objTosend.id = $form.find('input[name=id]').val();
$.post( 'urlToPostTo.php', objToSend );
A more Elegant solution is to have something loop through all form elements and put them into an object for you. Plugins like http://docs.jquery.com/Plugins:Forms make that a bit easier.
The end result is the form elements are stuffed into an object to send to your script.

Resources