Check if record exists in mySQL Database on blur - php

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....

Related

Live update php variable and simultaneously, show the value in a textbox

This is my table row click function in the file, 'BAConsult.php'. On click, showconsultationdata function will run.
$(document).ready(function(){ //table row click
}).on('click','.consultclick tr',function(e){
if(e.target.tagName === "TD"){
$(".consultclick tr").removeClass("highlight");
$(e.target).parent().addClass("highlight");
}
var dateconsulted = $(this).attr('value');
alert(dateconsulted);
showconsultationdata(dateconsulted);
});
This is my ajax script
function showconsultationdata(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Here is another php file called 'BAConsultRecordsAJAX.php' where i placed the ajax of the showconsultationdata.
session_start();
require('Config/Setup.php');
$q = $_GET['q'];
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareremarks=$row['skincareremarks'];
$skinconditionremarks=$row['skinconditionremarks'];
}
On table row click, $skincareremarks and $skinconditionremarks should be updated. And these values will show up in the textboxes in the 'BAConsult.php' page. How can i do this?
So, i followed #Jeff's method by using JSON. However, I realised that the xmlhttp.responseText wasn't only showing my JSON encoded code, but also my javascript which was why the JSON.parse method was unable run properly. I then did the following:
In my BAConsultRecordsAJAX.php file, i did this.
echo "<div id='test1'>";
echo json_encode(array('first'=>$skincareremarks,'second'=>$skinconditionremarks));
echo "</div>";
I gave this output a div called 'test1'.
Then, in my main file's AJAX script, i did this.
var a = JSON.parse($(xmlhttp.responseText).filter('#test1').html());
document.getElementById("test").value=a.first;
So basically, it filters out the rest of the xhtmlhttp.responseText outputs, and selects only the contents in the div where id='test1'.
Hope this helps those who have this problem too..

How do I delete multiple MySQL entries via check boxes?

In my application I display the database contents in a table. For each row displayed, I add a check box to the end of the row:
echo '<td><input type="checkbox" name="ticked[]"></td>';
When the user has checked off however many boxes they wish to delete the entries for, they click this delete button (front end is zurb foundation framework):
Delete URL
When this button is pressed the deleteUrl ajax function is triggered:
function deleteUrl(str)
{
document.getElementById("content01").innerHTML="";
if (str=="")
{
document.getElementById("content01").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("content01").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str,true);
xmlhttp.send();
document.getElementById("content02").innerHTML = 'Your URL was successfully deleted!<br/><br/>';
xmlhttp.onreadystatechange = urlRefresh;
return;
}
The ajax function directs the process to my deleteUrl.php file:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<?php
$deleteUrl = $_GET ['$deleteUrl'];
if(isset($_GET['delete'])) {
if(is_array($_GET['url'])) {
foreach($_GET['url'] as $id) {
$query = "DELETE FROM contact WHERE url=". $url;
mysql_query($query)or die(mysql_error());
}
}
}
mysql_close();
?>
So far the process runs through, without error. However, the entries that are checked are not deleted during the process.
QUESTION: What do I need to do to make the delete process work using check boxes?
EDITED CODE:
function runDelete(str, id)
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str+"&ticked="+id,true);
Delete URL
echo '<td><input type="checkbox" name="ticked[]" value="'.$row['id'].'"></td>';
Can you please try this,
1 Step - Include jquery url in head tag
2 Step - include this code after jquery url,
<script type="text/javascript">
$(function(){
$("#deleteUrl").click(function(){
$('#content02').html('');
var tickedItems = $('input:checkbox[name="ticked[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "deleteUrl.php",
data: "ids=" + tickedItems,
success: function(msg) {
$('#content02').html('Your URL was successfully deleted!');
}
});
return false;
});
});
</script>
3 Step - Replace this code in deleteUrl.php,
<!--Include Database connections info-->
<?php include('config.php'); ?>
<?php
$deleteUrl = $_GET ['$deleteUrl'];
if(isset($_POST['ids'])) {
$idsArray = #explode(',', $_POST['ids']);
foreach($idsArray as $id) {
$query = "DELETE FROM contact WHERE url='".$id."' ";
mysql_query($query)or die(mysql_error());
}
}
mysql_close();
?>
4 Step - assign id/property row value into checkbox
<?php
echo '<td><input type="checkbox" name="ticked[]" value="'.$row['id'].'" ></td>';
?>
5 Step - Add this button for delete action
<button class="button radius expand" id="deleteUrl" name="deleteUrl" >Delete URL</button>
Corey, it's just suggestion not the exact answer of your query. you should try to make few correction in your code like the steps below.
very first you need to assign the value to checkbox like
echo '<td><input type="checkbox" name="ticked[]" value="'.$id.'"></td>';// $id it would different in your case
than pass the checkbox values through function call
onClick="deleteUrl('deleteUrl',checkboxvalue);
and modify function accordingly
function deleteUrl(str,checkboxvalue)
than pass the checkbox value to delete url
xmlhttp.open("GET","deleteUrl.php?deleteUrl="+str+"&ticked="+checkboxvalue,true);
than modify delete page to delete the records as per your checkboxvalue not the url and make sure that you are passing correct value from ajax and getting correct value on delete page.

