Multiple form submissions - php

Just to give some context I'm a self taught programmer with no formal education or experience so apologise for my code in advance...
Code below attempts to turn a site designed for an iphone into a single page site (i.e. using ajax). I'm having an issue with multiple form submissions... looks like this is occurring when clicking the submit button on form #id2.
I've done some research and was thinking of implementing the below jquery solution for preventing multiple form submissions:
How to prevent form from submitting multiple times from client side?
and this php solution for preventing multiple form submissionson the server side:
http://www.ideologics.co.uk/programming/how-to-prevent-multiple-form-submissions-in-php
Also some sites suggest that the ajax post code should set async to false and cache to false but I'm not entirely sure of the reason and whether this is applicable in my case.
The reason I had to use the delegate function is because clicking submit on form #id1 loads a form with id#2... I tried using the on function which jquery site says supersedes the delegate function but this didn't seem to work. I'm loading version 1.8.2 using google CDN.
var startUrl = 'menu.php';
$(document).ready(function(){
loadPage(startUrl);
});
function loadPage(url) {
$('body').append('<div id="progress">Loading...</div>');
scrollTo(0,0);
if (url == startUrl) {
var element = ' #header ul';
} else {
var element = ' #content';
}
$('#container').load(url + element, function(){
var title = $('h2').html() || 'Menu';
$('h1').html(title);
$('h2').remove();
$('.leftButton').remove();
if (url != startUrl) {
$('#header').append('<div class="leftButton">Menu</div>');
$('#header .leftButton').click(function(e){
$(e.target).addClass('clicked');
loadPage(startUrl);
});
}
$("#container").delegate("a", "click", function(e){
var url = e.target.href;
if (url.match(/example.com/)) {
e.preventDefault();
loadPage(url);
}
});
$("#container").delegate("form", "submit", function(event){
event.preventDefault();
});
$('#id1').submit(function(){
var formData = $(this).serialize();
$.post('processform1.php',formData,processResults);
function processResults(data) {
$('#id1').remove();
$('#container').html(data);
}
});
$("#container").delegate("#id2", "submit", function(event){
var formData = $(this).serialize();
$.post('processform3.php',formData,processResults);
function processResults(data) {
$('#id2').remove();
$('#container').html(data);
}
event.preventDefault();
});
$('#progress').remove();
});
}
Below is the index page:
<html>
<head>
<title>Title</title>
<meta name="viewport" content="user-scalable=no, width=device-width" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon-precomposed" href="myCustomIcon.png" />
<link rel="apple-touch-startup-image" href="myCustomStartupGraphic.png" />
<link rel="stylesheet" href="iphone.css" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="iphone.js"></script>
</head>
<body>
<div id="header">
<h1>Menu</h1>
</div>
<div id="container"></div>
</body>
</html>

Just place this in your JS for the page the submit button is on
<script type="text/javascript">
$(document).ready(function(){
$("input[type='submit']").attr("disabled", false);
$("form").submit(function(){
$("input[type='submit']").attr("disabled", true).val("Please wait...");
return true;
})
})
</script>
You may need to use an on() event handler or do other tinkering depending on if the form is generated on page load.

Related

Submiting a form with jquery/AJAX isn't working when clicking the submit button

