views:

106

answers:

1

Hi,

I have a script which allows users to sign up, which imports data into a MySQL table.

user_availability.php
http://pastebin.com/PSRndXbq

number.js
http://pastebin.com/iYAPuwN7

This script will tell the user if that number is present in the table. However it continually says its not in the table despite it being in there (looking through PMA).

I have tried a few things, like var_dump etc to check the query and it returns fine. I've also tried adding "no" to both the if/else string and it's the same. With that in mind id it would seem the JS is at fault?

Do I have an error in my code?

Cheers

+1  A: 

EDIT:

JS:

$(document).ready(function()
{
    $("#number").blur(function()
    {
        $("#msgbox").removeClass().addClass('messagebox').text('Checking').fadeIn("slow");
        //check the username exists ajax
        // switch to ajax so we can handle errors...
        $.ajax({
            url: "user_availability.php",
            data: { user_name:$(this).val() },
            type: 'post',
            dataType: 'json',
            success: function(data) {
                if(!data.userExists) //if username not avaiable
                  {
                      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                    { 
                      $(this).html('<img src="img/off.png" alt="Number registered" />').addClass('messageboxerror').fadeTo(900,1);
                    });

                  }
                  else
                  {
                      $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
                    { 
                      $(this).html('<img src="img/on.png" alt="Number unregistered"/>').addClass('messageboxok').fadeTo(900,1);    
                    });
                  }
            },
            error: function(request, status, exception){
                $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                { 
                  $(this).html('<img src="img/off.png" alt="Number registered" />').addClass('messageboxerror').fadeTo(900,1);
                });
                // for debug in firefox/firebug only, if you open your js console you should see some error reporting
                try {
                    var data = $.parseJSON(request.responseText);
                    var error = (typeof data.error != 'undefned') ?  data.error : request.responseText;
                    console.log("Error: \"" + error +"\"");
                } catch (e) {
                    console.log("Couldn't parse as JSON: \""+request.responseText+"\"");
                }

            }
        });
});

PHP:

<?php
// config 
include("../config.php");

function return_error($error, $json = array()) {
   $json['error'] = $error;
   header('HTTP/1.0 500 Internal Server Error');
   header('Content-type: application/json'); // send json headers
   // dump the json value should look like {'userExists': true, 'error': 'Some MySQL Error text'}
   echo json_encode($json);
   exit;
} 

$json = array('userExists' => false);

if(!mysql_connect($host, $user, $pass) || !mysql_select_db($database))
{
    return_error(mysql_error(), $json);
}

// dont know your logic for checking with is_numeric so just apply that however, 
// i just changed the variable name so it matches up with what youre passing in the JS
$query = "SELECT email FROM recipients where email ='" . $_POST['user_name'] ."'";


$result = mysql_query($query);

if(!$result){
   return_error(mysql_error(), $json); 
}

$result = array('userExists' => false); // default to false

if(mysql_num_rows($result) > 0) {
  //username already exists
  $json['userExists'] = true; // we found a user so set to true
}

header('Content-type: application/json'); // send json headers
echo json_encode($json); // dump the json value should look like {'userExists': true}
exit;
?>

EDIT:

Ok here you use the variable name user_name:

$.post("user_availability.php",{ user_name:$(this).val() } ,function(data){...});

Yet in your php you are using $_POST['number']. Unless I am missing something you need to use $_POST['user_name'] in the php or use {number: $(this).val()} in the js... They should use the same var name.


'SELECT email FROM recipients where email =' . intval($_POST['number']);

IS this query correct? shouldnt it be something more like one of the following:

'SELECT email FROM recipients where id =' . intval($_POST['number']);

OR

"SELECT id FROM recipients where email ='" . mysql_real_escape_string($_POST['email'])."'";

Also for readability sake (which will help you avoid typos) you might want to use sprintf to format your query strings:

$query = sprintf(
  "SELECT id FROM recipients where email ='%s'", 
  mysql_real_escape_string($_POST['email'])
);
prodigitalson
No, I have a field named "email" in the table I want to check. Its for an SMS system, the system will use Email to SMS. So the table email will have [email protected] values. The form value number will contain just the 1234567890 bit, where users enter their number.
Dean
Same thing with your edit, this is confusing me.Do you need a copy of the actual form page to look at?
Dean
That would be helpful!
prodigitalson
http://pastebin.com/X3CPk2un
Dean
OK the only thing i see is the mismatch between the variable names in the js and php. You changed them so they were the same thing and still got an incorrect result? also are you sure `var_dump(intval($_POST['number']))` is actually the number youre expecting? It might be that casting it to an `integer` is producing an unexpected result depending on the numbers (though this is unlikely unless they have seperators or begin with a zero which i assume youre taking care of pripor to the ajax post).
prodigitalson
They begin with a zero, the var_dump I just ran with $_GET and it has stripped the zero. How do I go about leaving the 0 intact?
Dean
Ok fixed it with is_numeric. However there's certainly a problem with the JS code...anyone able to assist there?
Dean
@dean: can you elaborate on the issues you are having with the JS? Is it not posting to your PHP properly, or what?
prodigitalson
The problem with the JS is that it continually displays the "on.png" icon, even if the number exists in the DB and PHP returns "no". Its the same with anything I put in place of on.png or off.png
Dean
@dean: updated the php and js paste bin's to use json explicitly for the response. Also synced your variable name between the JS and PHP.
prodigitalson
You updated the pastbins? Where?I dont see a change if you modified mine.
Dean
i used the urls you provided above... maybe i did it wrong.. ill jsut edit my response.
prodigitalson
Editing them will generate a new paste with data from my original pastebin. So unless you give me the new URL to it I cant view it. Thanks heaps though :-)
Dean
@dean: ahhh I see... i never really use pastebin apps other than jsFiddle and i usually dont do it for sharing... jsut quick testing
prodigitalson
Well the script fails for some reason, it gets stuck on "Checking". And FYI, its not checking for a user, its checking for a number (that WILL start with 0). Thanks for trying though.
Dean
MySQL error with your second edit @ line 1 (everything looks fine).
Dean
@dean: i know about the number... the variable name isnt important so long as they match up on both sides, change them both to `number` if you want. Ive updated the php and js again.
prodigitalson