Solved

Mockjax for php script is always getting the worng value

Posted on 2013-12-23
13
785 Views
Last Modified: 2013-12-26
I am using the Jquery validation plugin to validate the username format, however I want to add an extra step to validate if the user already exists in the data base or not,
   So I have created the following php script (Which is working pretty well):
<?php
require_once(dirname(__FILE__).'/db.php');
$HTML='';
if(isset($_POST['username']) && !empty($_POST['username'])){
      $username=$_POST['username'];
      $username="ashraf";
      $query="select username from users where username='".$username."'";
      $res=pg_exec($con, $query);
      $count= pg_num_rows($res);
      if($count > 0){
        $HTML='Username is not available';
      }else{
        $HTML='Username is available';
       }
      }
   else{
      $HTML='Please enter a username';
   }
  echo $HTML;
?>

Open in new window


And I have created the following mockjax script:
        $(document).ready(function() {
                        $.mockjax({
                                url: "useravailable_check.php",
                                type: "POST",
                                response: function(settings) {
                                          var username = settings.data.username,
                                          response="Username is not available";
                                          this.responseText = "true";
                                          if(response!='Username is available'){
                                                this.responseText = "false";
                                        }
                                },
                        });

Open in new window

 And below is the validator :
                var validator = $("#createuser").validate({
                        rules: {
                                 username: {
                                        required: true,
                                        minlength: 6,
                                        remote: "useravailable_check.php"
                                },
                               },
                             messages: {
                                   username: {
                                        required: "Enter a username",
                                        minlength: jQuery.format("Enter at least {0} characters"),
                                        remote: jQuery.format("{0} is already in use")
                                },
                             },

Open in new window

       But I am getting always back that the user is available, is there anything wrong in the mockjax function I have?
0
Comment
Question by:Ashraf Hassanein
  • 7
  • 5
13 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39737965
What is "mockjax?"  I've never heard of this.  Have you verified that the AJAX call is working correctly, calling the backend script and returning the data you need?  You can use a simple JavaScript alert() to print out the intermediate variables.
0
 

Author Comment

by:Ashraf Hassanein
ID: 39738113
In the jquery validation you can define different rule to get different responses for the same elements what I understood that the ajax can not be included as a rule for the jquery validation and instead we use the mockjax where we mock the ajax functionality, that is why I am using the mockjax orcan I can use the ajax here?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39738329
Wow, a lot of moving parts with many things that can go wrong undected.  Let's start with the background script and work up from there.  In the first code snippet on line 8, what is the value of $res?
0
 

Author Comment

by:Ashraf Hassanein
ID: 39738390
in this one it should return back the username, and if it exists the count in line 9 is bigger than 1 else the count is less than one.
My target is the user enter a new username then that it is checked in the front end (jquey) that it is not short nor empty then it sends it to the backend to check if it is available or not.
For now the first 2 parts work properly as with Jquery (It only works when you press the submit button and not outof focus , but this a minor issue I will investigate later:-) )
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39738441
I understand that the intent is to return the username, but I'm not sure that's actually what will happen.  Please see the link here.  The function pg_exec() does not exist in the PHP language.  If you mean pg_execute() you would be using a prepared statement, not a query string.
http://www.php.net/manual-lookup.php?pattern=pg_exec

That is why I would want to test the value of $res and issue some kind of message.

As to the overall design, why not just do all the validation on the server side?  You can check length, appropriate character set, etc., as well as test for pre-existing username, and you can send back a message if there is any kind of misstep.  If not, put the new username into the data base and return the auto_increment id.  The front-end script can recognize the presence of an integer and the absence of a message as a signal that the new username has been created.
0
 

Author Comment

by:Ashraf Hassanein
ID: 39738747
Ray I totally agree about the design is a bit mess, it is better to do all on server side, the point that I have started my design assuming I will do all my checks on the client side, but by time it is always appearing an extra check to be done ending up in this situation.
Regarding your troubleshooting indeed it appears that the php has the problem, I execute the php using using a non existing username, twice:
   With pg_exec():
      $res=pg_exec($con, $query);
    I get the following:
       resource(6) of type (pgsql result)
    With pg_execute:
             $res=pg_execute($con, $query);
     I get the following:
         PHP Warning:  pg_execute() expects parameter 1 to be string, resource given in                      useravailable_check.php on line 8
NULL
PHP Warning:  pg_num_rows() expects parameter 1 to be resource, null given in useravailable_check.php on line 10
         
            And here my db.php which I use to connect:
<?php
$db="mydb";
$hostname = "localhost";
$user = "myself";
$password = "password";
$con = pg_connect("host=".$hostname." dbname=".$db." user=".$user." password=".$password) or die("Could not connect database");
?>


  What is your advice?
0
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

 

Author Comment

by:Ashraf Hassanein
ID: 39738758
It seems that pg_exec exists for something else:
http://scholar.lib.vt.edu/manuals/php/function.pg-exec.html
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39738772
Ha!  I am not laughing at you at all, but this site you are using is ancient history.  I started writing PHP when the current PHP level was PHP3, in the late 1990's.  PHP 5 has been the current level for more than half-a-dozen years, and PHP 5.2 is now considered obsolete.  So anything with PHP3 and PHP4 in the caption is automatically obsolete.

Ditch Virginia Tech's PHP web site.  Instead, choose some learning resources from this article.  I promise that they are much more up-to-date!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

I'm not exactly sure how to look at the code set right now (playing Santa Claus) but maybe in the morning before the children get up I can have a look.  Otherwise, I will be back to the issues on Thursday.

Best regards, ~Ray
0
 

Author Comment

by:Ashraf Hassanein
ID: 39738781
:-) well I am  totally in mess so that is why I was hunting in the web sites.
I have checked :    

      I have done:
         $res=pg_exec($con, $query);
         $resultArr = pg_fetch_all($res);
         var_dump($resultArr);
     And:
         $res=pg_query($con, $query);
         $resultArr = pg_fetch_all($res);
         var_dump($resultArr);

    So I changed all pg script to pg_query with the assumption (As I can see in the command description it returns false if no record is found):
 
      $res=pg_query($con, $query);
      $resultArr = pg_fetch_all($res);
      if(!$resultArr){
   And honestly I can see it is working but I want your advice from and expert, so what do you think?

     I have also changed my rules in the jquery validator as the previous question and now it is working.
     Only the replace is not (As the previous question) so I replaced it with trim in the server side script and it is working pretty well however I am only curious now why the replace is not working - thank you so much for your help, and sorry for ruining your christmas night.
0
 

Author Closing Comment

by:Ashraf Hassanein
ID: 39739951
As usual Ray is always great, and helpful
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39739980
Thanks for the points and thanks for using EE.  Glad to see you making progress here :-)
0
 

Author Comment

by:Ashraf Hassanein
ID: 39740006
I hope one day in my life to reach to you experience :-)
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 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

23 Experts available now in Live!

Get 1:1 Help Now