Solved

Alert message not working - PHP and Javascript

Posted on 2009-04-13
10
1,314 Views
Last Modified: 2013-12-13
Hey,

I have been on this question for a while now and I just can't seem to find anything that works the way I want it to. First I will explain what my pages do.

The exerciseTest page will list an exercise found in the exercise table. From that page I have a form that will allow the user to add the displayed exercise to the exercise of the month table. They will have the option of picking which month they would like to add it to. Only one exercise per month can be added.

If an exercise is already occupied by the month they have chosen, an alert message will come up asking them if they would like to replace the exercise. I would like it so if the user clicks OK then it will send it to the AddUpdateMonthlyExercise page and it will update. If the user clicks cancel then it will do nothing.

Basically, the alert message must go through a function that checks if the exercise month is in the exercise_of_month table after the user clicks on the add button. If it is not then the exercise will simply be added to the exercise_of_month.

I must tell you all that I am fairly new at PHP and javascript so I am looking for something that is hopefully easy to understand and code. I have received some comments that AJAX would be best to use in this situation. If the alert button cannot be coded without AJAX then I would have to resort to AJAX.

Here I have supplied the exerciseTest page and the AddUpdateMonthlyExercise page.
<!-- Test page to view exercises and add an exercise to exercise of the month -->

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    </head>

    <body>

        <?php

            $exerciseID = 3;

 

            include('connection.php');

                mysql_connect($ip,$username,$password);

                @mysql_select_db($database) or die('Could not connect to database: ' . mysql_error());

            

            // First, fetch all the unique Exercise_Month's

            $checkMonth = mysql_query("SELECT Exercise_Month FROM Exercise_of_Month GROUP BY Exercise_Month");

            $PhpArray = array();

            while($row = mysql_fetch_array($checkMonth, MYSQL_NUM)) {

                $PhpArray[] = $row[0];

            }

            // Echo the javascript stuff to the client.

            ?>

            <script language="javascript">

                var JavaArray = ['<?php echo implode("', '", $PhpArray) ?>'];

                

                function in_array(stringToSearch, arrayToSearch) {  

                    for (s = 0; s < arrayToSearch.length; s++) {

                        thisEntry = arrayToSearch[s].toString();

                        if (thisEntry == stringToSearch) {

                           return true;

                        }

                    }

                    return false;

                }

                function CheckExistance(month_name) {

                    if (in_array(month_name, JavaArray)) {

                        var answer = confirm("An exercise already exists for this month. Would you like to replace the exercise?");

                        if (answer) {

                            document.addMonthlyExercise.addUpdate.value="Update";

                            document.addMonthlyExercise.addExercise.value="Update";

                        }

                        else {

                            document.addMonthlyExercise.addUpdate.value="Add";

                            document.addMonthlyExercise.addExercise.value='Add';

                        }

                    }

                }

            </script>

            <?php

 

            $result = mysql_query("SELECT * FROM Exercise WHERE Exercise_Id = '$exerciseID'");

            while($row = mysql_fetch_array($result)) {

                $exerciseID = $row["Exercise_Id"];

                $exerciseName = $row["Exercise_Name"];

                $desc = $row["Description"];

                $disabled = $row["Disabled"];

                $dateCreated = $row["Date_Created"];

                $version = $row["Version"];

                $createdBy = $row["Created_By"];

            }

        ?>

        <form name="displayExercise" method="POST">

            Exercise ID: <input type="text" name="ExerciseID"  value="<?php echo $exerciseID;?>" /><br/>

            Exercise Name: <input type="text" name="ExerciseName"  value="<?php echo $exerciseName;?>" /><br/>

            Description: <input type="text" name="Description" value="<?php echo $desc; ?>"/><br/>

            Disabled: <input type="text" name="Disabled"  value="<?php echo $disabled;?>" /><br/>

            Date Created: <input type="text" name="Date Created" value="<?php echo $dateCreated; ?>"/><br/>

            Version: <input type="text" name="Version"  value="<?php echo $version;?>" /><br/>

            Created By: <input type="text" name="CreatedBy" value="<?php echo $createdBy; ?>"/><br/>

        </form>

        <form name="addMonthlyExercise" action="AddUpdateMonthlyExercise.php" method="POST">

            <input type="hidden" name="addUpdate" value="" />

            Add to Exercise of the Month: <select id="Month" name="Month">

                                            <option value="01">January</option>

                                            <option value="02">February</option>

                                            <option value="03">March</option>

                                            <option value="04">April</option>

                                            <option value="05">May</option>

                                            <option value="06">June</option>

                                            <option value="07">July</option>

                                            <option value="08">August</option>

                                            <option value="09">September</option>

                                            <option value="10">October</option>

                                            <option value="11">November</option>

                                            <option value="12">December</option>

                                        </select>

            <input type="hidden" name="exerciseID" value="<?php echo $exerciseID;?>" />

            <input type="submit" name="addExercise" value="Add" onclick="CheckExistance(document.Month.value);" />

        </form>

    </body>

