I'm trying to use an input validation script in jquery. Which executes on document ready event.
$(function(){
$("#cart").validationEngine();
});
Here's the form where I want to use it:
<form id="cart" name="cart_form">
<?php foreach($product as $prods): ?>
<tr>
<td><input type="text" id="qty_sel<?php echo $prods['PID']; ?>" name="qtysell[]" class="validate[required]"/></td>
<td><input type="text" name="subtotal" id="subtotal<?php echo $prods['PID']; ?>" class="validate[required]" readonly="readonly"/></td>
<?php endforeach; ?>
</form>
The above code doesn't work, but when I tried it in something simpler, it actually worked:
<form id="cart" name="a">
<input type="text" id="name" class="validate[required]"/>
</form>
Does this have something to do with another script which I have written which computes the subtotal from the given price and quantity.
Or is it the ordering of the elements (table, form, input). Which causes the script to not work.
if you have some custom handler on the form's submit action such as
document.getElementById("formID").onsubmit = function(){
//custom code here
}
Then the validationEngine will not work ...
Try adding your function to validationEngine.js
Related
I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.
I have a html form and a dropdown list like this:
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div>
<span>Select Event</span>
<select id = "events" onchange="run()" class = "pass" style="width: 209px">
<?php while($row = oci_fetch_array($curs)):?>
<option value="<?php echo $row[0];?>"><?php echo $row[1];?></option>
<? endwhile; ?>
<input type="submit" name="action" value="New Event">
</select>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
</div>
</form>
I can successfully show the values that I take from the database table. And after that I want to use the selected value for another query which needs this selected value simultaneously without pressing submit button.And my run function is like:
<script>
function run() {
document.getElementById("srt").value = document.getElementById("events").value;
}
How can I assign this selected value to a php variable simultaneously?
`
It is not possible.
PHP script will never execute on onchange event.
Don't confuse it with JavaScript.
PHP scripts will only run on events like GET, POST, etc.
I have simple form:
<div class="form-style-2">
<form action="" name="formular" id="formular" method="GET">
<label for="actual_position"><span>From: <span class="required"></span></span><input name="actual_position" type="text" maxlength="512" id="actual_position" class="searchField"
<?php if(!empty($actual_position)){ ?>
value="<?php echo $_GET['actual_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<label for="final_position"><span>To: <span class="required"></span></span><input name="final_position" type="text" maxlength="512" id="final_position" class="searchField" <?php if(!empty($final_position)){ ?>
value="<?php echo $_GET['final_position']?>"
<?php
}else {
?> value = ""; <?php
} ?>/></label>
<input type="submit" value="Find path" />
And another multiselect in form who gets values form url link and compere with database and get som results. Here is a code:
<table width= "570px">
<tr><td width="200px" style="align:center"><b>Waypoints:</b> <br>
<tr><td width="370px"><select style="float:center; margin-left:5px" multiple id="waypoints">
if(!empty($urls)){
foreach($urls as $url){
if($result = $conn->query("SELECT * FROM $table where $ID = '$url' "));
$atraction = $result->fetch_array(); ?>
<option value="<?php echo $atraction['lat']. "," . $atraction['lon']; ?>"
> <?php echo "<b>".$atrction['City']. ", " . $atraction['Name'];?> </option>
<?php
}
}
?>
</select></td></tr>
<br>
</table>
</form>
And getting ID-s from url code:
if(!empty($_GET[$ID])){
$urls = $_GET[$ID];
foreach($urls as $url){
// echo $url;
}
}
... and after submit, it Post to URL some variables like this:
http://127.0.0.1/responsiveweb/travel.php?actual_position=Paris&final_position=Praha&ID[]=23&ID[]=15&ID[]=55
... very important for me are ID-s values ... but when I change for example actual position and then submit I lost my ID-s and I get something like this: http://127.0.0.1/responsiveweb/travel.php?actual_position=Berlin&final_position=Praha
Can you help me how to get after clicking on submit button full url link? Thanks
I had some trouble understanding your question OP, but I think I understood somehow what you ment, so I decided to try giving you a answer.
I have re-written your code, and tried to make somehow better code-structure. I have also used form method POST in my example, so you can see how you can change the get data on the redirection url.
See my code example here: http://pastebin.com/wQ7QCBmt
I also decided to use the form method POST instead of GET, so you can easily do back-end tasks, and extend your link if neccessary. You could also add more data to the link even when using GET. You could add an hidden input inside your form, example:
<input type="hidden" name="more_data" value="a_value" />
I am creating a form such that when the user click the "submit" button, it prevents the default action, serializes a subset of the fields, and then proceeds to submit all of the information via the POST array (PHP).
I am encountering a problem where the form is basically not submitting when I use the .submit() method. When I disable my javascript, the form submits fine (just with the wrong information, as the array is not serialized). But as soon as I re-enable my js, clicking the submit button does nothing except show my test console.log(var) in console. Here is some of my code, hopefully you can see what I am doing wrong. All of the online documentation says to use .submit(), but it doesn't seem to work, no matter what I try.
HTML:
<form id="entryForm" action="add_entry.php" method="post">
<div class="leftDiv">
<input type="text" class="inputFormTitle" name="entryName" placeholder="Name your entry..." />
<span class="regText">
<b>Entry Properties</b>
Specify entry properties, permissions, etc.</span>
<table class="formTable">
<tr>
<th>Parameter</th>
<th>Value</th>
<tr>
<td>Group</td>
<td><select name="group"><option></option><option>Graham Test</option></select>
</tr>
<tr>
<td>Project</td>
<td><select name="project"><option></option><option>Project 1</option><option>Project 2</option></select>
</tr>
<tr>
<td>Protocol</td>
<td>
<select id="protocolloader" name="protocol">
<option></option>
<option>PCR & Gel</option>
<option>Item Storage</option>
<tr>
<td>Permissions</td>
<td><input type="radio" name="permission" value="0">Only I can access this entry</input>
<input type="radio" name="permission" value="1">Only group members can access this entry</input>
<input type="radio" name="permission" value="2">Everyone can access this entry</input>
</select>
</tr>
</table>
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
<br/>
</div>
<div class="rightDiv">
<input type="text" class="inputFormTitle" id="ppt" placeholder="Please select a protocol" disabled/>
<div class="formHolder" id="protocolForm">
</div>
</div>
<input type="hidden" id="serialInput" name="protocolValues" value="nuttin" />
</form>
And the accompanying javascript:
var entrySubmit = $('#submitEntry');
entrySubmit.on('click', initEntrySubmission);
function initEntrySubmission(e) {
e.preventDefault();
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
$('#entryForm').submit();
}
PHP Form (which I don't think is the issue but figured I would include it anyways)
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['serialInput'];
$filearray = $_POST['fileArray'];
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, filearray, group, project, permissionflag)
VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$filearray', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}
?>
I wouldn't normally include so much HTML but I thought maybe I messed something up in there that may be the issue, and I just don't realize it. I tried to take out most of the break and header tags to clean up the code a bit.
Thanks for any help!
Regards.
The documentation of .submit() states, that
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures.
You have an input that has the name submit.
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" />
I tried it with and without that name. It works without!
I found the following to work:
<script>
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
alert(serializedProtocol);
$('#serialInput').val(serializedProtocol);
return true;
}
</script>
<form id="entryForm" action="" method="post" onSubmit="return initEntrySubmission();">
...
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" value="Submit Entry"/>
</form>
The main things to do are to add an onSubmit to your form tag. The function must return either true or false. Return true will submit the form.
Also, you do need to clean up your HTML, there are select statements in there, without closing tags and your submit button
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
has no ending >, it also has 2 type attributes type="button" and type="submit"(its both a button and a submit?) and has a name=submit, which is also unnecessary .
You don't have to preventDefault(), the Code will still be run before the Form is submitted.
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
}
You can try something like below
In HTML just add
<form id="entryForm" action="add_entry.php" method="post" onsubmit="return false;">
And in JS function
function initEntrySubmission(e) {
var serializedProtocol = $("#protocolForm :input").serialize();
$('#serialInput').val(serializedProtocol);
$('#entryForm').removeAttr('onsubmit');
$('#entryForm').submit();
}
Just change:
$('#entryForm').submit();
To:
$('#entryForm')[0].submit();
Also rename your submit element as #Matmarbon has so eloquently explained.
Explanation:
$('#entryForm').submit(); simply triggers the submit event and takes you back to square one.
$('#entryForm')[0].submit(); submits the form ... more like the default action, without triggering the submit event.
I have this code for form output, but I want to change the result so that it will load two buttons which will subscribe and unsubscribe, how do I do that?
Tried
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val(1) + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;">Subscribe</span></a></div>
and
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val(0) + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;">Unsubscribe</span></a></div>
But no effect
<div class="box">
<!-- <div class="box-heading"><?php echo $heading_title; ?></div> -->
<h3><?php echo $heading_title; ?></h3>
<div class="box-content">
<div id="newsletter_message" class="content" style="display:none; background: #FFFFCC; border: 1px solid #FFCC33; padding: 10px; margin-top: 2px; margin-bottom: 15px;"></div>
<form action="<?php echo $action; ?>" method="post" id="module_newsletter" name="module_newsletter">
<div style="text-align: left;">
<span class="required">*</span><b><?php echo $entry_email; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_email" required placeholder="<?php echo $entry_email; ?>"/><br />
<?php if ($name == 'optional') { ?>
<b><?php echo $entry_name; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_name" placeholder="<?php echo $entry_name; ?>"/>
<?php } elseif ($name == 'required') { ?>
<span class="required">*</span><b><?php echo $entry_name; ?></b><br />
<input style="width:90%;" type="text" name="newsletter_name" placeholder="<?php echo $entry_name; ?>"/>
<?php } else { ?>
<input type="hidden" name="name" value="" />
<?php } ?>
<br />
<input name="subscribe" value="1" type="hidden" />
</div>
<table style="align:left;">
<tr>
<td style="width: 100%;">
<table>
<tr>
<td><input type="radio" style="vertical-align: middle;" id="subscribe" name="subscribe" value="1" checked="checked"/><label style="font-size:10px; vertical-align: middle;" for="subscribe"><?php echo $text_subscribe; ?></label></td>
</tr>
<tr>
<td><input type="radio" style="vertical-align: middle;" id="unsubscribe" name="subscribe" value="0" /><label style="font-size:10px; vertical-align: middle;" for="unsubscribe"><?php echo $text_unsubscribe; ?></label></td>
</tr>
</table>
</td>
<td></td>
</tr>
</table>
<div><a onclick="$('div#newsletter_message').load('index.php?route=module/newsletter/callback&subscribe=' + $('input[name=\'subscribe\']:checked').val() + '&email=' + escape($('input[name=\'newsletter_email\']').val()) + '&name=' + escape($('input[name=\'newsletter_name\']').val()), function() { $('div#newsletter_message').hide(); $('div#newsletter_message').show('slow'); });" class="buttons"><span style="float:left; clear:both;"><?php echo $button_go; ?></span></a></div>
</form>
</div>
</div>
Replace this...
$('input[name=\'subscribe\']:checked').val()
With this...
$('input[name=subscribe]:radio:checked').val()
You need the :radio selector as you also have a hidden form input with the same name. Bear in mind what this fact may do to your form for non-javascript users.
As requested, here is a more thorough answer. I can't help you fix all your code, as that is outside of the scope of Stack Overflow, however here is something to help you get started.
Basic working example: http://jsfiddle.net/jeb2x/
Let's say you have a form...
<form id="SubscribeForm">
<input type="radio" name="subscribe" value="1" checked="checked" />
<input type="radio" name="subscribe" value="0" />
Alert selected value
</form>
You can subscribe to the click event of the link with id alert and have it alert the selected radio button value. This Javascript code should be in a separate file to your html, and included in the head using a script tag.
<script type="text/javascript" src="/pathtofile/scripts.js"></script>
...
$(document).ready(function(){
$('#SubscribeForm').on('click', 'a#alert', function(){
var selectedValue = $('input[name=subscribe]:checked').val();
alert(selectedValue);
});
});
There are a few principles you need to learn about in order to understand the code here.
Firstly, it is subscribing to the ready event of the document. This ensures that the code only runs when the DOM has finished loading, and therefore, your form is definitely ready to be used. There is also a shorthand way of subscribing to document ready, which is to pass an anonymous function to jQuery, and it knows to run it on DOM ready
$(function(){
//...code here
});
It is then subscribing to the click event of the form. This code uses a principle called event delegation, which is worth reading up on. It's not really needed for this simple example, but is advantageous if you need to bind to multiple events within the same div for example. The code could in this case be simplified to...
$('a#alert').on('click', function(){
var selectedValue = $('input[name=subscribe]:checked').val();
alert(selectedValue);
});
...or even just $('a#alert').click(function(){
The code then uses my original solution (minus the :radio selector, which isn't needed as there is only one group of inputs with the name 'subscribe'), to alert the selected value.
In your case, you are trying to call an external script in order to subscribe or unsubscribe users. One way to do this is to use an AJAX request. You could use any of a number of methods to do this. You are using the load method above, which will send a request to the url supplied, and insert the response into the selected element.
$("#result").load( "test.html" );
In the example here, the response from test.html will be inserted into the element with id result. If you wanted to do something more complex with the response, you could use one of jQuery's AJAX methods, such as $.ajax() or $.get()
Hope this helps :)