如何通过AJAX使用的onfocus()函数的值保存到一个SQL DATABSE函数、onfocus、AJAX、SQL

2023-09-10 14:54:24 作者:涐想谈一场永不分手的恋爱

基本上我所要做的是从形式保存一个值到SQL数据库中,当用户重点是在另一个输入。我的猜测是用Ajax来做到这一点的最好办法。 (!希望是有道理的),这里是我的code:

脚本:

 函数的StoreLocation(){
       位置= $(#位置)VAL()。
       $阿贾克斯({
           网址:storeLocation.php,
           类型:'后',
           数据:'feed_id ='+位置,
           成功:函数(结果){}
       });

   }
 

在html:

 <形式ID =配置文件行动=的index.php的方法=邮报名称=配置文件>
    <输入类型=文本名称=位置ID =位置自动完成=关闭>
    <输入类型=提交值=提交>
< /形式GT;
 

和StoreLocation.php code:

 < PHP
需要'core.php文件;
要求将connect.php;

$城市= $ _ POST ['feed_id'];
$ idPerson = getfield命令('idPerson','人');

$查询=UPDATE表SET idLocation ='$ idLocation
WHERE idPerson ='$ idPerson';
$ query_run =请求mysql_query($查询);
?>
 
jquery里ajax中怎么将函数中的数据提取出来,放在另外一个其他函数中使用

目前这个code只是移动用户向一个新的URL与变量$市为例: www.example.com/london。

任何帮助将是惊人的,因为我一直停留在本作tooo长:)

额外的code要求:          

  $长期= $ _ GET [术语];


    $查询=请求mysql_query(SELECT * FROM场所,名称,比如%。$名词。%
     ORDER BY名);
     $ JSON =阵列();

        而($名称= mysql_fetch_array($查询)){
             $ JSON [] =阵列(
                '值'=> $名称[名称],
                标签=> $名称[名称]
                    );
              }

     回声json_en code($ JSON);

    ?>
 

解决方案

我能得到你想要的功能。我的例子,下面的解释:

假设两个表:

1)规定 - > ID VARCHAR(2)(铝,锰,佛罗里达州等)和国家VARCHAR(32)(阿拉巴马州,明尼苏达州,佛罗里达州等)

2)城市 - > ID INT(5)AUTOINC,城市VARCHAR(64)(手机,斯蒂尔沃特,迈阿密)和STATE_ID VARCHAR(2)(铝,锰,FL)

通过链接表:cities.state_id = states.id

让我们来看一看的形式了。

// autocomplete.php

叫什么你的头需要JQuery的:

 <脚本SRC =htt​​ps://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js>< / SCRIPT&GT ;
<脚本类型=文/ JavaScript的SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =htt​​ps://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js>< / SCRIPT>

<链接相对=样式类型=文/ CSS的href =htt​​p://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css/>
 

在体内设置您的形式。国家投入将调用javascript函数,当焦点远离此时它会检索与该国有关的城市领域。

 <形式的行动=#>
    <标签=状态→状态:其中; /标签>
    <输入类型=文本名称=状态ID =状态的onblur =getCities();/>

    <标签=城市>城市:LT; /标签>
    <输入类型=文本ID =城市NAME =城市/>
< /形式GT;
 

在的身体的形式,工作jQuery的魔力。我想如果你要使用自动完成,设置之前的工作的的用户输入的任何位置的数据,在这种情况下,状态。为此,我们通过封装code到的功能。

请记住,所发生的事情是自动完成的呼吁通过GET一个PHP文件,返回值的数组,使用自动完成您键入填充列表。

我们希望得到的所有的城市首先那么一旦用户在状态字段输入信息获取所有与该国有关的城市。从本质上讲,我们将设置自动完成两次。

在这里你去 - 函数来处理自动完成:

  //设置自动完成
    函数setAutocomplete(数据){
        $('#城市)。自动完成({
            来源:数据,
            的minLength:1
        });
    }
 