</html>

 

 

 

 

<?php

/*

        AddUpdateMonthlyExercise.php

    Adds or updates an exercise on the monthly exercise table

*/

        include('connection.php');

        mysql_connect($ip,$username,$password);

        @mysql_select_db($database) or die( "Unable to select database");

        

        $exerciseID = mysql_real_escape_string(stripslashes($_POST['exerciseID']));

        $exerciseMonth = mysql_real_escape_string(stripslashes($_POST['Month']));

    $addUpdate = mysql_real_escape_string(stripslashes($_POST['addUpdate']));

 

    echo "Month: ".$exerciseMonth;

    echo "<br>ID: ".$exerciseID;

    echo "<br>SQL Query: ".$addUpdate;

 

//    Check if value passed in is add or update

    if ($addUpdate == "Update") {

        $sql = mysql_query("UPDATE Exercise_of_Month

            SET Exercise_Id = '$exerciseID'

            WHERE Exercise_Month = '$exerciseMonth'");

 

        if (mysql_query($sql)) {

            echo "<br>Exercise of the month updated";

        }

        else

            echo "<br>Update Failed";

 

        mysql_close();

    }

    else {

        $sql = "INSERT INTO Exercise_of_Month

            SET Exercise_Id = '$exerciseID', Exercise_Month = '$exerciseMonth'";

 

        if (mysql_query($sql)) {

            echo "<br>New exercise of the month added";

        }

        else

            echo "<br>Insert Failed";

 

        mysql_close();

    }

 

//    header('Location: ViewMonthlyExercises.php' );

 

?>

Open in new window

0
Comment
Question by:tqrecords
  • 5
  • 3
  • 2
10 Comments
 
LVL 9

Expert Comment

by:Mahdii7
ID: 24131055
Hello,

What is the problem you are having with this? The code you posted seems to do what you ask already. You have a JS array generated from mysql that you use to check if an exercise exists for the month. If the month is occupied, you change the form's $_POST data and use a conditional to decide whether to update or insert into the DB. Is this code not working? What are you asking for?

Also, if you code like this you are asking for trouble. The DOM of HTML is easily modifiable, leaving JavaScript in the dust for validation. I could easily open up this page, remove the onClick event from your submit button, change the value of addUpdate/addExercise to "Add" and add multiple exercises per month. You'll need to add some PHP validation to this as well (ie, check again for existing entries in the month, if they exist throw an error).
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24132616
This statement...

$checkMonth = mysql_query("SELECT Exercise_Month FROM Exercise_of_Month GROUP BY Exercise_Month");

...will assign a value to $checkMonth.  The value will be either a resource ID for use with other MySQL functions or FALSE if the query did not execute correctly.  Because the script does not test the return value, you have no way of knowing whether the query worked, except that the script may malfunction one day, perhaps by producing no output.  It is wise to test the results of mysql_query() and if it is found to be FALSE, it is wise to inspect the contents of mysql_errno() and mysql_error() so you can make a programatically correct decision in the code.

A good book that will help with the PHP/MySQL side of the learning process is available here:

http://www.sitepoint.com/books/phpmysql1/

Best regards, ~Ray
0
 

Author Comment

by:tqrecords
ID: 24133554
Mahdii7:

When I click on the addExercise button it does not display the alert message when the exercise exists. The code makes sense but does not seem to work.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24133591
Are you using FIrefox?  If not, install it and install the exceptionally useful plug-in called Firebug.  Then you can track all kinds of things in JavaScript and CSS -- very helpful when debugging.

Also, if this were my application I would take to heart what Mahdii7 said about data validation in the server-side of the action script processing.  You do not really need a separate JS alert box - you can just issue an error message from the PHP script that processes the form.  Your clients will understand it just as well, I am sure.
0
 

Author Comment

by:tqrecords
ID: 24133640
Hey,

Thanks for the quick reply. I am using firefox yes. Security is not a problem for now because this project is just a sample of what is to come. I can always change the page to a more secure method later.

I am only using javascript because it was brought to my attention from another member on this site.

Is there a way to code the sql query and if statement inside of the onclick event of the addExercise button?
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24133678
"Is there a way to code the sql query and if statement inside of the onclick event of the addExercise button?" - I think the answer to that is, "Yes" and it would be an AJAX application.  I'm still not of the philosophy that this requires AJAX, but it usually produces very attractive effects on the sites that use it.

I can't recall where I got this snippet, but it is signed "Rasmus" and that may be Lerdorf of PHP fame.  It shows the essential moving parts of what has come to be known as AJAX.  Hope it helps suggest a good solution for you.
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have

been using similar things long before it became "AJAX".  And it really

isn't as complicated as a lot of people make it out to be.  Here is a

simple example from one of my apps.  
 

First the Javascript:
 

function createRequestObject() {

    var ro;

    var browser = navigator.appName;

    if(browser == "Microsoft Internet Explorer"){

        ro = new ActiveXObject("Microsoft.XMLHTTP");

    }else{

        ro = new XMLHttpRequest();

    }

    return ro;

}
 

var http = createRequestObject();
 

function sndReq(action) {

    http.open('get', 'rpc.php?action='+action);

    http.onreadystatechange = handleResponse;

    http.send(null);

}
 

function handleResponse() {

    if(http.readyState == 4){

        var response = http.responseText;

        var update = new Array();
 

        if(response.indexOf('|' != -1)) {

            update = response.split('|');

            document.getElementById(update[0]).innerHTML = update[1];

        }

    }

}
 

This creates a request object along with a send request and handle

response function.  So to actually use it, you could include this js in

your page.  Then to make one of these backend requests you would tie it

to something.  Like an onclick event or a straight href like this:
 

  <a href="javascript:sndReq('foo')">[foo]</a>
 

That means that when someone clicks on that link what actually happens

is that a backend request to rpc.php?action=foo will be sent.
 

In rpc.php you might have something like this:
 

  switch($_REQUEST['action']) {

    case 'foo':

      / do something /

      echo "foo|foo done";

      break;

    ...

  }
 

Now, look at handleResponse.  It parses the "foo|foo done" string and

splits it on the '|' and uses whatever is before the '|' as the dom

element id in your page and the part after as the new innerHTML of that

element.  That means if you have a div tag like this in your page:
 

  <div id="foo">

  </div>
 

Once you click on that link, that will dynamically be changed to:
 

  <div id="foo">

  foo done

  </div>
 

That's all there is to it.  Everything else is just building on top of

this.  Replacing my simple response "id|text" syntax with a richer XML

format and makine the request much more complicated as well.  Before you

blindly install large "AJAX" libraries, have a go at rolling your own

functionality so you know exactly how it works and you only make it as

complicated as you need.  Often you don't need much more than what I

have shown here.
 

Expanding this approach a bit to send multiple parameters in the

request, for example, would be really simple.  Something like:
 

  function sndReqArg(action,arg) {

    http.open('get', 'rpc.php?action='+action+'&arg='+arg);

    http.onreadystatechange = handleResponse;

    http.send(null);

  }
 

And your handleResponse can easily be expanded to do much more

interesting things than just replacing the contents of a div.
 

-Rasmus

Open in new window

0
 

Author Comment

by:tqrecords
ID: 24133713
Did I mention I was NEW at this..

"You do not really need a separate JS alert box - you can just issue an error message from the PHP script that processes the form."

Is there any way to do this without AJAX??
0
 
LVL 9

Expert Comment

by:Mahdii7
ID: 24133732
"Is there a way to code the sql query and if statement inside of the onclick event of the addExercise button?"

AJAX (Asynchronous JavaScript and XML)  is JavaScript, the onClick event triggers javascript. The the answer to this is really no. JavaScript will be involved in some way, if you want to use onClick instead of a link.

Personally I could do this faster with AJAX than with PHP JS outputs to the documents head. For you, that may not be the case, it all depends.

If you want a more realistic, refined method to execute AJAX on your site, use jQuery, You can make an AJAX call in < 3 lines.

www.jquery.com
http://docs.jquery.com/Ajax
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 24133912
"Did I mention I was NEW at this..." - well, it's not a simple topic.  Integrating PHP and JS via your own code or one of the packages like jQuery is really advanced stuff.  So don't be uncomfortable if you find it a little daunting -- just go after it the same way you eat an elephant, one bite at a time.

You do not absolutely have to use AJAX to get an alert box to pop up.  You might want to start with this:
http://www.javascriptkit.com/javatutors/alert2.shtml

If time is of the essence, you should consider hiring a developer.  If this is a learning exercise, just be patient with yourself and step through the examples in this book (it's not about JS but it will give you a good foundation in procedural PHP and MySQL).
http://www.sitepoint.com/books/phpmysql1/

In the code snippet are some examples of how PHP and MySQL relate to one another.  Hopefully if you follow those guidelines you won't find any uncaught error conditions.

And finally, add error_reporting(E_ALL) to the top of every script -- pay attention to warnings and notices.  The are the programmers friend!

Best of luck with it, ~Ray
<?php // RAY_mysql_example.php

error_reporting(E_ALL);
 
 

// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE

$db_host = "localhost"; // PROBABLY THIS IS OK

$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY

$db_user = "??";

$db_word = "??";
 

// CONNECT TO THE DATA BASE SERVER

if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))