PHP AJAX Confirm on Form Submit

I have a small form which contains a first name, last name and a date. On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. The confirm shouldn't show if there aren't any entries.
For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. Here is the code:
Javascript:
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+first;
url=url+"&last="+last;
url=url+"&date="+date;
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
result = xmlHttp.responseText;
alert("RESULT="+result);
if(result != "clean") {
var validate = confirm(result);
return validate;
}
}
}
xmlHttp.open("GET",url,true);
var test = xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP:
// DATABASE CONNECTION INFORMATION REMOVED
$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));
$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
"Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row['count'] > 0) {
if($row['count'] == 1) {
echo "There is already an entry for ".$first." ".$last." on ".
date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
else { // plural version of the same message
echo "There are already ".$row['count']." entries for ".$first." ".
$last." on ".date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
} else {
echo "clean";
}
Here is an answer using synchronous AJAX. This way, you don't have to overload the default form handling to get it to work. However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts.
This function will return true if the record should be added, and false otherwise.
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return false;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var validated = true;
var result = xmlHttp.responseText;
if (result != 'clean')
validated = confirm("RESULT="+result);
return validated;
}
This line of code return undefined.
var test = xmlHttp.send(null);
What you have to understand is that the send() call returns immediately and Javascript keeps running. Meanwhile, your AJAX request is running in the background. Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code.
I think what you wanted to submit the form AFTER the confirmation was finished. You only know when the request is finished from inside your onreadystatechange handler. The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form.
You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation.
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
var confirmed = false;
var result = xmlHttp.responseText;
if (result == "clean")
confirmed = true;
else
confirmed = confirm("RESULT="+result);
if (confirmed) {
var url = "addData.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
window.location = url;
}
}
}
Also, when you're building your URL you should use encodeURIComponent.
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);

javascript validate form values from database

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
?>

PHP Javascript AJAX fill and calculate several input fields - only one function fills?

