Jquery to limit the range of input - php

I have a text box that takes input as amount..I want to prevent the user from entering Amount greater than a certain amount..I tried using ajax ..but its not working the way i want..I think jquery wud do the needful..but I am not so good at it..If any one can help??
Ajax function that i Have written:
function maxIssue(max, input, iid) {
var req = getXMLHTTP();
var strURL = "limit_input.php?max=" + max + "&iid=" + iid;
if (input > max) {
alert("Issue Failed.Quantity Present in Stock is " + max);
}
if (input < 0) {
alert("Issue Failed.Enter positive Value");
}
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('maxdiv').innerHTML = req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
}
req.open("GET", strURL, true);
req.send(null);
}

Have you tried to use maxLength ?
<input maxLength="10"/>

$('input').on('keyup', function(){
if($(this).val() > someNumber){
$(this).prop('disabled', true);
alert('You cannot enter that many characters.');
}
});

It will helpful for your task.
<input type="text" name="usrname" maxlength="10" />
function limitText(field, maxChar){
$(field).attr('maxlength',maxChar);
}

Using jquery validation is pretty simple. You have to define rules and message you want to display for validation, and attach it with your form element.
This tutorial is great help.
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
Here's 101 on validation, in case you want to try it out. I am using cdn, but you can add reference to library in your path.
<html>
<head>
<title>Validation Test</title>
<!-- Importing jquery and jquery ui library from cdn -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.js"></script>
<!-- End of Import -->
</head>
<body>
<script>
$(document).ready(function(){
$("#testvalidation").validate({
rules: {
title: "required",
description: {
required:true,
maxlength:4000
}
},
messages: {
title: "Title is Required",
description: {
required : "Description is Required",
maxlength: "Should be less than 4000 Characters"
}
}
});
});
</script>
<style>
#testvalidation .error{
color: #FB3A3A;
font-weight:300;
}
</style>
<form action=update.jsp class="form-horizontal" id="testvalidation">
<input name="title" type="text"></input><br>
<textarea name="description"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

Unable to send POST request using AJAX

I am unable to send POST request to my php file using AJAX. I have two files, the first one is index.php and second isVerificationStatusAPIV2.php. Contents of index.php are:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Phone Verification by Dial2Verify API V2 ( www.dial2verify.com )</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var attempt=1;
var transactionToken="";
$(document).ready(function(){
$("#enter_number").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
});
function initiateDial2Verify() {
showCodeForm(1);
GetVerificationImage();
}
function showCodeForm(code) {
$("#dial2verify").fadeIn();
$("#enter_number").fadeOut();
$("#waiting_msg").text("Waiting for missed call from "+$("#phone_number").val());
}
function GetVerificationImage() {
$.post("GetImageAPIV2.php", { phone_number : $("#phone_number").val() },
function(data) { updateImage(data.img,data.transactionToken); }, "json");
}
function updateImage(img, vtransactionToken) {
$("#Image").html("Please give a missed call to <br><img src=\""+img+"\"/>");
transactionToken = vtransactionToken;
PollStart("0");
}
function CheckStatus()
{
$.post("VerificationStatusAPIV2.php", { transactionToken : transactionToken },
function(data) { PollStart(data.status); }, "json");
}
function PollStart(vStatus)
{
attempt =attempt+1;
if ( attempt >= 90 ) { TimeoutCheck(); }
else
if (vStatus === "0") {
$("#status").html("Please give a missed call in <b><i>"+(90-attempt) +"</i></b> seconds.");
setTimeout(CheckStatus, 1000);
}
else if (vStatus === "1")
{
success();
}
else
TimeoutCheck();
}
function Err() {
$("#status").html("Error!<br>Sorry something went wrong, Please cross check your telephone number.");
}
function success() {
$("#status").text("Congrats !!! Phone Number Verified!");
}
function TimeoutCheck() {
$("#status").text("Verification Failed!");
}
</script>
</head>
<body>
<form id="enter_number">
<p>Enter your phone number:</p>
<p><input type="text" name="phone_number" id="phone_number" /></p>
<p><input type="submit" name="submit" value="Verify" /></p>
</form>
<div id="dial2verify" style="display: none;">
<p id="waiting_msg"></p>
<p id="Image">Loading ..</strong></p>
<p id="status">Loading ..</strong></p>
</div>
</body>
</html>
In function CheckStatus() I am sending a post request using AJAX to file VerificationStatusAPIV2.php but it isn't making any post request. can someone tell what's wrong in that?
Update I just saw that "status" in "data.status" in func CheckStatus() is in yellow color while others in blue color. maybe thats the problem?
In your code snipped the only place you have CheckStatus exept for the function itselft is this line ... setTimeout(CheckStatus, 1000); so if this is the function call it'S should be like this : setTimeout(CheckStatus(), 1000);
This may be your problem.
Try changing
<input type="submit" name="submit" value="Verify" />
to
<input type="submit" id="btn_enter" name="submit" value="Verify" />
and in the js:
$("#btn_enter").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
you were pointing your submit function to the HTML form's ID
var request=$.ajax({
method:"POST",
url:"VerificationStatusAPIV2.php",
data:{ transactionToken : transactionToken },
dataType:"json"
});
request.success(function(data){
PollStart(data.status);
});

