javascript validate form values from database - php

The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?
$this->campaign is an array which contain all campaign details from database.
<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
<?
foreach($this->campaign as $c)
{
$old_cname=$c['name'];
?>
if(name==<?=$old_cname;?>)
{
alert("same name exists in database. Try again!");
}
<?
}
?>
if(!name)
{
alert("Please enter a name!");
return false;
}
if(!shape)
{
alert("Please select shape!");
return false;
}
return true;
}
</script>
<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>
Thanks!

You can't mix php and javascript like that.. php is a server-side language, while javascript is client-side; php renders the page before the user sees it, while javascript modifies the page without refreshing. Any php values in your js will get rendered and output before the js even executes.
In order to do what you need, you need to use ajax, which is asynchronous javascript and xml, a method of client-server communication that allows for what you want to happen.
To do this, I would suggest jQuery, a javascript library which makes such requests very simple. As an example of how you would make such a request in jquery....
The jQuery.ajax() method:
$.ajax({
url: "validate.php",
type: "POST",
data: "username=" + username,
sucesss: function(data) {
if (data == 1)
$("#ajax_div").html("Username is taken, choose another!");
}
else {
$("#ajax_div").html("Username is free :)");
}
}
});
That would be how to do it in ajax, while your php file would either return a 1 or a 0 depending on the result of an sql query comparing usernames in the database.
To do this without jquery, it would be something like this:
function checkUsername() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == 1) {
document.getElementById('ajax_div').innerHTML = "Username is taken, please choose another!";
}
else {
document.getElementById('ajax_div').innerHTML = "Username is free :)";
}
}
}
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username=" + username);
}
}

You should use jquery to validate using a php script. The best way to do this is to disable the submit button until all fields are verified. This requires that you to listen to keystrokes then make a jquery call to validate the input field. A simple example below
script.js
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
type: "POST",
url: 'ajax/validate.php',
data: 'cname='+$('#name').val(),
success: function(data) {
if(data == "original"))
//enable the submit button
else
//Update your div that contains the results
}
});
}
ajax/validate.php
<?PHP
//Run your validations here
?>

Related

Executing PHP with AJAX

I'm trying to run a php file with AJAX from my "main.php".
The problem is that it doesnt let my stay on the main.php and moves me to "tallennus.php", when I want to stay at "main.php". The tallennus.php should be done on the background.
"tallennus.php" does it's work perfectly (saves data to database). But I want to stay on mainsite while it does it.
Im trying to use AJAX to run "tallennus.php" on the background.
Why does the site change from main.php to tallennus.php?
<button onclick="testi()">testi</button><br>
<script>
function testi()
{
alert("function started");
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
}
xmlhttp.open("get", "tallennus.php",true);
xmlhttp.send();
}
</script>
The default type of <button> is type="submit", so it submits the form. Change it to type="button".
<button type="button" onclick="testi()">testi</button><br>
As per the following reference:
https://www.w3.org/TR/html-markup/button.html
"A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"."
I fixed my problem by doing this:
<script>
function tallenna()
{
var tunnus=document.getElementById('tunnus').value;
var nimi=document.getElementById('nimi').value;
var deadline=document.getElementById('deadline').value;
var vaihe=document.getElementById('vaihe').value;
var dataString=
'tunnus='+ tunnus +
'&nimi='+ nimi+
'&deadline='+ deadline+
'&vaihe='+ vaihe;
$.ajax({
type:"post",
url: "tallennus.php",
data: dataString,
cache:false,
success:function(html){
$('#msg').html(html);
}
});
document.getElementById("frm").reset();// for clearing form
return false;
}
</script>
<br><input type="submit" value="TALLENNA" onclick="return tallenna()">

Changing border color with help of JQuery & Ajax