I am trying to fill in a form using Javascript/ajax/php but the problem is that my function only fills in one of the needed forms and stops even tho I have gotten the second response from the server.
Code:
The function that starts filling stuff
function luePankkiviivakoodi(str) {
if (str==null) { //are we NOT injecting variables directly into the code, if not - Prompt for the barcode, and set the variable
var str = prompt("Valmis vastaanottamaan", "");
}
if (str==null) { //someone pressed abort on the prompt, we return
return;
}
newstr = str.split(' ').join(''); // remove spaces
if (str=="") { //is the string empty? -> return
return;
}
if (window.XMLHttpRequest) { //AJAX code
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
//we set some fields, no problem
document.getElementById('P_VII').value = viite;
document.getElementById('IBAN').value = saajatili;
document.getElementById('laskun_summa').value = summa;
document.getElementById('eräpäivä').value = eräpäivä;
//trigger other functions
getKassasumma(summa); //AJAX for accesing the database and calculating the sale price
DevideIntoCells(); //AJAX for accessing the database and dividing a sum into different cells
validateSumma(); //Validates the sum, and tells the user if it's OK
}
}
xmlhttp.open("GET","dataminer.php?question=pankkiviivakoodi&q="+newstr,true);//open AJAX connecttion
xmlhttp.send();//send stuff by AJAX
}
getKassasumma:
function getKassasumma(str) {
if (str=="") {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
eval(xmlhttp.responseText);
}
}
kale = document.getElementById("TOS_K_ale").value;
xmlhttp.open("GET","dataminer.php?question=kassasumma&q="+str+"&kale="+kale.replace("%", "p")+"&nro="+document.getElementById("S_NRO").value,true);
xmlhttp.send();
}
DevideIntoCells:
function DevideIntoCells() {
str = document.getElementById('tiliöintitapa').value;
if (str==null) {
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
document.getElementById("spinwheel3").style.visibility = "visible";
}
xmlhttp.onreadystatechange=function() {
//alert('OK! val= '+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//alert('OK!');
eval(xmlhttp.responseText);
//alert('OK2!');
document.getElementById("spinwheel3").style.visibility = "hidden";
//alert('OK3!');
calculateSumma();
}
}
xmlhttp.open("GET","dataminer.php?question=percentages&q="+str+"&nro="+document.getElementById('S_NRO').value,true);
xmlhttp.send();
}
validateSumma (just some math):
function validateSumma() {
float = document.getElementById('summabox').value;
float = float.replace(",",".");
summa = parseFloat(float);
if (summa < 0) {
summa = 0
};
kassasummaunp = document.getElementById('laskun_summa').value;
kassasummafloat = kassasummaunp.replace(",",".");
kassasumma = parseFloat(kassasummafloat);
if (kassasumma < 0) {
kassasumma = 0
};
if (kassasumma == 0 || summa == 0) {
prosentti = "0%";
}
else {
prosentti = summa / kassasumma * 100;
prosentti = Math.round(prosentti*Math.pow(10,2))/Math.pow(10,2);
prosentti = prosentti+"%";
};
if (prosentti == "100%") {
is100 = 1;
}else {
is100 = 0;
}
document.getElementById('prosentti').innerHTML = prosentti;
if (is100 == 1) {
document.getElementById('prosentti').setAttribute("style", "color:green");
} else {
document.getElementById('prosentti').setAttribute("style", "color:red");
}
puuttuvaEuro();
}
The problem code here is getKassasumma(summa); and DevideIntoCells();. I disable one of them, and the other one works, I enable both of them, DevideIntoCells stops somewhere before document.getElementById("spinwheel3").style.visibility = "hidden";, probably at the eval(response) because getKassasumma already finished the ajax request and killed this one. same the other way around.
AJAX answers: DevideIntoCells:
var KP_osuus = parseFloat('40');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box1.5').value = newvalue;
var KP_osuus = parseFloat('60');
laskunsumma = parseFloat(document.getElementById('laskun_summa').value);
onepercent = laskunsumma/100;
newvalue = onepercent*KP_osuus;
document.getElementById('box2.5').value = newvalue;
AJAX answer: getKassasumma
var kassasumma = '477.99€';
document.getElementById('kassasumma').value = kassasumma;
Please ask if you need clarification!
EDIT: Just to be clear, this is NOT an AJAX problem, rather javascript.
I think you are 'swimming in it', how we say. If you begin with AJAX, I'd recommend you use a framework like jQuery and it's $.get() or $.post() functions. It will accomplish all the needed AJAX logic for you.
Try to make xmlhttp local, i.e.
var xmlhttp;
Because you are overwriting you xmlhttp you refer to in the event listeners, so when the listeners get called, they both see the same response.
at the beginning of every of your functions. For compatibility, also use send(null) instead of send().

Categories