How post more than one variable in javascript? - javascript

There is 2 input type="text". First, user input 1st input text area with id="ncr_no". Then, cursor is in 2nd input type "text" with id="itm_cd". Now, I want to make, how the two input by user, when cursor is in 2nd input type, posted to other php (get_ncrnoitmcd.php) by javascript? That's the code.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){$("#user-result3").html('');return;}
if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post('get_ncrnoitmcd.php', {'itm_cd':itm_cd}, function(data) {
$("#user-result3").html(data);
});
}
});
});
</script>
Thank a lot.

This is the way you can send the 2 values to server on 2nd element keyup after validation. Whats the problem that you are facing? I also added ncr_no in the post request.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){
$("#user-result3").html('');
return;
}else if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post(
'get_ncrnoitmcd.php'
,{'itm_cd':itm_cd,'ncr_no':$('#ncr_no').val()}
,function(data) {
$("#user-result3").html(data);
}
);
}
});
});
</script>

I want to get available or not available, Mr. #joyBlanks
<?php
//connection.php
if(isset($_POST["itm_cd"],$_POST["ncr_no"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$itm_cd = strtolower(trim($_POST["itm_cd"]));
$itm_cd = filter_var($itm_cd, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$results = mysqli_query($connecDB,"SELECT itm_cd,ncr_no FROM sqc_ncr WHERE itm_cd ='$itm_cd' AND ncr_no ='$ncr_no'");
$itm_cd_exist = mysqli_num_rows($results);
if($itm_cd_exist) {
die('<!--img src="image/available.png" /--> <i>Available in database</i>');
}else{
die('<!--img src="image/not-available.png" /--> <i>Not Available in database</i>');
}
mysqli_close($connecDB);
}
?>

I've not used , and used && and not used http_x_requested, but available or not available in html not shown.
<td><input type="text" class="input" name="itm_cd" id="itm_cd" onBlur="updateItemName()" required /> <span id="user-result3"></span></td>

Related

Trying to run two functions on a form they both work independantly but cant get the both to work

in essence, I'm trying to validate a single field on a form to make sure it has content (Will eventually want to set a field length too) if the field validates then the second function should run. I've tried putting both functions in the action with && but that doesn't work - I've tried adding the field validation to an click on the button that works - but then doesn't run the next part
Any ideas?
<script type="text/javascript">
function OnSubmitForm()
{
if(document.ScriptFill.status[0].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=unfilled";
}
else
if(document.ScriptFill.status[1].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=filled";
}
else
if(document.ScriptFill.status[2].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=void";
}
return true;
}
</script>
<script type="text/javascript">
function validateForm() {
var x = document.forms["ScriptFill"]["Pharmacy"].value;
if (x == "") {
alert("You must enter your GPhC / RCVS number");
//return false;
}
}
</script>
Whate you can do is something like this in your javascript part:
<script type="text/javascript">
function OnSubmitForm()
{
/** Do what you want **/
document.getElementById('form').submit();
}
/** Considering this to be the first function you want to call **/
function validateForm() {
// Perform all the validations here
if(your validations pass){
/* Call your second function */
OnSubmitForm();
}
else{
return false;
}
}
</script>
Your HTML:
<form action='<your_action>' id='form'>
<input type='button' onclick='validateForm()' value='Submit'/>
</form>

Jquery Ajax On-Focusout On-Submit - Requires 2 Clicks

Hello I have a jquery and ajax validation form, when you fill the values (wrong values) x#x.com and 1111111 in password it will give ajax validation notice (which is fine) but after that if you put in the values (correct values) example#example.com and 12345678 it requires two clicks to submit. Meaning if you put wrong values first and then put correct values then it will require two clicks to submit. following is the code. I have set the code below so you can copy and paste the code into files (filenames given before) and you will have a working model to work with. I have hardcoded the php validate file so you guys can copy and paste the code and see how it works.
index.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
</head>
<body>
<form method="post" name="loginform" action="success.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
<div class ="errormsg" id ="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
<div class ="errormsg" id ="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class ="errormsglast" id ="errormsg8"></div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="validatelogin.js"></script>
</body>
</html>
validatelogin.js
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
$("#login").on('click', validate_email_login);
$("#login").on('click', validate_password_login);
/* ----------------- Stop on Submit */
$("#login").on('click', function()
{
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
validatelogin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_GET['f']==1) {
if(isset($_POST['user_email2'])) {
$user_email2 = strtolower($_POST['user_email2']);
if($user_email2 == "example#example.com") {
echo "exists";
} else {
echo "ok";
}
}
}
if($_GET['f']==2) {
if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
$user_email2 = strtolower($_POST['user_email2']);
$user_password2 = $_POST['user_password2'];
if($user_email2!="example#example.com" and $user_password2!="12345678") {
echo "WrongPw";
} elseif($user_email2=="example#example.com" and $user_password2=="12345678") {
echo "CorrectPw";
}
}
}
?>
success.php
<?php
echo "Login Successful";
?>
Tried Solutions
1. Putting a delay on the submit button
2. On Keyup instead of on Focusout (this works but not what is required)
3. Give delay to keyup (could not get it to work with ajax - but its closer to what I require, but not exactly what I require
4. Triggering the click on submit on return true of ajax (also did not work)
I need some javascript expert to look into it and give me solution.
Okay, I don't want to be rude, but all that code is a bit of a disaster. You're calling the on click function 3 different times, you're making ajax calls to the server on every form change and on submit. Then you're actually making two separate ajax calls for the actual submit function.
The code below is a lot more compact, only ever makes one ajax call and should work. I'll explain a bit before each code block
Your form add an id so that jQuery can use serialize in the ajax call
<form method="post" id="loginform" name="loginform" action="success.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
<div class ="errormsg" id ="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
<div class ="errormsg" id ="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class ="errormsglast" id ="errormsg8"></div>
</form>
validatelogin.php - This should only be one call to the server, do both functions in one, return the data as json rather than echoing single values, that way you get an object back that you can parse in your jQuery code.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
$user_password2 = $_POST['user_password2'];
$user_email2 = strtolower($_POST['user_email2']);
if($user_email2 != "example#example.com") {
$data['email_check'] = 'false';
} else {
$data['email_check'] = 'true';
}
$data = array;
if($user_email2!="example#example.com" && $user_password2!="12345678") {
$data['password_check'] = 'false';
} else {
$data['password_check'] = 'true';
}
}
print(json_encode($data));
jQuery - I am not really sure why you're calling all these functions on blur and the multiple on clicks. Just do it in the one on click, call validate email, if that passes you move on to validate password and if that passes it makes the ajax call to actually check the details against the server.
Also avoid variable names like item5, errormsg6, to another developer that means nothing, and it won't to you in 6 months either. And don't tell people which element was wrong, ie "Incorrect password" just for security, just tell them their login details are wrong.
$(document).ready(function() {
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function() {
var email = $("#user_email2").val().toLowerCase();
var errors = [];
if (email.length < 6 || email.length > 50) {
errors.push("Email : 6 - 50 Characters<br>");
}
if (!emailformat.test(email)) {
errors.push("Wrong Email Format");
}
if( errors.length > 0 ) {
$("#errormsg6").html(errors);
return false;
}
$("#errormsg6").html();
validate_password_login();
}
/* ----------------- Define Validate Password */
var validate_password_login = function() {
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20) {
$("#errormsg7").html("Password : 8-20 Characters");
return false;
}
$("#errormsg7").html("");
submitForm();
}
var submitForm = function() {
$.ajax({
type: 'POST',
url: 'validatelogin.php',
dataType: "json",
data: $("#loginform").serialize(),
success: function(msg) {
if(msg.email_check == 'true' && msg.password_check == 'true') {
//do whatever it is you want to do on correct login here
} else {
$("#errormsg6").html("Your login details are incorrect, please check and try again");
}
}
});
}
/* ----------------- Stop on Submit */
$("#login").on('click', function() {
errors = [];
if(validate_email_login() == true) {
alert("hi");
}
});
});
You can see the error validation on the jQuery end here: https://jsfiddle.net/calder12/3fhvpenr/

Disable rating stars after once rated js

Hi I want to put rating stars on my webpage.
Its is working fine. Rating is being added to database
But a user can rate again and again.
I want that stars should disable after rate once.
Here is my code. Kindly help me Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://online-btw-berekenen.nl/rating/rating.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://online-btw-berekenen.nl/rating/rating.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: '',
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
</script>
<style type="text/css">
.overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;}
</style>
</head>
<body style="background-color:black">
<h1>Give us star</h1>
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span>
Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span> rating)</span></div>
</body>
</html>
Click and Hover funtion in javascript.
(function(a){
a.fn.codexworld_rating_widget = function(p){
var p = p||{};
var b = p&&p.starLength?p.starLength:"5";
var c = p&&p.callbackFunctionName?p.callbackFunctionName:"";
var e = p&&p.initialValue?p.initialValue:"0";
var d = p&&p.imageDirectory?p.imageDirectory:"images";
var r = p&&p.inputAttr?p.inputAttr:"";
var f = e;
var g = a(this);
b = parseInt(b);
init();
g.next("ul").children("li").hover(function(){
$(this).parent().children("li").css('background-position','0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px')
},function(){});
g.next("ul").children("li").click(function(){
var a = $(this).parent().children("li").index($(this));
var attrVal = (r != '')?g.attr(r):'';
f = a+1;
g.val(f);
if(c != ""){
eval(c+"("+g.val()+", "+attrVal+")")
}
});
g.next("ul").hover(function(){},function(){
if(f == ""){
$(this).children("li").slice(0,f).css('background-position','0px 0px')
}else{
$(this).children("li").css('background-position','0px 0px');
$(this).children("li").slice(0,f).css('background-position','0px -28px')
}
});
function init(){
$('<div style="clear:both;"></div>').insertAfter(g);
g.css("float","left");
var a = $("<ul>");
a.addClass("codexworld_rating_widget");
for(var i=1;i<=b;i++){
a.append('<li style="background-image:url('+d+'/widget_star.gif)"><span>'+i+'</span></li>')
}
a.insertAfter(g);
if(e != ""){
f = e;
g.val(e);
g.next("ul").children("li").slice(0,f).css('background-position','0px -28px')
}
}
}
})(jQuery);
ok, in you click handler just remove the click event listener using the jquery off() method.
There are a few steps to disable to click and hover events AFTER a user has successfully selected (& recorded) a rating:
Add a line into your ajax success
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
$('.codexworld_rating_widget').addClass('already_set');
}else{...
Then add a function to disable each hover & click on the <li> in the "http://online-btw-berekenen.nl/rating/rating.js" script. See example below:
g.next("ul").children("li").hover(function(){
if ('.codexworld_rating_widget.alreadyset') {
$('.codexworld_rating_widget').off('click','li').off('hover','li');
}else{
// original script goes here
});
});
Anyways, I'm not able to test it without building a sandbox, so...hope it helps to point you in the right direction.

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

