#javascript #php #mysql #ajax
Вопрос:
Я пытаюсь получить данные из своей БД с помощью Ajax-запроса, используя JS и PHP, но когда я в консоли.регистрируйте результат, который он дает мне в качестве ответа DOM, а не Json, которого я жду.
JS :
`
$('#ref').on('input', function() {
let value = $('#ref').val()
$.ajax({
type : "POST",
url : '../ajax/ajaxSearchByRef.php',
data : {
value : value
},
success:function(msg) {
console.log(msg)
}
})
})
`
PHP :
<?php
require './functions/functions.php';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo $e->getMessage();
}
$value = $_POST['value'];
$result = $pdo->query("SELECT a.id, a.article, a.designation_en, a.description_en, a.designation_fr, a.description_fr, b.id as group_id, b.name
FROM products as a INNER JOIN fct_group as b ON b.id = a.fct_group_id AND a.fct_group_id = b.id WHERE a.article LIKE %".$value."%");
$list = $result->fetchAll();
echo json_encode($list);
результат console.log :
<pre class='xdebug-var-dump' dir='ltr'>
<small>C:wamp64wwwpocSompageshome.php:18:</small><small>float</small> <font color='#f57900'>1382</font>
</pre>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="float-right mr-2" > <a href="/uploadpage"> upload a file </a> </div>
<div class="container text-center">
<h2> ALE Service offer Manager </h2>
</div>
<div class="container">
<div class='text-center'>
<input id='ref' type='text' name='reference' placeholder="search by reference" />
</div>
<p> The catalogue contains 27638 products </p>
<table class="table table-hover table-dark">
<thead>
<tr>
<th scope="col">Article reference</th>
<th scope="col"> English designation</th>
<th scope="col"> English description </th>
<th scope="col"> French designation </th>
<th scope="col"> French description </th>
<th scope="col"> Functional Group </th>
</tr>
</thead>
<tbody>
<tr>
<td> HAW-AP1101-RW</td>
<td> NaaS Stellar HAW-AP1101-RW Hardware </td>
<td> NaaS Stellar AP1101. Dual radio 2x2 802.11a/b/g/n/ac AP, integrated antenna, 1 x 10/100/1000Base-T RJ-45) w/802.3af POE, 1x48V DC power interface, Console port. Unrestricted Regulatory Domain. MUST NOT be used for US, Japan or Israel. LAW-AP1101 needed## </td>
<td> NaaS Stellar HAW-AP1101-RW Hardware </td>
<td> NaaS Stellar AP1101. Dual radio 2x2 802.11a/b/g/n/ac AP, integrated antenna, 1 x 10/100/1000Base-T RJ-45) w/802.3af POE, 1x48V DC power interface, Console port. Unrestricted Regulatory Domain. MUST NOT be used for US, Japan or Israel. LAW-AP1101 needed## </td>
<td> X3I </td>
</tr>
<tr>
<td> HAW-AP1101-US</td>
<td> NaaS Stellar HAW-AP1101-US Hardware </td>
<td> NaaS Stellar AP1101. Dual radio 2x2 802.11a/b/g/n/ac AP, integrated antenna, 1 x 10/100/1000Base-T RJ-45) w/802.3af POE, 1x48V DC power interface, Console port. Regulatory Domain United States. LAW-AP1101 needed## </td>
<td> NaaS Stellar HAW-AP1101-US Hardware </td>
<td> NaaS Stellar AP1101. Dual radio 2x2 802.11a/b/g/n/ac AP, integrated antenna, 1 x 10/100/1000Base-T RJ-45) w/802.3af POE, 1x48V DC power interface, Console port. Regulatory Domain United States. LAW-AP1101 needed## </td>
<td> X3I </td>
</tr>
<tr>
<td> 300790730</td>
<td> VQIP Classic-Active Conversion Fee </td>
<td> VQIP, Classic-Active Conversion Fee# </td>
<td> VQIP Classic-Active Conversion Fee </td>
<td> VQIP, Classic-Active Conversion Fee# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955838</td>
<td> VQIP CLASSIC 5K TO 10K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, Up to 9,999 IP Addresses Supported, per IP#address# </td>
<td> VQIP CLASSIC 5K TO 10K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, Up to 9,999 IP Addresses Supported, per IP#address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955846</td>
<td> VQIP CLASSIC 10K TO 25K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 10,000 - 24,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP CLASSIC 10K TO 25K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 10,000 - 24,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955853</td>
<td> VQIP CLASSIC 25K TO 50K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 25,000 - 49,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP CLASSIC 25K TO 50K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 25,000 - 49,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955861</td>
<td> VQIP CLASSIC 50K TO 100K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 50,000 - 99,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP CLASSIC 50K TO 100K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 50,000 - 99,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955879</td>
<td> VQIP CLASSIC 100K TO 250K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 100,000 to 249,999 IP Addresses Supported,#per IP address# </td>
<td> VQIP CLASSIC 100K TO 250K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 100,000 to 249,999 IP Addresses Supported,#per IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955887</td>
<td> VQIP CLASSIC 500K TO 750K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 500,000 to 749,999 IP Addresses Supported,#per IP address# </td>
<td> VQIP CLASSIC 500K TO 750K PER IP ADDRESS </td>
<td> VQIP Classic licensing RTU, 500,000 to 749,999 IP Addresses Supported,#per IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955895</td>
<td> VQIP CLASSIC 1M IP ADDRESS PER IP ADDR </td>
<td> VQIP Classic licensing RTU, 1M IP Addresses Supported, per IP address# </td>
<td> VQIP CLASSIC 1M IP ADDRESS PER IP ADDR </td>
<td> VQIP Classic licensing RTU, 1M IP Addresses Supported, per IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300955994</td>
<td> VQIP ACTIVE 5K TO 10K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, Up to 9,999 IP Addresses Supported, per IP#address# </td>
<td> VQIP ACTIVE 5K TO 10K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, Up to 9,999 IP Addresses Supported, per IP#address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956000</td>
<td> VQIP ACTIVE 10K TO 25K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 10,000 - 24,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP ACTIVE 10K TO 25K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 10,000 - 24,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956018</td>
<td> VQIP ACTIVE 25K TO 50K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 25,000 - 49,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP ACTIVE 25K TO 50K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 25,000 - 49,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956026</td>
<td> VQIP ACTIVE 50K TO 100K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 50,000 - 99,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP ACTIVE 50K TO 100K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 50,000 - 99,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956034</td>
<td> VQIP ACTIVE 250K TO 500K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 250,000-499,999 IP Addresses Supported, per#IP address# </td>
<td> VQIP ACTIVE 250K TO 500K PER IP ADDRESS </td>
<td> VQIP Active licensing RTU, 250,000-499,999 IP Addresses Supported, per#IP address# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956208</td>
<td> VQIP ENUM MGR RTU,1K TO 4,999 SUB </td>
<td> VQIP ENUM Manager RTU, 1,000 to 4,999 Subscribers Supported, per subscriber## </td>
<td> VQIP ENUM MGR RTU,1K TO 4,999 SUB </td>
<td> VQIP ENUM Manager RTU, 1,000 to 4,999 Subscribers Supported, per subscriber## </td>
<td> YB </td>
</tr>
<tr>
<td> 300956216</td>
<td> VQIP ENUM MGR RTU,5K TO 9,999 SUB </td>
<td> VQIP ENUM Manager RTU, 5,000 to 9,999 Subscribers Supported, per subscriber## </td>
<td> VQIP ENUM MGR RTU,5K TO 9,999 SUB </td>
<td> VQIP ENUM Manager RTU, 5,000 to 9,999 Subscribers Supported, per subscriber## </td>
<td> YB </td>
</tr>
<tr>
<td> 300956224</td>
<td> VQIP ENUM MGR 10K TO 25K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 10,000 - 24,999 Subscribers Supported, per#subscriber# </td>
<td> VQIP ENUM MGR 10K TO 25K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 10,000 - 24,999 Subscribers Supported, per#subscriber# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956232</td>
<td> VQIP ENUM MGR 25K TO 50K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 25,000 - 49,999 Subscribers Supported, per#subscriber# </td>
<td> VQIP ENUM MGR 25K TO 50K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 25,000 - 49,999 Subscribers Supported, per#subscriber# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956240</td>
<td> VQIP ENUM MGR 50K TO 100K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 50,000 - 99,999 Subscribers Supported, per#subscriber# </td>
<td> VQIP ENUM MGR 50K TO 100K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 50,000 - 99,999 Subscribers Supported, per#subscriber# </td>
<td> YB </td>
</tr>
<tr>
<td> 300956257</td>
<td> VQIP ENUM MGR 100K TO 250K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 100,000-249,999 Subscribers Supported, per#subscriber# </td>
<td> VQIP ENUM MGR 100K TO 250K PER IP ADDR </td>
<td> VQIP ENUM Manager RTU, 100,000-249,999 Subscribers Supported, per#subscriber# </td>
<td> YB </td>
</tr>
</tbody>
</table>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$('#ref').on('input', function() {
let value = $('#ref').val()
$.ajax({
type : "POST",
url : '../ajax/ajaxSearchByRef.php',
data : {
value : value
},
success:function(msg) {
console.log(msg)
}
})
})
</script>
</html>
Комментарии:
1. Добавить
console.log
результат2. в функции успеха ? Я добавил его, и это значение не определено
3. добавьте результат «console.log(msg)» в вопрос
4. Вы не можете извлечь
../ajax/ajaxSearchByRef.php
, например, изlocalhost:8080/home.php
(технически вы можете, но результат, вероятно, не такой, как вы ожидаете). Почему вы идете вверх? Какова ваша структура папок и каков ваш www-корень? Вы пытаетесь загрузить файл из-за пределов своего проекта?5. У вас есть опечатка в sql-запросе , так как ваш шаблон поиска должен быть заключен в одинарные кавычки:
'%...%'
, но вы не должны использовать интерполяцию строк, вы должны использовать подготовленную инструкцию с параметризованными запросами.
Ответ №1:
Проблема заключается в передаче запроса.
- Убедитесь, что ваш
php
код находится в другом файле, похоже, что это не так. - Даже если вы выполняете запрос на ту же страницу, убедитесь, что вы обрабатываете его правильно.
Например,
HTML, JS, CSS в другом файле и php в другом файле, затем
<?php
require './functions/functions.php';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo $e->getMessage();
}
if(isset($_POST['value'])){//Work on request accurately
$value = $_POST['value'];
$result = $pdo->query("SELECT a.id, a.article, a.designation_en, a.description_en, a.designation_fr, a.description_fr, b.id as group_id, b.name
FROM products as a INNER JOIN fct_group as b ON b.id = a.fct_group_id AND a.fct_group_id = b.id WHERE a.article LIKE %".$value."%");
$list = $result->fetchAll();
echo json_encode($list);
}
HTML,JS и php — все на 1 странице, и делать запрос на одну и ту же страницу {не рекомендуется}
<?php
require './functions/functions.php';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo $e->getMessage();
}
if(isset($_POST['value'])){//Work on request accurately
$value = $_POST['value'];
$result = $pdo->query("SELECT a.id, a.article, a.designation_en, a.description_en, a.designation_fr, a.description_fr, b.id as group_id, b.name
FROM products as a INNER JOIN fct_group as b ON b.id = a.fct_group_id AND a.fct_group_id = b.id WHERE a.article LIKE %".$value."%");
$list = $result->fetchAll();
echo json_encode($list);
}
else{?>
<!-- Here the HTML part with javascript css whatever -->
<?php
}
?>
После того, как вы правильно обработаете запрос, вы получите именно то, что хотите для конкретного запроса.
Вывод:-
- Не связывайтесь с интерфейсом и бэкендом {php, html} для файла, на который сделан запрос Ajax.
- Старайтесь обрабатывать запросы как можно аккуратнее, это уменьшит конфликты между различными запросами.
например, для:-
if($_POST['action']== 'hello') echo "handling request for hello";
else if($_POST['action']== 'bye' echo "handling request for bye";
.
.
.
else { //some error code or some defaults}
Для любых запросов прокомментируйте ниже.