Chris Bier
Chris Bier

Reputation: 14455

Dynamically Query a Database to check for value

I need to check if a certain value "SheetNumber" is in my mysql database dynamically. I have seen it done on popular web sites and I am trying to find a good tutorial to outline it for me. I am fairly new to Javascript but i know a lot of PHP.

I am anxious to learn how to do this.

Upvotes: 0

Views: 3135

Answers (3)

Ali
Ali

Reputation: 267207

You will need to do this using Ajax. I recommend the Jquery library. Install it using the Jquery documentation, and then use something like the following:

Javascript:

function makeAjaxRequest()
{
   var url="script-that-checks-db.php";
   $.get(url,{},verifyDb);
}

function verifyDb(response)
{
    if (response==1)
    {
       //The value exists, do what you want to do here
    }

    else
    {
      //The value doesn't exist
    }
}

You can have makeAjaxRequest() invoked when someone clicks a link, clicks a button, or anything else, e.g:

<a href="#" onclick="makeAjaxRequest();">Check database</a>

The php code of the file script-that-checks-db.php (of course, name it something different) will be responsible for checking the db. The code would look something like this.

PHP:

<?php

//Do the mysql query and find out if the value exists or not.

if ($exists==true)
   echo "1"; //1 will indicate to javascript that the value exists.
else
   echo "0";
?>

You could also use JSON here rather than the 0/1 method, but because you are new I think this will be simple enough for you.

Hope this helps, if you have any questions feel free to ask. Also, feel free to change the function and file names.

Upvotes: 4

pix0r
pix0r

Reputation: 31290

It's pretty simple; check the jQuery docs on the AJAX functions: jQuery.get()

You'll need to set up a simple PHP service that returns raw data, XML, or JSON-formatted data that you can then interpret with your jQuery callback function.

Example:

function checkData(userInputValue) {
  jQuery.get('ajax-backend.php?value='+userInputValue, false, function(data) { alert('Response from server: ' + data)});
}

Instead of using alert() to display the response from the server, you'd probably want to interpret this value and change something on the page indicating whether the operation was successful.

Here's a more detailed example from a previous question: Beginning jQuery help

Upvotes: 2

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67197

I assume that by "dynamically" you mean "without leaving the page", suggesting a "AJAX" solution.

You cannot the access your database using client-side JavaScript, I recommend using a JavaScript library/framework like JQuery to call a PHP script "behind the scenes" that does what you want.

Upvotes: 1

Related Questions