• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1922
  • Last Modified:

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
0
EICT
Asked:
EICT
  • 6
  • 5
  • 4
2 Solutions
 
GaryCommented:
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
 
Ray PaseurCommented:
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
 
EICTAuthor Commented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
EICTAuthor Commented:
Thanks Ray I shall look at this also.
0
 
Ray PaseurCommented:
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
 
GaryCommented:
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
 
EICTAuthor Commented:
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
 
EICTAuthor Commented:
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
 
GaryCommented:
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
 
GaryCommented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
EICTAuthor Commented:
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
 
Ray PaseurCommented:
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
 
EICTAuthor Commented:
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

  • 6
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now