Is it possible to change border color of Textbox if that Username is not available in MySQL with help of Ajax & JQuery with PHP? I've searched a lot on web but all I get is how to change innerHTML of div using Ajax which is useful if I want to show Tick or Cross image. Please Help
make ajax call like below and pass user name with formdata and check with database.if you can't get username from your database then send flag 'false' in response.
$.ajax({
type: "POST",
url: "your_url to post",
data: formdata,
dataType: 'json',
success: function (msg) {
if(msg=='false')
$('#tbxControl').attr('style','border:1px solid #000');
}
});
Check jQuery documentation "how to change style of element"
Check jQuery documentation "how to send ajax request"
Combine 1) and 2): send a request that checks username, in callback function
adapt style of element
It is very easy. You can change the border based on an ajax response; to change the border, use the css method on a jQuery object.
Example:
http://jsfiddle.net/mCk6z/
jQuery(function(){
$('#username').css({'border': '1px solid #000'});
});
Check out this tutorial.
If you go to the Jquery part, after the line 40, you just need to add:
$('#username').css({border: "1px solid red"});
Hope it helps!
Cheers
You could create a bad username class
.badUsername{
Border-colour: <colour of your choice>
}
Then in the ajax success or fail function you can apply this class to the textbox
$(#<TextboxID>).addClass(badUsername);
(You can also use removeClass or hasClass to perform checks on the element)
Another option is to adjust the style directly in the success or fail function
$(#<TextboxID>).css(“border-colour: <colour of your choice>;”);
Solution which worked for me :)
HTML
<input type="text" name="eMailTxt" id="eMailTxt" class="texttt" placeholder="Email Address" onChange="showUser(this.value)" />
AJAX
function showUser(str)
{
if (str=="")
{
$('#eMailTxt').css({'border':'blue 2px solid'});
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText=="false")
{
$("#eMailTxt").css({'border':'red 2px solid'});
}
else
{
$("#eMailTxt").css({'border':'green 2px solid'});
}
}
}
xmlhttp.open("GET","login.php?q="+str,true);
xmlhttp.send();
}
PHP
<?php
$q=$_GET["q"];
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT Email FROM persons WHERE EMAIL = '".$q."'";
$data=mysqli_query($con,$check);
$result=mysqli_fetch_array($data);
if ($result[0]==$q)
{
echo "true";
}
else
{
echo "false";
}
?>

Check if record exists in mySQL Database on blur

I am thinking on how to implement this scenario:
I have a table orders where there is a serialNumber field. Then I also a have a PHP page with a form. What I am thinking of doing is that, onBlur or on keypress enter/return of a <input type=text> field, I would like an ajax/jquery script to check the serial number from the text box input if it has an existing record in my mySQL database. Then the script will warn the user that the serial number exists already in the database and will not allow submission.
I know how to implement it with standard form submission but I was thinking is it can be done without the literal pressing of the submit button.
Is there a way to implement this?
for this you can use javascript. create on javascript that called on textbox on blur event.
here i created on function that called on textbox on blur event.
function CheckUserName(){
var UserName = document.getElementById('UserName');
if(UserName.value != "")
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var value = xmlhttp.responseText;
if(value.length > 1)
{
document.getElementById('ErrorSpan').innerHTML="User Name Already exist please choose Other User Name";
UserName.focus();
}
else
{
document.getElementById('ErrorSpan').innerHTML="";
}
}
}
xmlhttp.open("GET","checkUserName.php?q="+UserName.value,true);
xmlhttp.send();
}
}
and create one php file with the name checkusername.php and pass your value through query string.
php code as follow.
<?php
$q=$_GET["q"];
include("db_connect.php");
$sql="select * from usermaster where UserName='".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['UserName'];
}
mysql_close($con);
?>
here from php if username find it will return value and you can get value in your javascript function. i hope it will help you.
you can also use this method I checked it on keyup you can use it via onblur option.
<input type="text" value="" id="jform_domain_name" name="jform[domain_name]" onkeyup="checkAvailability();"/>
<div id="errormsg" class="no-display">Sorry, this name is not available!</div>
<div id="successmsg" class="no-display">Congratulations, this domain is available!</div>
<script>
function checkAvailability(){
jQuery('#ajaxloader').html('<img src="images/ajax-loader.gif" />');
var string = jQuery('#jform_domain_name').val();
if(string == ''){
jQuery('#ajaxloader').html('');
return false;
}
jQuery.ajax({
type : "POST"
,url : "YOUR_ACTION_URL"
,data :"string="+jQuery('#jform_domain_name').val()
,success : function(data){
if(data==0){
var errormsg = jQuery("#errormsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(errormsg);
}else{
var successmsg = jQuery("#successmsg").html();
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html(successmsg);
}
}
,complete : function(){
if( jQuery('#jform_domain_name').val() == "" ) {
jQuery("#ajaxloader").hide();
}
}
,beforeSend: function(html){
jQuery("#ajaxloader").show();
jQuery('#ajaxloader').html('<img style="padding-top:6px;" src="images/ajax-loader.gif" />');
return;
}
});
}
</script>
for reference I am providing my controller action and the model which I have used
//sample controller action
function checkdomain(){
$requestData = JRequest::get();
$return = $model->checkAvailabiLity($requestData['string']);
if($return === false){
echo 0;
}else{
echo 1;
}
die;
}
//sample model on which I created Query logic.
public function checkAvailabiLity($data){
$select = "SELECT id FROM #__jshopping_vendors WHERE domain_name = '".strtolower($data)."' AND user_id != ".$user->id."";
$db->setQuery($select);
$type = $db->loadObject();
if(isset($type->id) && $type->id >0){
return false;
}else{
return true;
}
}
hope this helps....

Submit one select field in ajax (not entire form) to get it's value and filter another select in php on same page

it's my first programming experience in Ajax (or Jquery) so i appreciate any kind of help.
What i am trying to do is that i have 2 select inputs in my html form i want when the first select is changed (onchange) to have its value to use it to filter the second select in php to dynamically generate its options, that must happen without submitting the entire form only the first select.
I tried the following code but whenever the first select changes it submit the entire form.
the ajax function:
function showKadaa(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("kop").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","annonce.php?mid="+str,true);
xmlhttp.send();
}
the html code portion with php:
<?php if(isset($_GET['mid']))
$q=$_GET['mid'];
else $q=$_SESSION['mid'];?>
//code goes here
<tr><td>Kadaa:</td><td><div id="kop"><select name="kadaa" id="kad" ><option value="default">[Choisir Kadaa]</option>
<?php
if(login_db()){
$req="SELECT `nom_kadaa`,`id` FROM `kadaa` WHERE `id_mohafaza`=".$q."";
echo $req;
$kadaa="";
if($res=mysql_query($req)){
while($l=mysql_fetch_array($res)){
echo "<option value=".$l[1].">".$l[0]."</option>";
}
}
}
?>
</select></div></td></tr>
P.S: WHERE EVER I PUT THE div of id="kop"
the entire page is submited in it. Another thing i using the two select on same page with
form action="<?php echo $_SERVER['PHP_SELF'];?>
for getting on field value:
jquery would love to use
$("#IdOfElement").val();
by the way, jquery has a lot more handy methods for ajax:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});

