Solved

Can you use Javascript to check whether a form value already exists within a MYSQL table prior to submitting the form

Posted on 2014-01-07
15
1,655 Views
Last Modified: 2014-01-10
I have a PHP form which has dependent drop downs within it. Therefore I have the following javascript at the top of the page so it can refresh to form client side without submitting it.

------------------------------------------------
<script language="JavaScript">
function autoSubmit()      
{
    var formObject = document.forms[\'theForm\'];
    formObject.submit();
}

function process(){

document.theForm.action="close_pdp_process.php";
document.theForm.submit();
}

</script>
------------------------------

The autoSubmit() function refreshes the form based on the drop down selections without submitting it.

The process() function submits the form only when the user is happy and presses the ‘Save’ button which actions this function.

The process() function then passes the form values to a separate PHP page called “close_pdp_process.php” which uses $_POST superglobal variable to collect the data and perform the necessary actions.

The problem I have it that I would like to check whether the ‘userid’ and ‘reviewdate’ primary key values already exist within the MYSQL table prior to opening the “close_pdp_process.php” page, so the user has an alert and can correct the form first.  

I was thinking that a check within the process() function would be appropriate. Like

function process(){

/////CHECK WHETHER KEY (userid, reviewdate) EXISTS IN TABLE  HERE  - If it does show alert, If not continue //////
 
document.theForm.action="close_pdp_process.php";
document.theForm.submit();
}

I’m not sure how to do this as I would normally do the check using PHP. Can I mix PHP and Javascript in this way? Or is there a better solution?

Thanks
0
Comment
Question by:EICT
  • 6
  • 5
  • 4
15 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Since you are submitting the page everytime a dropdown is changed why not just check it then if the keys exist?
Else you would need to just Ajax to make a call to the server to check if the key exists.
Or using jQuery it would be even easier

The idea is that when the submit button is clicked you halt the form from being submitted, make a request to a php page on your server asking if the key exists. The page returns either 0 (doesn't exist) or 1 (does exist).  At this point you either then let the page finish submitting or send an alert to the user and end the submit.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 300 total points
Comment Utility
Gary's description is right on point.  This article shows the "hello world" exercise using jQuery and AJAX.  Please read it over and post back if you have any questions.  In your case the data base queries and relate processing would make the background script considerably more interesting than this one, that just sends back a couple of values to show the communications technique.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
 

Author Comment

by:EICT
Comment Utility
ok. What you say about making a request to a php page and then return either 0 or 1 seems to make sense.

I can write the PhP page to check and return a value but I not sure how to get Javascipt to check returned value is 0 or 1.

The following seems to answer it but I don't know much about ajax. I think I need to learn what $.ajax and $('#box2')  means/is doing

stackoverflow.com/questions/8692162/how-to-return-a-value-to-javascript-after-posting-via-ajax-jquery

I shall try modifying this accordingly and reply.
0
 

Author Comment

by:EICT
Comment Utility
Thanks Ray I shall look at this also.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
This is a really good book for learning jQuery.  Ignore the hokey title and just buy it.  You'll be glad you did, and you'll be amazed by the elegance and simplicity of jQuery. And as a side bonus, you will finally, really, understand how CSS works!
http://www.sitepoint.com/store/jquery-novice-to-ninja-new-kicks-and-tricks/

I have Version One and I've just ordered Version Two.
0
 
LVL 58

Assisted Solution

by:Gary
Gary earned 100 total points
Comment Utility
This is basic example of intercepting the submit button with jquery and posting an ajax request

$("#my-form-id").submit(function(e){
	e.preventDefault() // stop the form submitting
	$.ajax({type:'GET',context:this,url:'/checkuserid.php?userid='+$("#userid-input").val(),success:function(response) {
		if(response==1){
			this.submit()
		}
		else{
			alert("Please enter userid")
		}
	}})
})

Open in new window

0
 

Author Comment

by:EICT
Comment Utility
Ray,
I've read your JQuery Article. It was very helpful.

I have a couple of quick questions.

1. If I want to post more than one argument to the php page do I separate them with a comma i.e.  $.post("myphpcheckpage.php", {myArg1: indata, myArg2: indata2}, function(response){...}),

2. I was thinking about using the myphpcheckpage.php page repeatedly for different forms. The easiest way to do this would be to pass the MySQL check query string as a argument value. Is this a bad idea - for security reasons?

3. I understand CSS so referring to the page element is straight forward enough.  How would I refer to a php variable value such as $myvariable
0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 

Author Comment

by:EICT
Comment Utility
Relating to this . Why does the following not work?
$indate = '2014-01-07';

echo '
<script language="JavaScript" src="http://code.jquery.com/jquery-latest.min.js">

var indate = \''.$indate.'\';
alert(indate);
}
</script> ';

Open in new window


When I view the source is seems that the $indate is being assigned to the var indate but that the alert is not displaying it.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
When you set the src of a script tag it cannot include javascript e.g

This is wrong - it cannot include your own code
<script src="http://code.jquery.com/jquery-latest.min.js">
var indate = '.$indate.'
alert(indate);
}
</script>