Modal not validating when elements generated through external file

I've been experimenting with modal dialogue boxes and came across one which uses the FancyBox JQuery tool. I am trying to understand why the validation script works correctly when the modal elements are in HTML form on the same page (in the body tags) as the script, however if I generate these elements in a php file the validation script fails.
Please see my index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="style-modal.css">
<link rel="stylesheet" type="text/css" media="all" href="fancybox/jquery.fancybox.css">
<script type="text/javascript" src="fancybox/jquery.fancybox.js?v=2.0.6"></script>
<script type ="text/javascript" src="like2.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function() {
$(".load").load('show.php');
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var commentid = $("#commentid").val();
alert("clicked!");
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
$("#send").replaceWith("<em>Sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
});
}
});
});
</script>
</head>
<body>
<div class="load">
</div>
</body>
</html>
Please see the php file "show.php" which I load:
<?php
include('connect.php');
echo '<div class="load">
<button class="modalbox" href="#inline">Click</button>
</div>
<div id="inline">
<h3>Enter your email to receive updates</h3>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<input type="hidden" id="commentid" name="commentid" value="5">
<br>
<button id="send">Send E-mail</button>
</form>
</div>
</div>';
?>
In this format when I click "Click" on index.php, the modal appears as normal, however when I click "Send E-mail" with or without data, the modal fades without any feedback or validation. Is it possible to work with this set up? All works as expected when the contents of div id="inline" from show.php are put into the body of index.html. Please assist

Use jQuery validation on anchor tag click

I want to use jQuery validation on anchor tag click event. Here is my HTML form and jquery
HTML Form :
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer" >Search</a>
</form>
jQuery Code:
$(document).ready(function () {
$("#submit").click(function () {
$("#search_booking").validate({
rules: {
job_date: {required: true}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function (form) {
form.submit();
}
});
});
});
After clicking on anchor tag it will not submitting form to the form action.
Thanks in advance.
You need to initialize the validator plugin in dom ready and then in the submit button click, call the form's submit event which will do the validation.
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function() {
$("#search_booking").submit();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer">Search</a>
</form>
This is very similar to the accepted answer except for two things...
I'm using an event.preventDefault() to block the default behaviors of the anchor element.
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
I've added a href="#" so that the jump to the top of the page can be properly blocked by the .preventDefault(), as well as to maintain HTML standards compliance.
<a id="submit" href="#" style="cursor: pointer">Search</a>
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
// form.submit(); //default plugin behavior
alert('submission'); // only for demo
}
});
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" href="#" style="cursor: pointer">Search</a>
</form>

jquery get data using jquery.load

i have a problem similar to my previous question but now its different
jquery : progress bar show in html
var auto_refresh = setInterval(
function ()
{
$('#battery').load('https=://localhost/userinfo/battery_level/');
}, 10000);
i dont want to load the div ... i want to get the result and want to display in my progress bar here
$('.demo-progress').progress(data);
i am geting a value here "10"
want to do something like this
var auto_refresh = setInterval(
function ()
{
var data = $('#battery').load('https=://localhost/userinfo/battery_level/');
}, 10000);
$('.demo-progress').progress(data);
Try this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css" rel="Stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$("#progressbar").progressbar({ max: 100, value: 10 });
$("#twenty").click(function () { loadFile("20"); });
$("#fifty").click(function () { loadFile("55"); });
$("#eighty").click(function () { loadFile("80"); });
});
function loadFile(file) {
$.get(file + ".txt", function (data) {
var value = parseInt(data, 10);
$('#progressbar').progressbar("option", "value", value);
});
}
</script>
</head>
<body>
<div id="progressbar">
</div>
<input type="button" id="twenty" value="Load to 20%" />
<input type="button" id="fifty" value="Load to 50%" />
<input type="button" id="eighty" value="Load to 80%" />
</body>
</html>
From the jquery page:
This method (.load) is the simplest way to fetch data from the server.
It is roughly equivalent to $.get(url, data, success) except that it
is a method rather than global function and it has an implicit
callback function.
The reason why I am using .get is because of the last part, the implicit callback function, which let's me know when the function has ended, and I can then update the progressbar.

