tags:

views:

65

answers:

3

In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:

<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">

</form>

The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.

Is there any way to check the database for value without refreshing the page?

+2  A: 

It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.

You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.

Pekka
Pekka advice is very good, you should consider that some browsers may have javascript disabled
Fábio Antunes
+1  A: 

While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.

EDIT - Here is my illustration - this uses Prototype's Form.serialize function.

<form id="my_form" onSubmit="return checkUsername();">
  Username: <input type="text" name="username" id="username" />
</form>

<script type="text/javascript">
  var xhr; // global XMLHttpRequest object
  var formElem = $('my_form'); // our form element

  function checkUsername() {
    var formData = formElem.serialize();
    sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
  }

  function sendPOSTRequest(toURL, sendData) {
    xhr = false;
    if (window.XMLHttpRequest) {
       xhr = new XMLHttpRequest();
       if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/html');
       }
    } else if (window.ActiveXObject) {
       try {
          xhr = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          try {
             xhr = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
       }
    }
    if (!xhr) {
       alert('Cannot create XHR');
       return false;
    }

    xhr.onreadystatechange = handleResponse;
    xhr.open('POST', toURL, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", sendData.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(sendData);
  }

  function handleResponse() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var result = xhr.responseText;
        // result is now whatever content was returned by the PHP script
        // do whatever you want with the result here
        // for example, you might have the PHP return 'true' or some such thing, and then
        // change window.location, or perhaps if it returns 'false' you put up an alert('No!')
        // use your imagination, go nuts
      } else {
        alert('The script returned an error.');
      }
    }
  }
</script>

There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.

Dustin Fineout
Why give up support for non-JS users for something that can be achieved differently when JS is active? I don't get it.
Pekka
I wouldn't at all. I'm just pointing out one way to accomplish what's being asked. I would recommend sticking to server-side validation and never relying on JS.
Dustin Fineout
@Dustin: Can you please illustrate?
RPK
A: 

Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.

Its a pain, but that's how HTTP works.

Sqoo