开发者

How to make a dynamic database consult using jQuery?

开发者 https://www.devze.com 2023-01-26 19:54 出处:网络
I want to make a mysql consult sending a variable from ajax to php. I think the code explains better by itself

I want to make a mysql consult sending a variable from ajax to php. I think the code explains better by itself

<script type="text/javascript" src="jquery.js"></script>
<?php
include "w_config.php"; //only a local php lib, you can ignore
//the function query only returns the query result
print_r(query("select * from artists where artist like '%$_POST[query]%'"));
?>
<script language="javascript" type="text/javascript">
$.ajax({
   type: "POST",
   data: "query=search"
 });
</script>

when I say data: "query=search" I want to send the value "search" as a string to $_POST[query] in the mysql consult: select * from artists wher开发者_StackOverflow中文版e artist like '%$_POST[query]%'

for example data: "query=linkin park";

so the variable $_POST would get the string "linkin park" and update the query


First, if you're using ajax then there should be a separate php file that only returns the search results.

Second, you need to escape the search string to prevent SQL injection (Google will tell you all about it).

Third, you need to decide if you're going to accept something like json and parse it with jquery and build the html, or have the php return ready-made HTML so you can put it in a DIV or something like that (in this case you would probably use jQuery's load).

Fourth, you need to tell us what your HTML looks like, specifically the part that has the input box (search term) and some kind of button.

After these first steps, we can talk about code.


There are several ways to do it. A good one is to write php scripts that return your request answer into XML format.

Call these scripts from your javascript code and manipulate the XML data you received as you want.

So basically:

//Your pseudo PHP Script:
// pre conditions on inputs (assertion, secure strings, ...)

// Write the data selected from your database in XML
// For example:
 SELECT name FROM Artist WHERE id_artist = $_GET['id']
// Start your XML output
<Artists>
// For each name write:
  <Artist name="..." />
</Artists>

// post conditions ...

//Your Javascript Code Example:
$.get({
  url: 'script.php?id=' + id,
  success: function(xml) { //manipulate your XML }
});
0

精彩评论

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

关注公众号