Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
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
Medium Priority
?
1,888 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 4
15 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39762432
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 111

Accepted Solution

by:
Ray Paseur earned 1200 total points
ID: 39762451
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
ID: 39762479
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
Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

 

Author Comment

by:EICT
ID: 39762486
Thanks Ray I shall look at this also.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 39762583
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 400 total points
ID: 39762670
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
ID: 39765087
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
 

Author Comment

by:EICT
ID: 39765230
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
ID: 39765270
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
ID: 39765287
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 111

Expert Comment

by:Ray Paseur
ID: 39765589
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 111

Expert Comment

by:Ray Paseur
ID: 39765614
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
ID: 39770806
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 111

Expert Comment

by:Ray Paseur
ID: 39770863
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
ID: 39771405
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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses

636 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