Run Sql Query From Javascript
Solution 1:
JavaScript can't deal with databases on its own, it just can tell the browser what to do and is only loaded after the server has submitted the page to the browser. So I guess you'll have to work with AJAX. This is quite simple using jQuery:
...
$.post('process.php', {id:curid, date : when}, function(data) {
alert(data);
//data contains all output from process.php, //either in json-format if you jsonencode a results-array//or just a simple string you echo in the phpreturnfalse; //prevent from reloading the page
});
...
Your process.php could look something like:
<?php$curid = $_POST['id'];
$when = $_POST['date'];
//run the queryecho jsonencode($results_array);
//or check if query succeeded and echo e.g. 'ok' or 'failed'?>
You get the idea... ;)
//EDIT:
You should probably use the jQuery UI for the dialog-box to avoid the message as described in the comments. It could be something like this:
<div id="dialog_box" style="display: none;">
Reallydelete?
</div>
$('#dialog_box').dialog({
title: 'Really delete this stuff?',
width: 500,
height: 200,
modal: true,
resizable: false,
draggable: false,
buttons: [{
text: 'Yep, delete it!',
click: function(){
//do the post
}
},
{
text: 'Nope, my bad!',
click: function() {
$(this).dialog('close');
}
}]
});
Solution 2:
Make a webservice. jQuery has functions that will allow you to call a webservice, but you can't build the webservice with jQuery.
Solution 3:
AFAIK, you cannot directly run sql queries through JavaScript on the web page. Even if so, this would be the worst thing to do.
The best way is implementing is to write a service (REST service would be a good fit) which will connect to db, work with the data. Then working with that service through JavaScript would be a better approach.
have a look at the JQuery.ajax() API to find out how you can make Http posts to server.
Solution 4:
You should send the data to a php file.
$.post("delete.php", { id: id, date: date }, function(){alert('delete success!');} )
.error(function() { alert("error"); });
Post a Comment for "Run Sql Query From Javascript"