Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.

if ($publish == '') { 
Link to publish.html
} else { 
Link to edit.html
} 

What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.

How can it be donw using javascript, jquery or ajax?? Please assist.

like image 319
Sam Avatar asked Apr 10 '11 07:04

Sam


People also ask

Can you query a database with JavaScript?

It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.


1 Answers

I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.

Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.

PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.

For example, you could have javascript call a script like: http://www.myserver.com/ajax_function.php?do=queryTheDatabase

In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.

like image 114
soulkphp Avatar answered Sep 19 '22 14:09

soulkphp