Link to home
Start Free TrialLog in
Avatar of Moses Dwana
Moses Dwana

asked on

HOW DISPLAY PHP ERRORS TO USER USING JQUERY AND CSS

i want to change the text field color when validation fail. i understand this can be achieve using query but i want the validation errors to be post by php because i want to validate a lot of things going to my database. for example, i want to check whether email address already exits in the database and trow an error, while at the same time using the power of jquery and css to style the text field when the error occur.

thanks in advance for your help.
Avatar of BR
BR
Flag of Türkiye image

you can simply do that with html and css,
I don't think you need jquery to do that.

for example your error message comes with the $error variable

you can simply  use span or header tag with a class like below

<h2 class="give a proper class here"> $error occurs </h2>
Avatar of Scott Fell
This is a few questions rolled into one.  What you will do is post your data using ajax. Then your php page that is called via ajax will return something valid or errors.  Jquery reads the response and updates the page.  I will create a short example for you.
Sorry for the delay.

Here is a sample form
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Form Validation</title>
</head>
<body>
<div id="result"></div>
<form>
    <label for="email">Enter your email</label>
    <input id="email" name="email">
    <button id="submitform">Submit</button>
</form>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
    $(function(){
        $('#submitform').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
            var emailaddress = $('#email').val(); // get value entered from email field

            $.ajax({
                method: "POST",
                url: "process.php",
                data: { email: emailaddress}
            })
                .done(function( data ) {  // capture the return from process.php
                    var obj = $.parseJSON( data );
                    var isValidForm = obj.valid;
                    var msgEmail = obj.msg_email;


                    if(isValidForm == 1){  // place results on the page
                        $('#result').html('<div class="valid">Success!</div>');
                    } else {
                        $('#result').html('<div class="valid">Error!<br>'+msgEmail+'</div>');
                    }
                });
        });
    });

</script>
</body>
</html>

Open in new window


Then your process page
<?php

if(isset($_POST)){
    $email = $_POST['email']; // capture post
    $valid = 1; // flag to alert form if valid or not.  Change to 0 if any error.
    $msg_email = ''; // set value of each possible return value to blank.

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  // test for valid email
        $msg_email = "Please enter a valid email";
        $valid = 0;  // if bad, set valid flag to 0
    }

    $result = array('valid' => $valid, 'msg_email' => $msg_email);  // create an array to be converted to json

    echo json_encode($result);  // echo out json encoded response 
}

Open in new window

Avatar of Moses Dwana
Moses Dwana

ASKER

thanks in advance!!!! let me see how it works
thanks for the code but i actually want to also check my database to see whether the email address already exist. if yes, throw an error.
sorry if i am not making a lot of since, i am new to programming.

some thing like this:
include('section.php'); 
 $username=$_POST['username'];
$result = $con->query("SELECT COUNT(*) FROM `users` where username='$username'");
$row = $result->fetch_row();
$yes= $row[0];
	  
	  if($yes <= 0){ $quer=mysqli_query($con,"insert into users(username) values ('$username')");
      }else{$msg = "user name already exist";}

Open in new window

is it possible to use this code on the process page?
You can take your real life needs to my example.

You have
else{$msg = "user name already exist";}

Open in new window

I have
 $result = array('valid' => $valid, 'msg_email' => $msg_email);  // create an array to be converted to json

    echo json_encode($result);  // echo out json encoded response 

Open in new window


Use
 $result = array('valid' => $valid, 'msg_email' => $msg);  // create an array to be converted to json

    echo json_encode($result);  // echo out json encoded response 

Open in new window


You don't have to use the valid flag. I throw that in for my own needs.  They key is to output a json response that you can read from jquery that will add the the message to your page.  Using ajax like this means no page refresh. You could of course just post to the same page and add logic as Braveheartli suggest something like

<div id=result"<?php
if($msg){
 echo $msg;
}
?></div>

Open in new window


The ajax method better separates your logic from the view.
ok thanks very mush!!!!! i am trying it right now. will be back
sorry for replying at time, i went on a weekend. however, the code you give did not worked. the error message is not displaying and the text box color is not changing to red when i click the submit button. i think there is an error some where.
ASKER CERTIFIED SOLUTION
Avatar of Scott Fell
Scott Fell
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
thanks. it worked find, but what i want is to also change the textbox color to red when validation fail.
thanks in advance!!!!!!
> want is to also change the textbox color
Just update  your css.

https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
https://www.w3schools.com/cssref/pr_background-color.asp

<style>
		.error{
			color:red;
                      /* ***** background-color: xxxx ********* */

                    
		}
	</style>

Open in new window

i mean the textbox field should change   to red when validation fail. i am not talking about the error div background color.
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
this one  same great. i am trying play around it to see how it works because currently there is no css file for the textbox and i think the html file has to be restructure to achieve this. if you could help me to reorganize the whole script step by step, i will highly appreciate it.

sorry if i am sounding somehow. i am new to programming.

thanks for the help!!!!. i will get back to you soon.
Moses, I think for the most part we have the hard part working.  You can do an ajax request and get data back.  Let's close out this question, then ask a new question on how to style your form.  It will be easier to work with by focusing on one thing at a time.

In your new question, you can render your html (view source, copy and paste) your code in the question or just provide a link to our sample page.
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