0

I have an HTML file which contains registration form(inputs,labels, buttons and etc.). I have a special div:

<div id ="errorArea"></div>

- which is reserved empty space I want to use to display error messages (login is already used, passwords do not match, email couldn't be empty and etc.). There is submit button which triggers php. In current state everything works fine, as I'm using this to display messages:

if (!empty($myrow['id'])) {
    exit ("this login is already used");
 }

After submit button is pressed, if there is an error new white blank shows us pre-defined text. What I'm trying to achieve is: show error messages inside of errorArea div, without leaving current page. Can you help as I cannot find out myself the best way to do that. Keep in mind that I have very little knowledge in php language.

Update Maybe there is a way to refresh page with new parameters or is it legit to load another one which is exact same page with exception of adding new text?
Update2 Can anyone explain me if it possible, to trigger a javascript before posting data a.k.a triggering php script?

Amal.A
  • 29
  • 1
  • 1
  • 10
  • You have to submit your form using ajax. Then display the php response inside your div using javascript. – Romain Braun Mar 21 '14 at 00:47
  • it looks you may want to use javascript in the DOM to post the values via ajax and have php return the message to javascript to display to the DOM. – 13ruce1337 Mar 21 '14 at 00:47
  • @RomainBraun can you give some more details so i can start research on that? – Amal.A Mar 21 '14 at 00:48
  • Both comments are valid, but mean that you are now coding for both client & server (which is not a bad thing, but it depends on your application). It is perfectly possible, and normal, to do it all server side in PHP only. – Mawg says reinstate Monica Mar 21 '14 at 00:48
  • @13ruce1337 can you please recommend some information about that? – Amal.A Mar 21 '14 at 00:49
  • 1
    @Mawg to that point, when I started, I had a `index.php` page and a `logincheck.php` page to verify and `echo` on failure then redirect to login. – 13ruce1337 Mar 21 '14 at 00:50
  • @Amal.A it's really hard for me to give you a reference if you aren't familiar with [client side/server side functions](http://programmers.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming). but would you rather it be done in php or javascript? – 13ruce1337 Mar 21 '14 at 00:53
  • @13ruce1337 First thing i came out with was writing javascript function like `displayError()` which handles all the problems and switches errors messages based on argument it takes. But errors are based on checking database, so i used php for inserting data into it. My brick wall was echoing scripts from php, but it seems not like a legit way – Amal.A Mar 21 '14 at 01:00
  • @Amal.A how are you running PHP? If you are using a linux box then check where the [`error.log` is like this.](http://www.cyberciti.biz/faq/error_log-defines-file-where-script-errors-logged/) – 13ruce1337 Mar 21 '14 at 01:03
  • @13ruce1337 i'm using xampp which has Appache server with preinstalled php interpritator. – Amal.A Mar 21 '14 at 01:08
  • @Amal.A then it should still be in the logs folder. [here is a reference](http://stackoverflow.com/questions/3719549/where-does-phps-error-log-reside-in-xampp) – 13ruce1337 Mar 21 '14 at 01:11
  • @13ruce1337 i found them, but i don't clearly understand how they can help? I could get them with console on my browser =) – Amal.A Mar 21 '14 at 01:15
  • 1
    @Amal.A what i recommend is that you re-evaluate your logic for this task and chose between learning little more Javascript to do this dynamically, or using redirects doing this fully in PHP. – 13ruce1337 Mar 21 '14 at 01:17
  • @13ruce1337 i can work with database using javascript+Ajax? – Amal.A Mar 21 '14 at 01:18
  • 1
    @Amal.A I do it all day. And it feels good :) – 13ruce1337 Mar 21 '14 at 01:19
  • @13ruce1337 hmm, looks valid for me, i'm not trying to be annoying, but does this mean i can escape using php at all? – Amal.A Mar 21 '14 at 01:22
  • @Amal.A there are a lot of things you can use my friend, it looks like you have a lot of googling ahead of you. – 13ruce1337 Mar 21 '14 at 01:25
  • @13ruce1337 well thank you for your advises and time, sir. – Amal.A Mar 21 '14 at 01:30
  • Some good feedback from @13ruce1337 there. Yes, you can escape using PHP, but as your own comment below remarks, how are you going to the server. So, you need something server-side. PHP (& MySQl) is traditional, but if you are going to code both client & server, you can use NodeJS on the server & code JS on both sides. You might also look at AngluarJS for client side (a Google framework, which I find helpful - and it let's you do everything on one page Lol) – Mawg says reinstate Monica Mar 21 '14 at 01:34
  • @Mawg i believe it's possible to do everything using assembler. =) But there is an ergonomic problem. I technically understand that i can escape coding in php with help of different frameworks and libraries, but i try to escape inventing bicycle. That's one of the reasons i jumped into php. – Amal.A Mar 21 '14 at 01:40
  • Lol - I had 8 years of professional assembler coding. Ok, two major ways to go, server-side. Traditional PHP, or the newer NodeJs. Do some googling & see which suits you. – Mawg says reinstate Monica Mar 21 '14 at 01:50

4 Answers4

0

"without leaving current page" - very bad idea.

Firstly, whet is your form action? It should normally lead to a validation script, which user does not see, and that in turn can lead to successful login page, or, as you seem to want, to rebuild the first log in" page, with an error message.

This is all very standard. Just google for something like PHP login form validation tutorial (or example).

Don't worry, PHP is eacy to learn (but get a good IDE, like NetBeans).

Good luck!


[Update] I just googlged for php login example and there are some good hits. For instance, the first one http://www.9lessons.info/2009/09/php-login-page-example.html but why look at a few from the first page of hits?

IMPORTANT: a lot of people here are telling you that MUST use client-side code. That is 100% NOT the case.

Yes, client-siders, I can, and do, code client side (I started with plain JS, moved on to JQuery & am now coding AndularJs). I know why client-side, Ajax or otherwise, is A Good Thing, but it sounds like OP is just beginning, so why not let him master server-side first? Then, when he has mastered that , he can look at client-side (I am just afraid that someone here will try to talk him into using NodeJs on the server side. Again, not totally wrong, but for a beginner, it's best to start with PHP)

This can be done entirely on the server side. Parts of login MUST be done on the server side (where are you going to validate the password?).

OP, some form input can be validated at client side (is that a valid date, zip code, etc Is a mandatory field blank?)

You can (I can even say "should") do that client side to avoid a round trip to the server.

But, you can also just chuck all user input at the server and let it sort it out. I strongly recommend this - for a leaner.

I advise you, as a leaner, to:

  • become reasonably proficient in server side before getting into client side (but do lean both in the medium term)
  • get a good IDE, such as NetBeans, and learn how to use the debugger
  • look at other people's code. Google for tutorial or example for whatever you seek to do. It wouldn't hurt to buy a book to learn from.

Client-siders - a plea - let's not start a flame war. I know why you are advocating what you are advocating, but it is not 100% necessary - in this case - it can all be done server side and I am just trying to help the OP learn, rather than decide that it is all too complicated & give up & walk away.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • I'm sorry, why is it a bad idea not leaving the page ? – Romain Braun Mar 21 '14 at 00:49
  • 2
    This should be a comment not an answer – isJustMe Mar 21 '14 at 00:49
  • i'm sorry but how ide will help me when i'm in front of a brick wall that caused by my lack of knowledge? I'm using sublimeText, which is fine for me. Secondary it's not a login page it's registration form. Validation is already done, i need to find a way to rebuild form page with text added in specialized div. – Amal.A Mar 21 '14 at 00:52
  • bad idea not to leave the page just because of modularity. Sure, you can do everything, the entire application in one single page, in one single PHP file, but it gets messy. Amal, the IDE won't help this exact problem (actually it might, if you learn to use the debugger, set breakpoints, examine variables, etc). But you will with brickier walls very soon without a good IDE, you can't just use a text editor. Just advice. – Mawg says reinstate Monica Mar 21 '14 at 01:02
  • @Mawg thank you but modern browsers have a debugger, which i use with success. And by leaving the page i don't mean refreshing it. If there is an easy way to refresh the page with adding new params then it's legit to me. – Amal.A Mar 21 '14 at 01:06
  • Yes, you _can_ debug in the browser, but a good IDE offers you code completion, refactoring & a bunch of other god stuff. By all means, continue to debug in the browser console, but do get a good IDE. Again "without leaving the page" ... the form submission has an action, which is a new page to be loaded. Yes, you *can* just use the same page, but your code will get messy. Keep it modular, as all s/w should be. One file to display a form, one to validate, one for success, one for error (can also be back to the first, with some variables to mark the problems). Look at other people's examples. – Mawg says reinstate Monica Mar 21 '14 at 01:26
  • Why you think that sublime is not a "good IDE" looks like holy war but really, with all plugins and extensions it literally has more than any other ide. – Amal.A Mar 21 '14 at 01:32
  • Nothing at all wrong with Sublime, but why not using something free? Absolutely zero "holy war", I said " a good IDE" (which I believe to be important - IDE, not editor" **like** NetBeans". It doesn't have to be NetBeans. I used Eclipse for years, I still somethings use CodeLobster. There are others. – Mawg says reinstate Monica Mar 21 '14 at 01:37
  • @Mawg i believe it's just matter of taste =) – Amal.A Mar 21 '14 at 01:42
0

What you want is client side validation which is usually achieved using JavaScript. I would recommend using the jQuery library as it abstracts a lot of the ugliness of ensuring browser compatibility. The below pseudo-code is starting point if you want to validate when user hits submit.

$('#myForm').submit(function(e) {
    // do error checking here

    If (error) {
         // spend error message to div
         return false; // prevents standard form submission event
    }
 });

Another option is to validate each input field as the user finishes entering the field. Below pseudo-code outlines:

$(document).on('change', '.my-form-fields', function () {
    // check if valid and post message if needed
});
Brian Bolli
  • 1,873
  • 1
  • 12
  • 14
  • "What you want is client side validation" - his example is that a login ID is already used. how can the client side know that? "which can only be achieved using JavaScript" - Only? Try usually. See http://en.wikipedia.org/wiki/Client-side_scripting – Mawg says reinstate Monica Mar 21 '14 at 01:28
  • 1
    I stand corrected... although I would contend vbscript is all but dead and both actionscript and dart are supersets of JavaScript. Soooo, I wouldn't label it an unforgivable offense! – Brian Bolli Mar 21 '14 at 01:41
  • +1 forgive me. But I still say that he wants server-side validation for "id already in use". Just glad we are trying to help the guy, without flames. – Mawg says reinstate Monica Mar 21 '14 at 01:51
0

Maybe my code will help you)

Html with jQuery:

(function($){

"use strict";

$('document').ready(function(){
    $( ".submit-button" ).on('click', function(){

    var ajaxData = {
        action: 'getsettings',
        string: $('.name').val()
    };

    $.ajax({
        type: 'POST',
        url: 'resp.php',
        data: ajaxData }).done(function(msg){
            console.log(msg);
        });
    });
});

})(jQuery);


<input type="text" class="name">
<button class="submit-button">Button</button>   

And file resp.php with php script:

if ( 'POST' === $_SERVER['REQUEST_METHOD'] && 
     isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && 
     'XMLHttpRequest' === $_SERVER['HTTP_X_REQUESTED_WITH'] ) {

    if (    'getsettings' === $_POST['action'] &&
        isset($_POST['action']) && 
        !empty( $_POST['action'] ) ) {

     echo $_POST['string'];
     /*.... Your code ....*/

    }

}

It's work fine!

Brotheryura
  • 1,158
  • 13
  • 21
-3

What you need is Javascript since PHP is server side and you cannot change the text with only PHP and without leaving / refreshing / redirecting, here is an example on how to validate an email address and add text to the div

It is taken from http://www.w3schools.com/js/js_form_validation.asp and modified to your case

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  document.getElementById('errorArea').innerHTML = "Invalid Email";
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
<div id ="errorArea"></div>
</form>
</body>

</html>
Jack
  • 436
  • 5
  • 13
  • +1 Aha, you are not such a newbie as I thought. Yup, for some of it, you MUST go to the server, for all of it you _can_ go to the server. JS is not *needed*, just helpful. Can you tell us if you want to learn JS & PHP at the same time, or PHP first, then JS? – Mawg says reinstate Monica Mar 21 '14 at 01:30
  • @Mawg i'm not a newbie i just want you to treat me like the newbie one, so i can get constructed advises. I already have AJAX function which loads a lot of pages for my project, a lot of jacascript and jquery to handle different conditions. My problem is server side programming. – Amal.A Mar 21 '14 at 01:36
  • You want constructive advice? don't say that, they will close your question (alas). Yup, Ajax is fine. If not a newbie then you can develop both C & S sides. PHP is traditional for server, but you can also use NodeJS & ave JS only on both sides. Look into Google's AngularJS framework for the client side. – Mawg says reinstate Monica Mar 21 '14 at 01:39
  • In conjunction with Angular.JS (which has lots of greta tuorials, plus a lot of support here on S.O), look at http://angular-ui.github.io/bootstrap/ for some GUI stuff. – Mawg says reinstate Monica Mar 21 '14 at 01:53