I am trying to submit a form with jquery/AJAX but my function is never called when I am clicking on the submit button.
My website looks like that:
CarMenu.php
<html lang="en">
<html>
<head>
<meta charset="ISO-8859-1">
<title>ArsenalAutoBrokers - Backend - add car</title>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
<link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
<script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
<script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
<script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
<script charset="UTF8" src="../js/app/carForm.js"></script>
<script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
<div id="container">
<div id="leftMenuContainer">
<ul id="menu">
<li id="addCarItem">Add car</li>
<li id="saveCarItem">Edit cars</li>
</ul>
</div>
<div id="rightMainContent">
</div>
<div class="clear"></div>
</div>
</body>
</html>
On that page, I am using jquery menu and I am loading the data into the div with the id 'rightMainContent'.
The javascript code to do this looks like: carForm.js
$(document).ready(function () {
$( "#menu" ).menu({
select: function(event, ui) {
if (ui.item.attr('id') === 'addCarItem') {
$("#rightMainContent").load(
'/CarDealer/CarForm/CreateCar/AddCar.php');
}
}
});
});
If you are clicking on the 'addCar' menu item parts of the site will load from this php site:
<script type="text/javascript">
$('input[type=submit]').button();
//$('#activeCheck').button();
$("#activeCheck").attr('checked','checked');
$('#saveButton').hide();
$('#tabs').tabs();
$('#accordion' ).accordion({heightStyle: "content"});
$('#tabs').tabs({
activate: function (event, ui) {
var act = $("#tabs").tabs("option", "active");
if (act == 0 || act == 1) {
$('#saveButton').hide();
} else {
$('#saveButton').show();
}
}
});
$('#fileToUpload').on('change', function(){
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
if (files.length > 10) {
$('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
$('.info').show();
} else {
$('.info').html('');
$('.info').hide();
}
});
</script>
<form id="carSaveForm"
action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
enctype="multipart/form-data">
<div id="tabs">
<ul>
<li>General Car Information</li>
<li>Car Descriptions</li>
<li>Picture Upload</li>
</ul>
<div id="tabsGen">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
</div>
<div id="tabsDescr">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
</div>
<div id="tabsPics">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>
</div>
</div>
<br> <input id="saveButton" type="submit" name="submit" value="save" />
</form>
This site is containg only form elements like input buttons, file pickers, etc.
Well, so far so good. Everything is displaying properly but if I am clicking the submit button this function isn't getting called: addCar.js
$('#carSaveForm').on('submit', function(event){
event.preventDefault();
var formData = new FormData();
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
formData.append('carBrand' , $('input[name=carBrand]').val());
formData.append('carModelYear' , $('input[name="carModelYear"]').val());
formData.append('carModel' , $('input[name=carModel]').val());
formData.append('carTrim' , $('input[name="carTrim"]').val());
formData.append('carDriveTrain' , $('input[name="carDriveTrain"]').val());
formData.append('carCondition' , $('input[name="carCondition"]').val());
formData.append('carType' , $('input[name="carType"]').val());
formData.append('carFuelType' , $('input[name="carFuelType"]').val());
formData.append('carTransmission' , $('input[name="carTransmission"]').val());
formData.append('carEngine' , $('input[name="carEngine"]').val());
formData.append('carCylinder' , $('input[name="carCylinder"]').val());
formData.append('carMileage' , $('input[name="carMileage"]').val());
formData.append('carExteriorColor' , $('input[name="carExteriorColor"]').val());
formData.append('carInteriorColor' , $('input[name="carInteriorColor"]').val());
formData.append('carLocation' , $('input[name="carLocation"]').val());
formData.append('carVin' , $('input[name="carVin"]').val());
formData.append('carStock' , $('input[name="carStock"]').val());
formData.append('carPrice' , $('input[name="carPrice"]').val());
formData.append('carPriceDetails' , $('input[name="carPriceDetails"]').val());
formData.append('carTax' , $('input[name="carTax"]').val());
formData.append('carTaxDetails' , $('input[name="carTaxDetails"]').val());
formData.append('carCurrency' , $('input[name="carCurrency"]').val());
formData.append('carOnline' , $('input[name="carOnline"]').val());
formData.append('carDescr' , $('input[name="carDescr"]').val());
formData.append('carBodyDescr' , $('input[name="carBodyDescr"]').val());
formData.append('carDriveTrainDescr' , $('input[name="carDriveTrainDescr"]').val());
formData.append('carExteriorDescr' , $('input[name="carExteriorDescr"]').val());
formData.append('carElectronicsDescr' , $('input[name="carElectronicsDescr"]').val());
formData.append('carSaftyFeaturesDescr' , $('input[name="carSaftyFeaturesDescr"]').val());
formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
data : formData, // our data object
contentType: false,
processData: false,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function (data) {
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
return false;
});
I have no clue why this function is never getting called, I have tried everything, I have googled a lot but I am not getting it. I am searching for the error the whole day but I can't see it.
Please help me.
Your help is apreciated.
Thanks in advance.
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
For instance, this button has been added to the DOM via AJAX:
<input id="saveButton" type="submit" name="submit" value="save" />
In order to properly handle this (if it is the only form with this id added to the page) is to delegate the click or submit event:
$(document).on('click', '#saveButton', function(event) {...
In addition, if you continue to add forms as you show here, you will have duplicate id's in your page and id's must be unique. Failure to make them unique will result in a number of problems.
Make sure to watch the AJAX request / response in the browser's console as outlined here to find and correct errors that you may be having.
change $('#carSaveForm').on('submit', function(event) to $('#carSaveForm').on('click','#saveButton', function(event)
Cut (ctrl+x) this line from CarMenu.php
<script charset="UTF8" src="../js/app/addCar.js"></script>
And paste (ctrl+v) the script in AddCar.php

How to change default behavior of enter key?

It's a chat application code in notepad++. My enter key is not working as it gives a new line always. I tried to find the problem but couldn't rectify it,
It will be of great help if someone can spot and rectify the problem?
?
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<link href="../Style/Style.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="..Js/jquery.js"></script>
<title>Chat Application Home</title>
<script type="text/javascript">
$(document).ready(function(){
$("#ChatText").keyup(function(e){
//When We Press Enter Do
if(e.keyCode ==13){
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
});
</script>
</head>
<body>
<h2>Welcome <span style="color:green"><?php echo $_SESSION['UserName'];?></span></h2>
</br></br>
<div id="ChatBig">
<div id="ChatMesseges">
</div>
<textarea id="ChatText" name="ChatText"></textarea>
</div>
</body>
</html>
You have to cancel the default behaviour of the enter keypress event. Add this to your code:
$("#ChatText").keypress(function(e) {
if(e.keyCode ==13){
return false;
}
}
Note that this is a different event; leave the keyup handling as-is, or alternatively, change your code to respond to the keypress event instead of the keyup event, and add the return false; there. Both ways are fine.
You should prevent the default behaviour on key press. Use e.preventDefault() or return to do that, then run your code.

JQuery Page Refreshes

I working on a page with some JQuery and Kendo UI. This is my first JQuery project and I getting things along. However, my page refreshes for some reason. This is what I am trying to do: I have a text field where I can enter a search term and when I press a button, the query is sent to a php file and some json info will pop up. So far, I can get it to return something, but the page refreshs and all the data is gone.
code:
*<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.default.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<script src="js/kendo.web.min.js"></script>
</head>
<body>
<div id="example">
<form id="search">
<label for="search">Search For:</label>
<input type="text" id="txtSearch" name="q">
<button type="submit" id="submit">Find</button>
</form>
<div id="grid">
</div>
</div>
<script>
$(function() {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "include/showsearch.php"
},
schema: {
data: "data"
}
},
columns: [{field: "id"},{field: "name"},{field: "season"}]
});
$("#submit").click(function(){
var textVal = $("#txtSearch").val();
var dynamicURL = "include/showsearch.php?show_name=" + textVal;
var grid = $("#grid").data("kendoGrid");
alert("sdf123");
grid.dataSource.transport.options.read.url = dynamicURL;
grid.dataSource.read();
alert("sdf");
});
});
</script>
</body>
</html>*
NOTE:
I used the alert functions to stop and see how the page reacts. How do I get the page from refreshing?
The reason this is happening is that the default action for your submit button is still occurring; submitting the form.
It's probably best to catch the form submission event rather than the button click as hitting Enter in a text field may also submit the form.
You will also need to prevent the default event action.
Change this
$("#submit").click(function(){
to this
$('#search').on('submit', function(e) {
e.preventDefault();
// and the rest of your code here

Jquery Confirmation Does Not Appear

I want to begin by saying I am extremely new to Jquery / client side scripting. I was kinda blind sided when my bosses wanted some way for customers to acknowledge form submission.
This is my jquery / header :
<head>
<title>Access Point</title>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<link rel="stylesheet" href="<?php echo base_url();?>css/mainstyle.css" type="text/css" />
<link rel="stylesheet" href="<?php echo base_url();?>css/secondarystyles.css" type="text/css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$("#signinform").submit( function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});
</script>
</head>
And this is my form :
<?php echo form_open('staff_controller/agree', 'id="signinform"') ?>
<input type="checkbox" id="agree" name="options" value="agree"<?php echo form_checkbox('options','agree') ?>I have read and understood the above <br /> <font color="#ff0000" size="3">(Please click on the box)</font></input>
<br />
<br />
<br />
<?php
echo form_submit('submit', 'Submit');
echo anchor('staff_controller/studentlogin', 'Cancel');
echo form_close();
?>
My php script checks if the checkbox is checked (to agree to our requirements) and also checks if submit is clicked. If it is clicked then submit the values into a database. To my understand I can continue to use this style to handle my data I just want jquery in the middle to allow users to know they are submitting. I found this code out in the internet and I have no idea how to debug this. I also do plan to a jquery confirm to check if you want to "Cancel" form submission
Edit 1 :
looking at source code it "should" work :
form
action="https://www.finaidtest.com/index.php/staff_controller/agree"
id="signinform" method="post" accept-charset="utf-8"
and then my updated confirmation :
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait"))
{
e.preventDefault();
return;
}
});
</script>
Edit 2
Thanks to Musa it all works fine now! Thanks!!
Code :
<script src="<?php echo base_url();?>javascript/js/jquery.js" type="text/javascript"></script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait"))
{
e.preventDefault();
return;
}
});
</script>
You have to wait for the element to be created before you can bind an event handler to it. Use $(document).ready to ensure your element is created before you set the handler.
$(document).ready(function(){
$("#signinform").submit( function(e)
{
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});
});
You could also use delegation to attach the event so you don't have to wait for the dom to be loaded
$(document).on('submit', "#signinform", function(e){
if (!confirm("If you click OK you will be inserted into student queue. Please take a seat and wait."))
{
e.preventDefault();
return;
}
});

Manipulating Form Values After jQuery.load

Good evening everyone,
I am currently trying to cleanup my inline JS and break it up into its own .js file, as well as breaking up some of my code into functions. Below I provide my code, I have an HTML file with an empty div named #main. On document ready I want to call my firstLoad function. It simply calls $("#main").load("login.php"); Seems simple enough, however my next step is that on submit of the form I want to serialize the submitted data, turn to string and submit via post. This for some reason will work if I hard code the form into the index.php file, but not if I use .load to fill in #main. I can't figure out why this is, I am sure it's simple if someone could explain it little that would be wonderful. My code follows:
UPDATE
After more searching I came across this thread that says the following:
As it turns out, the jquery .load() function is working flawlessly,
and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any
"callback" function included by the programmer, just like any other
jquery function that accepts a callback as one of its "arguments". The
.load() function is complete once it either errors or successfully
begins the HTML replacement and loading of new content, but that is
IT! The content will then take however long it takes to load, but your
.load call is already complete before that. Therefore, expecting the
callback to run after the .load content has loaded will only
disappoint you. ;)
I hope others can learn from this just as I did, including those who
thought what I thought was the case. Proof: as stated in the jquery
ajax .load page, the callback is executed when the request completes,
not when the load completes. Eureka. Whoops.
Which leads to the follow up question, how can I manipulate the form after the load content has been added to the DOM? This is surely a simple fix, but I am new to AJAX and could use a nudge in the right direction. I notice adding a document(ready) within the login.php script works properly as it is added with the html, but it doesn't seem like the cleanest way of doing things, as I'm trying to keep out inline JS. Any more advice?
/UPDATE
PHP/HTML
index.php
<?php
session_start();
$sessionNumber = session_id();
?>
<!doctype html>
<!-- Conditional comment for mobile ie7 blogs.msdn.com/b/iemobile/ -->
<!--[if IEMobile 7 ]> <html class="no-js iem7" lang="en"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MyMobile</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/h/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/m/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="img/l/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="img/l/apple-touch-icon.png">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body>
<div id="container">
<header id="header">
<img alt="Logo" src="img/logo.png" />
<div id="blackHead">Please sign-in to continue</div>
</header>
<div id="main" role="main">
</div>
<footer id="footer">
<div id="greyFoot">
© 2012 ACME<br />
<pre id="result"></pre>
</div>
</footer>
</div> <!--! end of #container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/firstLoad.js"></script>
</body>
</html>
login.php
<?php session_start();
$sessionNumber = session_id();
?>
<!-- begin login form -->
<?php if(isset($_SESSION['sessionemail'])){ ?>
Logout
<?php }else { ?>
<form id="logForm" name="login" method="post" action="#">
<label for="sessionemail">Email</label><br />
<input id="sessionemail" type="email" name="sessionemail" autofocus="autofocus" autocapitalize="off" maxlength="150" required="true" value="" class="inputText" /><br />
<label for="password">Password</label>
<input id="password" type="password" name="password" required="true" value="" class="inputText" /><br />
<br />
<input type="hidden" name="sessionid" id="sessionid" value="<?php echo $sessionNumber; ?>" />
<input type="hidden" name="subtocall" id="subtocall" value="g2.web.login.sub" />
<input type="submit" value="Sign-In" name="submit" class="submitBox" />
</form><!-- end login form -->
<?php } ?>
And finally, my JS/Jquery
firstLoad.js
//function serializes our object
(function($){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
//firstLoad function runs on document ready
//it loads the login form into the main div and slides
//the container down
(function($){
$.fn.firstLoad = function(){
return this.each(function() {
$("#container").slideUp("slow", function(){
$("#main").load('./login.php', function(){
$("#container").slideDown("slow", function(){
});
});
});
});
};
})(jQuery);
//logParse takes the loginResponse from the server
//changes from string to object, runs a check for authentication then
//manipulates the object dropping excess keys and adding new relevant ones for
//the intial to do list call
(function($){
$.fn.logParse = function(xml){
return this.each(function() {
//parse the JSON login check string from the XML response
var loginResponse = $(xml).find('string').text();
//setup isBad variable for error check
var isBad = false;
//convert to JSON object from parsed string data
loginResponse = $.parseJSON(loginResponse);
//check if the sessionID is correct and user authenticated properly
if((loginResponse.SESSIONID != "<?php echo $sessionNumber; ?>") || (loginResponse.ISAUTHENTICATED == 0)){isBad = true;}
//if error flag is raised alert and bounce back to login
if(isBad){
alert("Unauthorized connection, please try again.");
}
//if there are no errors
else{
alert("so far so good!");
//set up a new JSON object for to do list passback
//and import the values from the lognResponse object
//var todoPost =
}
});
};
})(jQuery);
$(document).ready(function(){
//hide screen for slidedown
//$("#container").addClass("noShow");
//allow cross domain scripts
$.support.cors = true;
//call firstLoad function to slide in the login prompt
$("#main").firstLoad(function(){
//create JSON object to store form input for AJAX POST
//create submit listener
$("#logForm").submit(function(){
alert("inside submit");
//parse form into formObj for data passing and manipulation
var formObj = JSON.stringify($("form").serializeObject());
//output initial formObj into result pane
$("#result").text(formObj);
$("#main").text("submitted: " + formObj);
//AJAX POST call
$.ajax({
//type of communication
type: "POST",
//action for form
url: "http://mydomain.com/JSONService.asmx/G2WebRequest",
//data to be passed
data: "request="+ formObj,
//type of data passed in
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//enable cross domain
crossDomain: "true",
//data type returned from webservice
dataType: "xml",
//if login POST was successful
success: function(xml){
alert("post successful");
$.logParse(xml);
},
//if login POST failed
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
});
You are probably setting up the listener on $("#logForm") before the login form is fully loaded into the DOM. This would explain why the login form works when hardcoded. You can test this by alert($("#logForm").length);- this will be zero if not found.
If this is the case you will need to ensure you wait until the login page is completely loaded before attempting to attach the listener. I would probably make firstLoad call a function once load completes.
Good luck.
JQuery.on() solved this issue. Took me a while to figure that out.

Categories