fetch multiple urls data using PHP Curl, Jquery In Loop

I found this script from (http://w3lessons.info/2012/01/03/facebook-like-fetch-url-data-using-php-curl-jquery-and-ajax/) Problem is that i want to do in loop with multiple urls.
<link rel="stylesheet" type="text/css" href="style.css" />
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style-ie.css" />
<![endif]-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/jquery.livequery.js"></script>
<script type="text/javascript" src="js/jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// delete event
$('#attach').livequery("click", function(){
if(!isValidURL($('#url').val()))
{
alert('Please enter a valid url.');
return false;
}
else
{
$('#load').show();
$.post("curl_fetch.php?url="+$('#url').val(), {
}, function(response){
$('#loader').html($(response).fadeIn('slow'));
$('.images img').hide();
$('#load').hide();
$('img#1').fadeIn();
$('#cur_image').val(1);
});
}
});
// next image
$('#next').livequery("click", function(){
var firstimage = $('#cur_image').val();
$('#cur_image').val(1);
$('img#'+firstimage).hide();
if(firstimage <= $('#total_images').val())
{
firstimage = parseInt(firstimage)+parseInt(1);
$('#cur_image').val(firstimage);
$('img#'+firstimage).show();
}
});
// prev image
$('#prev').livequery("click", function(){
var firstimage = $('#cur_image').val();
$('img#'+firstimage).hide();
if(firstimage>0)
{
firstimage = parseInt(firstimage)-parseInt(1);
$('#cur_image').val(firstimage);
$('img#'+firstimage).show();
}
});
// watermark input fields
jQuery(function($){
$("#url").Watermark("http://");
});
jQuery(function($){
$("#url").Watermark("watermark","#369");
});
function UseData(){
$.Watermark.HideAll();
$.Watermark.ShowAll();
}
});
function isValidURL(url){
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
}
</script>
<input type="hidden" name="cur_image" id="cur_image" />
<div class="wrap" align="center">
<div class="box" align="left">
<input type="text" name="url" size="64" id="url" />
<input type="button" name="attach" value="Attach" id="attach" />
<div id="loader">
<div align="center" id="load" style="display:none"><img src="load.gif" /></div>
</div>
</div></div>
Is there any i can do loop and load the different different url same time? Please help me!
In JavaScript who can't create thread.
So you can't fetch all those "different url at same time".
But you can "almost" achive the same thing using the event loop to request them quickly one by one without waiting for the HTTP response. Who end up being very quick !
Let's say for exemple you want to featch 3 url:
www.mysite.com/myurl1
www.mysite.com/myurl2
www.mysite.com/myurl3
You can write something like that using jQuery:
$.get('http://www.mysite.com/myurl1', function(data) {
alert('html for site 1:' +data);
});
$.get('http://www.mysite.com/myurl2', function(data) {
alert('html for site 2:' +data);
});
$.get('http://www.mysite.com/myurl3', function(data) {
alert('html for site 3:' +data);
});
It will request the 3 page "almost" in the same time.
The first HTTP request will call the "alert('html for site x:...');"
but you don't know witch one will arrived first.
Anyway you probably need something more flexible.
Let's say you want to request 50,000 pages requesting them in "almost" the same time using 200 simultaneous request.
You can write something like that in JavaScript:
function getNextUrl(){
urlIndex ++;
if(urlIndex >= stopAtIndex){
//nothing to do anymore in the event loop
return;
}
$.get('http://www.mysite.com/myurl'+urlIndex, function(data) {
// html receivend here
getNextUrl();
});
}
/* program start here */
int urlIndex = 0;
int stopAtIndex = 50000;
int simultaneousRequest = 200;
for( var i = 0; i < simultaneousRequest; i++ ) {
getNextUrl();
}

Categories