Jquery $.post() gives same page in HTML back

I have written a page so i can create a friendship between users. But my Problem is that jquery wont post the parameters.
I need some help, to fix that issue.
My Code:
//currentURL -> e.g: firstname.lastname
$('#friendRequestButton').on("click",function(e){
if(currentURL != "" && typeof(currentURL) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL})
.done(function(data) {
console.log(data); // Here I get the same page(in HTML-format).. as result in the console.
});
//$('#friendRequestButton').attr("disabled","true");
}
});
If you need more details, let me know.
My PHP-Code:
<?php
if(isset($_POST['user1']) && isset($_POST['user2'])){
$user1 = $_POST['user1'];
$user2 = $_POST['user2']
die("OK!");
}else {
die("NOO!");
}
?>
EDIT: I changed the way you mentioned with e.preventDefault();
<?php
$friends = false;
if(!$friends){
?>
<center>
<button class="submit" id="friendRequestButton">Ask for friendship</button>
<br />
<br />
<button>Send Message!</button>
</center>
<script>
$(document).ready(function(e){
$('#friendRequestButton').on("click",function(e){
console.log(e.target);
e.preventDefault();
if(currentURL != "" && typeof(currentURL) != "undefined" && $.cookie("user-id") != "" && typeof($.cookie("user-id")) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"), user2:currentURL},function(data){
console.log(data);
}
);
//$('#friendRequestButton').attr("disabled","true");
}else {
console.log("NOOOOO");
}
});
});
</script>
<?php
}
?>
Without seeing the html it is a guess, but judging by the name of your element you are using a button. Probably that button submits the form the "normal" way, causing your page to reload and you to not see the results of your ajax call.
If that is the case, you need to prevent the default event for the button press (submitting the form in this case):
$('#friendRequestButton').on("click",function(e){
e.preventDefault();
// the rest of your code
use your ajax request like this-
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL}),function(data){
console.log(data);
});
I found the ISSUE:
I'm SOOOO Stupid:
I have written the filename like this: sendFriendRequest..php (two dots)
It should be: sendFriendRequest.php
So thanks everyone for helping!! :D

Categories

Resources