开发者

run sql query from Javascript

I am in a pickle right now... I have this function that gets 2 variables from a page then run a sql query after it grabs the data.

function delete(id,date){
    confirmdel=confirm('Are you sure?');
    if(confirmdel){
      var curid = id;
      var whe开发者_高级运维n = date;

      //sql code should go here   

    }
    else{
      //don't do anything
      return false;
    }
  } 

How do I run an sql query from the function or send the data to a php file? I tried using jquery but it would just ignore it, so if I can use jquery please explain/give an example of how to use it.


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 php

  return false; //prevent from reloading the page
});

...

Your process.php could look something like:

<?php

$curid = $_POST['id'];
$when = $_POST['date'];

//run the query

echo 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;">
    Really delete?
</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');
    }
  }]
});


Make a webservice. jQuery has functions that will allow you to call a webservice, but you can't build the webservice with jQuery.


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.


You should send the data to a php file.

$.post("delete.php", { id: id, date: date }, function(){alert('delete success!');} )
.error(function() { alert("error"); });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