Jquery Confirmation Does Not Appear - php

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;
}
});

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

Multiple form submissions

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.

jquery form plugin & programmatic submit

There are similar questions at SO, but none that seem to address this.
Below is a very simplified variant of my situation. Drupal/PHP site -- I have a form w/ submit button that I am using jquery.form plugin to ajax-ly submit. It works fine if I use the submit (#submit) button.
Now, I want to programmatically fire that button using another button (#submit2) outside of the form. I can do that using jquery click() function, but the content coming back isn't going to the ajax target as I would expect.
I do not have much freedom to re-organize this code, else i would.
(Note I tried to make this code easy for you to run by src-ing jquery and the form plugin from my website.)
Ideas? Thanks!
<?php
if ($_REQUEST['submit'] == 'Submit') {
print 'ajax returns ... ' . $_REQUEST['text'];
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery-1.2.6.js"></script>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#form').ajaxForm( { target: $('#span') } );
$('#submit2').click( function() { $('#submit').click(); } );
});
</script>
</head>
<body>
<span id='span'>target span</span>
<form method='post' id='form'>
<input type='text' name='text' size='50' />
<input type='submit' id='submit' name='submit' value='Submit'/>
</form>
<input type='submit' id='submit2' name='submit2' value='Submit Too?' />
</body>
</html>
I managed to solve a similar situation to yours. If the only objective of simulating a click on submit1 is to submit the form, you might try:
$('#submit2').click(function() {
$('#form').trigger('submit');
});
You may also need to return false immediately after triggering the form submit button from the non-form submit button click event code. For example:
<script type="text/javascript">
$(function() {
$('#form').ajaxForm({ target: $('#span') });
$('#submit2').click(function() { $('#submit').click(); return false; });
});
</script>
It works for me. Is that what you are looking for?
Have you tried giving a name to the form, and instead of
$('#submit2').click( function() { $('#submit').click(); } );
doing
$('#submit2').click( function() { document.myForm.submit(); } );
That should do the same thing as having the submit button clicked if the form has been ajaxified.

Categories