现在设置自动完成,显示所有城市。

  //自动完成默认
    setAutocomplete('getautocomplete.php');
 

在这一点上,如果你开始输入城市输入栏,你会看到,无论状态的所有城市。

现在,我们会处理当用户输入的状态输入的状态会发生什么:

  //获取基于状态输入城市
    功能getCities(){
        。VAR STATE_NAME = $('#国家)VAL();
        setAutocomplete('getautocomplete.php状态='+ STATE_NAME);
    }
 

这就是它!当你进入状态的名字而失去专注于这一领域,这将改变自动完成对国家输入字段,要求getautocomplete.php再次而是由国家的名字这段时间的过滤。

让我们一起来看看PHP文件了。

// getautocomplete.php

从顶部 - >设置数据库连接:

  $库MySQLi =新库MySQLi('本地主机','根','','php_autocomplete');

/ *检查连接* /
如果(mysqli_connect_errno()){
    的printf(连接失败:%S \ N,mysqli_connect_error());
    出口();
}
 

然后设置我们需要的SQL查询的参数。

  //获得参数
$长期=使用isset($ _ GET ['长期'])? $ _GET ['长期']:NULL;
$状态=使用isset($ _ GET ['状态'])? $ _GET ['状态']:NULL;
 

现在我们检查状态参数已定,因为这决定了我们使用的SQL SELECT字符串。

  //设置查询取决于国家是否可用
如果($状态== NULL){
    //获取所有城市
    $查询=选择城市
              由城市
              WHERE城市像%。$任期。%
              ORDER BY城市;
} 其他 {
    //按国家过滤器
    $查询=选择城市
              由城市
              INNER JOIN国就cities.state_id = states.id
              WHERE(州=,$状态。'和类似城市的%。$任期。%)
              ORDER BY城市;
}
 

最后,我们返回并打印出结果(实质上是一个数组),这是什么JQuery的自动完成将用于填充自动完成列表:

  //得到结果
$结果= $ mysqli->查询($查询);
$ JSON =阵列();

而($城市= $结果> fetch_array()){
    $ JSON [] =阵列('值'=> $城市['城市'],'标签'=> $城市['城市']);
}

回声json_en code($ JSON);
 

您不需要使用AJAX。自动完成基本上是做AJAX的getautocomplete.php了。我们只是给它一个额外的参数加入?状态= STATE_NAME,然后在PHP中,我们考虑的参数,并根据需要工艺的SQL SELECT语句。

下面是完整的code这两个文件,​​所以你可以看到它在上下文中没有我的任何意见。我希望这可以帮助您解决问题。您应该能够使这项工作与你的表格和形式。

//// autocomplete.php

 <!DOCTYPE HTML>
< HTML>
< HEAD>
   <元字符集=utf-8>
   <冠军>自动完成< /标题>
   &所述;脚本的src =htt​​ps://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js>&所述; /脚本>
   <脚本类型=文/ JavaScript的SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js>< / SCRIPT>
   <脚本类型=文/ JavaScript的SRC =htt​​ps://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js>< / SCRIPT>
   <链接相对=样式类型=文/ CSS的href =htt​​p://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css/>
< /头>
<身体GT;
   <形式的行动=#>
      <标签=状态→状态:其中; /标签>
      <输入类型=文本名称=状态ID =状态的onblur =getCities();/>
      <标签=城市>城市:LT; /标签>
      <输入类型=文本ID =城市NAME =城市/>
   < /形式GT;
   <脚本类型=文/ JavaScript的>
      //设置自动完成
      函数setAutocomplete(数据){
          $('#城市)。自动完成({
            来源:数据,
            的minLength:1
          });
      }

      //自动完成默认
      setAutocomplete('getautocomplete.php');

      基于状态的输入//获取城市
      功能getCities(){
        。VAR STATE_NAME = $('#国家)VAL();
        setAutocomplete('getautocomplete.php状态='+ STATE_NAME);
      }
  < / SCRIPT>
< /身体GT;
< / HTML>
 

///// getautocomplete.php

 < PHP

$库MySQLi =新库MySQLi('本地主机','根','','php_autocomplete');

/ *检查连接* /
如果(mysqli_connect_errno()){
    的printf(连接失败:%S \ N,mysqli_connect_error());
    出口();
}

//获取参数
$长期=使用isset($ _ GET ['长期'])? $ _GET ['长期']:NULL;
$状态=使用isset($ _ GET ['状态'])? $ _GET ['状态']:NULL;

//设置查询取决于国家是否可用
如果($状态== NULL){
    //获取所有城市
    $查询=选择城市
              由城市
              WHERE城市像%。$任期。%
              ORDER BY城市;
} 其他 {
    //按国家过滤器
    $查询=选择城市
              由城市
              INNER JOIN国就cities.state_id = states.id
              WHERE(州=,$状态。'和类似城市的%。$任期。%)
              ORDER BY城市;
}

//得到结果
$结果= $ mysqli->查询($查询);
$ JSON =阵列();

而($城市= $结果> fetch_array()){
    $ JSON [] =阵列('值'=> $城市['城市'],'标签'=> $城市['城市']);
}

回声json_en code($ JSON);

?>
 

Basically what I am trying to do is save one value from a form into a sql database when a user focus's on another input. I guess the best way to do this is using ajax. (hope that makes sense!) here is my code:

the script:

   function storeLocation() {
       location = $("#location").val();
       $.ajax({
           url: 'storeLocation.php',
           type: 'post',
           data: 'feed_id=' + location,
           success: function (result) {}
       });

   }

the html:

<form id="profile" action = "index.php" method="post" name="profile">
    <input type="text" name="location" id="location" autocomplete="off">
    <input type="submit" value="submit">
</form>

and the StoreLocation.php code:

<?php 
require 'core.php';
require 'connect.php';

$city = $_POST['feed_id'];
$idPerson = getfield('idPerson','person');

$query = "UPDATE table SET idLocation = '$idLocation' 
WHERE idPerson = '$idPerson'"; 
$query_run = mysql_query($query);
?>

Currently this code just moves the user to a new url with the variable $city for example: www.example.com/london.

Any help would be amazing as I've been stuck on this for tooo long:)

extra code requested:

    $term=$_GET["term"];


    $query=mysql_query("SELECT * FROM venue WHERE name like '%".$term."%'
     ORDER BY name ");
     $json=array();

        while($name=mysql_fetch_array($query)){
             $json[]=array(
                'value'=> $name["name"],
                'label'=>$name["name"]
                    );
              }

     echo json_encode($json);

    ?>

解决方案

I was able to get the functionality you were looking for. My example and explanation below:

Assume two tables:

1) states -> id varchar(2) (AL, MN, FL, etc..) and state varchar(32) (alabama, minnesota, florida, etc...)

2) cities -> id int(5) autoinc, city varchar(64) (Mobile, Stillwater, Miami), and state_id varchar(2) (AL, MN, FL)

Tables linked by: cities.state_id = states.id

Let's take a look at the form now.

// autocomplete.php

Call what you need for JQuery in the head:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

Set up your form in the body. The state input will call a javascript function when focus moves away from the field at which point it will retrieve the cities associated with that state.

<form action="#">
    <label for="state">State: </label>
    <input type="text" name="state" id="state" onBlur="getCities();"/>

    <label for="city">City: </label>
    <input type="text" id="city" name="city"/>
</form>

Below the form in the body, work the Jquery magic. I figure if you're going to use autocomplete, set it up to work before the user has input any location data, in this case "state". We do this by encapsulating the code into functions.

Keep in mind that what is happening is that autocomplete is calling a php file via GET, which returns an array of values that autocomplete uses to fill the list as you type.

We want to get all the cities at first THEN once the user has input information in the state field get all the cities associated with that state. Essentially we'll be setting up autocomplete twice.

Here you go - function to handle autocomplete:

// set autocomplete
    function setAutocomplete(data) {
        $('#city').autocomplete({
            source: data,
            minLength: 1
        });
    }

Now set up autocomplete, displaying all cities.

// autocomplete default
    setAutocomplete('getautocomplete.php');

At this point if you start typing in the cities input field you'll see all the cities, regardless of state.

Now we'll handle what happens when the user enters a state in the state input:

// get cities based on state input    
    function getCities() {
        var state_name = $('#state').val();
        setAutocomplete('getautocomplete.php?state='+state_name);
    }

And that's it! When you enter state's name and lose focus on that field, it will alter autocomplete on the state input field, calling getautocomplete.php again but filtering by state name this time.

Let's take a look at the PHP file now.

// getautocomplete.php

From the top -> Set up your database connection:

$mysqli = new mysqli('localhost', 'root', '', 'php_autocomplete');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Then set the parameters we'll need for the SQL Query.

// get parameters
$term    = isset($_GET['term']) ? $_GET['term'] : NULL;
$state   = isset($_GET['state']) ? $_GET['state'] : NULL;

Now we check if the state parameter has been set, as this determines which SQL SELECT string we use.

// set query dependant on if state available
if ( $state == NULL ) {
    // get all cities
    $query = 'SELECT city 
              FROM cities 
              WHERE city LIKE "%'.$term.'%" 
              ORDER BY city';
} else {
    // filter by state
    $query = 'SELECT city 
              FROM cities 
              INNER JOIN states ON cities.state_id=states.id 
              WHERE (state="'.$state.'" AND city LIKE "%'.$term.'%") 
              ORDER BY city';
}

And finally we return and print out the results (essentially an array) which is what JQuery autocomplete will use to populate the autocomplete list:

// get results
$results = $mysqli->query($query);
$json    = array();

while ( $city = $results->fetch_array() ) {
    $json[] = array( 'value' => $city['city'], 'label' => $city['city'] );
}

echo json_encode($json);

You don't need to use AJAX. Autocomplete is essentially doing AJAX on getautocomplete.php already. We just give it an additional parameter by adding ?state=state_name, and then in the PHP we account for that parameter and craft an SQL SELECT statement as required.

Here's the complete code for both files so you can see it in context without any of my comments. I hope this helps you solve your problem. You should be able to make this work with your tables and form.

//// autocomplete.php

<!doctype html>
<html>
<head>
   <meta charset="utf-8">
   <title>Autocomplete</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
   <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
</head>
<body>
   <form action="#">
      <label for="state">State: </label>
      <input type="text" name="state" id="state" onBlur="getCities();"/>
      <label for="city">City: </label>
      <input type="text" id="city" name="city"/>
   </form>
   <script type="text/javascript">
      // set autocomplete
      function setAutocomplete(data) {
          $('#city').autocomplete({
            source: data,
            minLength: 1
          });
      }

      // autocomplete default
      setAutocomplete('getautocomplete.php');

      // get cities based on state input    
      function getCities() {
        var state_name = $('#state').val();
        setAutocomplete('getautocomplete.php?state='+state_name);
      }
  </script>
</body>
</html>

///// getautocomplete.php

<?php

$mysqli = new mysqli('localhost', 'root', '', 'php_autocomplete');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// get parameters
$term    = isset($_GET['term']) ? $_GET['term'] : NULL;
$state   = isset($_GET['state']) ? $_GET['state'] : NULL;

// set query dependant on if state available
if ( $state == NULL ) {
    // get all cities
    $query = 'SELECT city 
              FROM cities 
              WHERE city LIKE "%'.$term.'%" 
              ORDER BY city';
} else {
    // filter by state
    $query = 'SELECT city 
              FROM cities 
              INNER JOIN states ON cities.state_id=states.id 
              WHERE (state="'.$state.'" AND city LIKE "%'.$term.'%") 
              ORDER BY city';
}

// get results
$results = $mysqli->query($query);
$json    = array();

while ( $city = $results->fetch_array() ) {
    $json[] = array( 'value' => $city['city'], 'label' => $city['city'] );
}

echo json_encode($json);

?>