{

   $errmsg = mysql_errno() . ' ' . mysql_error();

   echo "<br/>NO DB CONNECTION: ";

   echo "<br/> $errmsg <br/>";

}
 

// SELECT THE DATA BASE

if (!$db_sel = mysql_select_db($db_name, $db_connection))

{

   $errmsg = mysql_errno() . ' ' . mysql_error();

   echo "<br/>NO DB SELECTION: ";

   echo "<br/> $errmsg <br/>";

   die('NO DATA BASE');

}
 
 
 

// MAKING A SELECT QUERY AND TESTING THE RESULTS

$sql = "SELECT id FROM my_table WHERE username='$username'";

$res = mysql_query($sql);
 

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS

if (!$res)

{

   $errmsg = mysql_errno() . ' ' . mysql_error();

   echo "<br/>QUERY FAIL: ";

   echo "<br/>$sql <br/>";

   die($errmsg);

}

// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS
 
 
 

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT

$num = mysql_num_rows($res);

if (!$num)

{

   echo "<br/>QUERY FOUND NO DATA: ";

   echo "<br/>$sql <br/>";

}

else

{

   echo "<br/>QUERY FOUND $num ROWS OF DATA ";

   echo "<br/>$sql <br/>";

}
 
 
 

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND

echo "<pre>\n"; // MAKE IT EASY TO READ

while ($row = mysql_fetch_assoc($res))

{

   var_dump($row);

}
 
 
 

// MAKING AN INSERT QUERY AND TESTING THE RESULTS

$sql = "INSERT INTO my_table (username) VALUES (\"$username\")";

$res = mysql_query($sql);
 

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS

if (!$res)

{

   $errmsg = mysql_errno() . ' ' . mysql_error();

   echo "<br/>QUERY FAIL: ";

   echo "<br/>$sql <br/>";

   die($errmsg);

}

// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS
 

// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED

$id  = mysql_insert_id($res);

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24157512
What's wrong with our answers? Why did you mark this down to a "B" without any explanation?  Please tell us what you were expecting that we did not deliver?  Thanks, ~Ray
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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 …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
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 and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

743 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

17 Experts available now in Live!

Get 1:1 Help Now