Link to home
Start Free TrialLog in
Avatar of EICT
EICTFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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

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
Avatar of Gary
Gary
Flag of Ireland image

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.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EICT

ASKER

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.
Avatar of EICT

ASKER

Thanks Ray I shall look at this also.
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EICT

ASKER

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
Avatar of EICT

ASKER

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.
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>
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.
From these questions...
https://www.experts-exchange.com/questions/28332389/Can-you-use-Javascript-to-check-whether-a-form-value-already-exists-within-a-MYSQL-table-prior-to-submitting-the-form.html?anchorAnswerId=39765087#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.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html
From this question:
https://www.experts-exchange.com/questions/28332389/Can-you-use-Javascript-to-check-whether-a-form-value-already-exists-within-a-MYSQL-table-prior-to-submitting-the-form.html?anchorAnswerId=39765230#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

Avatar of EICT

ASKER

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
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
Avatar of EICT

ASKER

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.