I can't validate upload field. the field name is an array. how to validate it using jquery?
here is my code:
<script type="text/javascript">
$().ready(function() {
// validate signup form on keyup and submit
var validator = $("#signupform").submit(function() {
// update underlying textarea before submit validation
}).validate({
rules: {
name: "required",
photo_path: { required: true }
},
errorPlacement: function(label, element) {
label.insertAfter(element);
},
messages: {
name: "Please enter your name",
photo_path: "Upload your Image"
}
});
});
</script>
<?php
$count=1;
for($i=0; $i<4; $i++)
{
?>
<input type="hidden" name="galleryImage[]" id="galleryImage[]" value="<?=$i?>"/> </td>
</tr>
<tr>
<td align="left" valign="middle" bordercolor="1" class="signup">Upload Image <?=$count?>:</td>
<td align="left" valign="middle" bordercolor="1"><input type="file" name="photo_path[]" id="photo_path" class="inputcolor_text" />
<br />
<?php
$count++;
}
?>
Give this a go...
var validator = $("#signupform").submit(function(e) {
if(!$('.inputcolor_text').val()){
e.preventDefault();
// $('#error').html('Cannot be empty.');
return false;
}
}).validate.....
Related
jqlib.js is https://code.jquery.com/jquery-3.2.1.js
nothing is happing i m trying to add to number using ajax using jquery 3.2.1.js
cant find the error in this code can anyone tell me where is the error in this code
add.php
<html>
<body>
<script type="text/javascript" src="jqlib.js"></script>
<form id="tt">
<table>
<tr>
<td>Enter first Number</td>
<td><input type=text name=t1 ></td>
</tr>
<tr>
<td>Enter 2nd Number</td>
<td><input type=text name=t2></td>
</tr>
<tr>
<td><input type=button value="OK" onClick="cal()"></td>
</tr>
<tr>
<td>Addition</td>
<td><input type=text name=t3 id="tt1"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
function cal()
{
var frm = $("#tt");
$.ajax(
{
type:"POST",
url:"ajax.php",
data:frm.serialize(),
sucess:function (data)
{
$("#tt1").val(data);
}
});
}
</script>
ajax.php
<?php
if(!empty($_POST))
{
if(($_POST['t1']!="" )|| ($_POST['t2']!=""))
{
$z = $_POST['t1'] + $_POST['t2'];
}
else
{
$z ="please enter data";
}
echo $z;
}
else
{
echo "please enter data";
}
?>
you have a typo error:
sucess should be success
Change your script as follow and check whether any alert is showing or not
<script type="text/javascript">
function cal()
{
var frm = $("#tt");
$.ajax(
{
type:"POST",
url:"ajax.php",
data:frm.serialize(),
sucess:function (data)
{
$("#tt1").val(data);
alert('Success: '+data); ///---> this show alert with success and content
},
error:function(a,b,c)
{
alert(c); //---> If error happen it will show alert();
}
});
}
</script>
I have a feedback form which is validate by jquery and request is sent to Php page using ajax. So In firebug I checked that it's successfully showing the "Successful Message" but why it's not showing in hmtl page <div id="#feedback_result"></div> tag ?
Jquery Code:
<script>
$(document).ready(function() {
// validate signup form on keyup and submit
$("#feedback").validate({
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
//async: false,
data: $(form).serialize(),
beforeSend : function (){
$('input[type=submit]').attr('disabled', false);
},
success: function(response) {
$('#feedback_result').html(response);
}
});
},
rules: {
yourfeedback: "required",
},
messages: {
yourfeedback: "Required",
}
});
});
</script>
Html Code:
<div id="#feedback_result"></div>
<form id="feedback" method="post" action="<?php echo htmlspecialchars("feedback_process.php"); ?>">
<table width="400" border="0" cellspacing="5" cellpadding="0">
<tr>
<td>Your feedback</td>
</tr>
<tr>
<td><textarea class="textarea2" name="yourfeedback" placeholder="Your feedback"></textarea></td>
</tr>
<tr>
<td><input type="submit" id="submit" value="Send Feedback" name="submit" class="submit_button"/></td>
</tr>
</table>
</form>
</div>
Note: I've another form in this same page with same jquery/ajax code except the id $("#order").validate({
Try to remove the # from your id value:
<div id="feedback_result"></div>
I have a simple search form using HTML, PHP, and jQuery but the form submits even though some fields are empty and the validator warnings appear for a moment. So I would submit the form, the warnings about "Required field" appear, and it submits anyway. The validator is being triggered but isn't stopping the form.
HTML + PHP
<form action="dater.php" method="post" id="daterange">
<table width = "1000px">
<col width="250px" />
<col width="250px" />
<col width="250px" />
<col width="250px" />
<tr>
<? dateRangeView(); ?>
<td><input class="comment" type="text" name="groups" id="groupname" placeholder="Enter group name"> *</td>
<td><input class="comment" type="text" name="employee" id="staffname" placeholder="Enter employee name"> *</td>
</tr></table>
*Leave these blank to view all<br>
<button class="mainButton" id="viewTimesheets" value="viewTimesheets" type="submit">View</button>
function dateRangeView()
{
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
echo'<td><select id="startdate" class="infotable" name="startdate"><option value="">---- Start date ----</option>';
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br><td><select id="enddate" class="infotable" name="enddate"> <option value="">---- End date ----</option>';
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br></td>';
}
VALIDATOR PLUGIN CODE
<script language="javascript" type="text/javascript">
/*-------------Validator-------------*/
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
</script>
I've been at it for four hours now, used .on(), return false; onSubmit() and e.preventDefault(); although I may have gotten the syntax on those messed up... This is the plugin I'm using... http://jqueryvalidation.org/validate/
Try this.
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function (form) {
alert('submitted');
form.submit();
}
});
$('#daterange').validate({
rules: {
startdate: {
required: true
},
enddate: {
required: true
}
}
});
});
Working JsFiddle example Demo
Hope this helps, Thank you
or here is the code for you both works
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
});
$(document).ready(function () {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
if($("#daterange").valid()) {
// call your function;
alert("submitted!");
}
});
This is my first form using jquery to validate via client-side and I'm running into a problem with the .ajaxSubmit function (I also just used .ajax) and when clicking on submit button the database is updated but the ajax function doesn't return the results to the page. So, when I click on the submit button it looks like nothing is happening but when I look at the database the fields are updated with the data. Also, when I comment out the ajax function and just use the alert then when I click on the submit button the alert pops up. If someone can please assist me, as I've been working on this for a week now.
Here's the html and jQuery script:
<html>
<head>
<style type="text/css">
<!--
#import "./css/job.css";
-->
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="./js/jquery.validate.js"></script>
<script type="text/javascript" src="./js/jquery.form.js"></script>
<script type="text/javascript">
(function($,W,D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function() {
//form validation rules
$("#job").validate({
rules: {
jobtype: {
required: true },
account: {
required: true,
minlength: 8 },
phone: {
required: true,
minlength: 7 },
comment: {
required: true,
minlength: 5 },
available: {
required: true,
minlength: 3 }
},
messages: {
jobtype: {
required: "Select a job type" },
account: {
required: "Enter account in correct format" },
phone: {
required: "Enter phone number" },
comment: {
required: "Enter WIP details" },
available: {
required: "Enter an available timeframe" }
},
submitHandler: function(form) {
// alert("Submitting Job");
$(form).ajaxSubmit({
url: 'response.php',
type: 'POST',
data: {
jobtype: $("#jobtype").val(),
account: $("#account").val(),
phone: $("#phone").val(),
comment: $("#comment").val(),
available: $("#available").val(),
},
dataType: 'json',
cache: false,
timeout: 7000,
success: function(data) {
$('form #schedTable').html(data.msg).fadeIn('fast');
}
});
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
</head>
<body>
<div id="jobForm">
<form id="job" name="job" action="response.php" method="post" novalidate="novalidate">
<h1>Job Scheduling</h1>
<label>Type</label>
<select id="jobtype" name="jobtype">
<option value="" selected><< SELECT >></option>
<option value="service">Service</option>
<option value="install">Install</option>
</select>
<label>Account</label>
<input type="text" id="account" name="account" maxlength="10" size="10">
<label>Phone</label>
<input type="text" id="phone" name="phone" maxlength="7" size="7">
<label>Comment</label>
<textarea id="comment" name="comment" rows="2" cols="40" maxlength="40"></textarea>
<label>Available</label>
<input type="text" id="available" name="available" maxlength="20" size="20">
<input id="submit" name="submit" type="submit" value="Submit" class="submit">
</form>
</div>
<div id="schedTable"></div>
</body>
</html>
Here's the response.php code:
<?php
$mydb connection info here
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Test Form</title>
<link rel="shortcut icon" href="/favicon.ico">
</head>
<body>
<?php
// form inputs
$account = trim($_POST['account']);
$type = $_POST['type'];
$phone = $_POST['phone'];
$comment = trim($_POST['comment']);
$available = trim($_POST['available']);
// Insert into mysql db
$ins = mysql_query(sprintf("INSERT INTO table (type,comment,available,phone,account) VALUES ('%s','%s','%s','%s','%s')", $type,$comment,$available,$phone,$acct)) or die(mysql_error());
$sched = mysql_query(sprintf("SELECT * FROM table ORDER BY type asc"));
$return['msg'] = "
<table border='1'>
<tr>
<th>Type</th>
<th>Account</th>
<th>Comment</th>
</tr>";
while($rowu = mysql_fetch_array($sched)) {
$return['msg'] .= "
<tr>
<td>{$type}</td>
<td>{$acct}</td>
<td>{$comment}</td>
</tr>";
}
$return['msg'] .= "</table>";
// header("Content-Type: text/javascript; charset=utf-8");
// $return['msg'] = "Testing " .$account . "works";
header('Content-Type: application/json');
echo json_encode($return);
?>
</body>
</html>
UPDATE: I removed all of the html and the issue is the same while using chrome. When I use IE 8 and I click on the submit button it asks to open or save as a text file (repeats the same form data multiple times as well):
{"msg":"<table border='1'><tr>\n <th>Type<\/th>\n <th>Account<\/th>\n <th>Comment<\/th>\n <\/tr><tr>\n <td>other<\/td>\n <td>12345678<\/td>\n <td>sssss<\/td>\n <\/tr><tr>\n <td>other<\/td>\n <td>12345678<\/td>\n <td>sssss<\/td>\n <\/tr><tr>\n <td>other<\/td>\n <td>12345678<\/td>\n <td>sssss<\/td>\n <\/tr><\/table>"}
Strip out all the html around the php logic. This is causing the problem, the response needs to be only json not html + json + html.
<?php
$mydb connection info here
// form inputs
$account = trim($_POST['account']);
$type = $_POST['type'];
$phone = $_POST['phone'];
$comment = trim($_POST['comment']);
$available = trim($_POST['available']);
// Insert into mysql db
$ins = mysql_query(sprintf("INSERT INTO table (type,comment,available,phone,account) VALUES ('%s','%s','%s','%s','%s')", $type,$comment,$available,$phone,$acct)) or die(mysql_error());
$sched = mysql_query(sprintf("SELECT * FROM table ORDER BY type asc"));
$return['msg'] = "
<table border='1'>
<tr>
<th>Type</th>
<th>Account</th>
<th>Comment</th>
</tr>";
while($rowu = mysql_fetch_array($sched)) {
$return['msg'] .= "
<tr>
<td>{$type}</td>
<td>{$acct}</td>
<td>{$comment}</td>
</tr>";
}
$return['msg'] .= "</table>";
// header("Content-Type: text/javascript; charset=utf-8");
// $return['msg'] = "Testing " .$account . "works";
header('Content-Type: application/json');
echo json_encode($return);
Invalid JSON is being returned possibly due to the emission of a notice of undefined array index msg for $return, but more likely because of the emission of a lot of HTML. Essentially this returns:
<some html>JSON<some html>
This is not valid JSON, so jQuery will not call the success callback. Remove all of the HTML and emit only the JSON.
The response now works. I changed my code to the following and the results now show in my schedTable div without page refresh:
submitHandler: function(form) {
var data = $("#job").serialize();
$.ajax({
type: 'POST',
url: 'response.php',
data: data,
cache: false,
success: function(data) {
$('#job')[0].reset();
$('#schedTable').html(data).fadeIn('fast');
}
});
}
However, now the results that are displayed are not entirely correct. Say, for instance, I submitted 3 jobs via the form, only the third job will display 3 times instead of all 3 jobs in the database displaying. Guess, I'm back to the drawing board with searching for this issue. Thanks for the advice Explosion Pills and Musa.
Update: Changing the while loop into a json array method fixed this issue. Everything is now working properly.
<script>
function loadXMLDoc() {
$("input[class=search]").bind("keyup",function(){
$.get("search.php?search="+$(this).val(),
function(data){
if(data==1) {
alert("this is valid search")
} else {
alert("this is a right user search");
}
}
);
});
}
</script>
Below is the button image code
<table width="165" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<img src="images/search_box_left_im.png" width="3" height="28" />
</td>
<td class="inputbox_bg" width="118px">
<input type="text" name="search" class="username">
</td>
<td>
<input type="image" onclick="loadXMLDoc()" src="images/search_go_btn.png" border="0" width="44" height="28" />
</td>
</tr>
</table>
It is going to the function but not executing the ajax code
Change this:
<script>
function loadXMLDoc()
{
$("input[class=search]").bind("keyup",function(){
$.get("search.php?search="+$(this).val(),function(data){
if(data==1){
alert("this is valid search")
}else{
alert("this is a right user search");
}
})
})
}
</script>
to this:
<script>
function loadXMLDoc()
{
$("input[name=search]").bind("keyup",function(){ //<- important bit here
$.get("search.php?search="+$(this).val(),function(data){
if(data==1){
alert("this is valid search")
}else{
alert("this is a right user search");
}
})
})
}
</script>
$(document).ready(function(){
$(".username").keyup(function(event){ //<- important bit here
$.get("search.php?search="+$(this).val(),function(data){
if(data==1){
alert("this is valid search")
}else{
alert("this is a right user search");
}
});
});
$('input[type=image]').click(function() {
$('.username').keyup();
});
});
Please try this:
<script>
function loadXMLDoc() {
$.ajax({
type: 'GET',
url: 'search.php?search='+$(".username").val(),
success: function(data){
if(data==1) {
alert("this is valid search")
} else {
alert("this is a right user search");
}
}
});
}
</script>
Your <input type="image" ... /> is a submit button for the form.
What you want to do is change its default behaviour (submitting form) to alternative - execute some code.
Here is a good question about this: event.preventDefault() vs. return false
Besides that, you are assigning an event listener twice - once in your <input onclick="" /> and second time inside the event handler $("input[class=search]").bind()
Try removing your <input onclick="" /> and define event listener in $(document).ready():
<script>
$(document).ready(function() {
$("input[class=search]").bind("keyup",function(e){
e.preventDefault();
$.get("search.php?search="+$(this).val(),function(data){
if(data==1){
alert("this is valid search")
}else{
alert("this is a right user search");
}
});
});
});
</script>
...
<input type="image" src="images/search_go_btn.png" border="0" width="44" height="28" />
...