Javascript and php

I have a page called getvalues.php, I need to call a function which is written in a different php page(fileclass.php) in a class from this page(getvalues.php), but the issue is i need to pass a variable also which is $i, and the value of $i passed should be 1 if we are selecting option B, and $i=2 if option=c, and $i=3 if option=D given in dropdown. I had simply wiritten an onchange event but had not written any code in javascript. Please help Thanks. Here is the code for getvalues.php
<html>
<select id="s" onchange="callsome();">
<option value='B' selected>B</option>
<option value='c'>c</option>
<option value='D'>D</option>
</select></html>
<?php include("fileclass.php")
$obj=new file;
echo $obj->func($i);?>
You could implement this using JQuery or Javascript (I use JQuery in the example because it is shorter and easier to make Ajax calls) :
<html>
<select id="s" onchange="callsome();">
<option value='1' selected="selected">B<option>
<option value='2'>C</option>
<option value='3'>D</option>
</select>
<script>
function callsome() {
var selected = $('select#s option:selected').val();
$.ajax({
type: "POST",
url: "fileclass.php",
data: ({selectedvalue : selected}),
success: function(data) {
alert(data);
}
});
}
</script>
</html>
After that the callsome returns the output of the fileclass.php script and you can use that however you like in your code. From your explanation it was not really clear what is happening in fileclass.php and what you want to do with it, so I hope it helps you.
If you want the function in Javascript only:
<script type="text/javascript">
function callsome() {
var e = document.getElementById("s");
var strVal = e.options[e.selectedIndex].value;
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var data = xmlhttp.responseText;
//use the data as you wish
}
}
xmlhttp.open("GET","fileclass.php?selectedvalue=strVal",true);
xmlhttp.send();
}
</script>
This isn't the way PHP and HTML work.
PHP is rendered on the server. HTML is rendered on the client, after the PHP is completely done. To do what you want to do, you need to have the HTML (possibly Javascript) make a request to the PHP page at fileclass.php.

Categories