This is correct
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
1. If you want to pass more than one value in the Ajax then just append it to the url e.g.

$.ajax({type:'GET',context:this,url:'/checkuserid.php?userid='+$("#userid-input").val()+"&anotherelement="+$("#anotherelement").val(),
success:function(response) {
            if(response==1){
...

2. Do not expose your sql on the client side - it may be a trivial sql query but it could come back to bite you in the bum.

3. Not sure I am following you but PHP variables do not exist in the browser.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
From these questions...
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28332389.html#a39765087

1. "commas"  Yes, something like this:
$.post("RAY_ajax_server.php", {myArg:indata,foo:'bar'}, function(response){

2. "pass the MySQL check query string as a argument value"  Nope.
What I would recommend instead is passing a handshake signal of some sort.  The backend script could have several queries predefined and the handshake signal could just be a number or a query name you made up to identify which query to run.  This will help avoid exposing details about your SQL.  You would always want to treat any data passed to the backend script as tainted external data and an attack vector.  The guidance is "Accept Only Known Good Values."

3. CSS ... a php variable value such as $myvariable
This question mixes the client side technologies of HTML, CSS and JavaScript with the server-side technology of PHP.  These are different machines.  PHP runs first on the server and is complete before any of the information is sent to the client, but that fact can be confusing when you watch jQuery in action.  Please see this article for some disambiguation of these technologies and some information on how they work in harmony.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
From this question:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28332389.html#a39765230

It looks like there is an extraneous curly brace in the code.  That may not be the only thing wrong, but it's enough to make the JavaScript parser fail.

I think I would code it more like this.  PHP HEREDOC notation is really easy  to use, when compared to a lot of escaped quotes!  Heed the warning on the man page, but don't be put off by it.

<?php // RAY_temp_eict.php
error_reporting(E_ALL);

// CREATE A PHP VARIABLE
$indate = '2014-01-07';

// CREATE A RESPONSE DOCUMENT USING HEREDOC NOTATION
$document = <<<EOD
<script>
var indate = '$indate';
alert(indate);
</script>
EOD;

// SEND THE RESPONSE TO THE BROWSER
echo $document;

Open in new window

0
 

Author Comment

by:EICT
Comment Utility
Hi,

Thanks I've got this working well but have a couple of final questions which relate to this subject before I close of the question.

For a separate problem I'm using code Ray produced, so pass values to a php page

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $("#signal").click(function(){
        indata = $("#xinput").val();
        $.post("add_agencyreferral_prepop.php", {myArg:indata}, function(response){
            $("#output p#target").html(response);
           
            
        });
    });
});
</script>

Open in new window


then the php page is checking using the value and returning a reply.

$id = $_POST['myArg'];

		$queryagency = "SELECT id, name, address1, address2, city, county, contactNo FROM agency WHERE id = '$id'";
		$resultagency = @mysql_query ($queryagency); // Run the query.
		$rowagency = mysql_fetch_array($resultagency, MYSQL_NUM);
		
		

// SEND THE CONTENTS OF THE OUTPUT BUFFER
die($rowagency[1]);

Open in new window


How do I return multiple values i.e. $rowagency[1], $rowagency[2] etc and then reference them in the javascript?  I've tried sending them all back as Array and then calling the array content i.e. response[1] response[2] but it does not work.

Secondly instead of using  $("#output p#target").html(response); to assign the response to the output elements p tag, How do I assign it to display in the form field <input id="outname" type="text" name="name" value=""> ?

I tried $("outname").html(response) but no joy.


Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
This seems to have turned from a question into an application development project, so I'll sign off now.  I recommend that you get two SitePoint books.  Ignore the bozo titles, they are good books with strong examples and excellent advice.
http://www.sitepoint.com/store/php-mysql-novice-to-ninja/
http://www.sitepoint.com/store/jquery-novice-to-ninja-new-kicks-and-tricks/

Best of luck with your project, ~Ray
0
 

Author Closing Comment

by:EICT
Comment Utility
Thanks for your help.  I've ordered the jquery book and will try to find how to pass multiple values elsewhere. As the original question is resolved I've closed it off.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now