как получить два значения, чтобы получить результат в PHP и AJAX - PullRequest
0 голосов
/ 03 июля 2019

Я пытаюсь получить два значения из формы в php - это вес и пол, используя jquery и ajax, чтобы показать цену, соответствующую этому полу и весу,

таблица mysql выглядит следующим образом

gender range1  range2  price
male     0       100     20
male    101      200     30
female   0       100     25
female  101      199     46

форма php выглядит следующим образом

  <input type="text" name="gender" id="gender">
  <input type="number" name="weight">
 price <span id="result"></span>
<input type="button" herf="javascript:;" onclick="getprice" value="">

функция ajax выглядит следующим образом

    function getprice (gender, whieght) {
        var str_num {
        "gender" : gender,
        "weight" : weight
       };
             $.ajax({ data: str_num, 
        url: 'selectprice.php',
        type: 'post'
        beforeSend: function() {
     $("#result").html("in progress..");},
           succes: function (reponse){
         $("result").html(reponse);
                  })}}

selectprice.php выглядит следующим образом

 $gender = $_GET["gender"];
  $weight = $_GET["weight"];
   $fetch = "SELECT * FROM table where gender like $gender and weight 
  >range1 and <range2"; 
$result = mysqli_query($con, $fetch) or die("Ocurrio un error en la 
  consulta SQL");
while ($row = $resul->fetch_assoc()) {
    echo "".$row["price"]."";
    }
   echo $result;

когда я нажимаю кнопку, ничего не происходит, я действительно могу воспользоваться некоторой помощью, заранее спасибо

Ответы [ 3 ]

1 голос
/ 03 июля 2019

Вы действительно упаковали ошибки в.

<input type="text" name="gender" id="gender">
<input type="number" name="weight" id="weight">
price 
<input type="button" herf="javascript:;" onclick="getprice()" value="">


<script>
$(document).ready(function() {
});
function getprice () {
    var str_num = {
        "gender" : $('#gender').val(),
        "weight" : $('#weight').val()
    };
    $.ajax({ 
        data: str_num, 
        url: 'selectprice.php',
        type: 'post',
        beforeSend: function() {
            $("#result").html("in progress..");
        },
        succes: function (reponse){
            $("result").html(reponse);
        }
    })
};

</script>

PHP файл

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', true);
//  ini_set('log_errors', true);

var_dump($_POST); // Your doing a post not a get in the javaacript.
0 голосов
/ 03 июля 2019

Вы смешиваете здесь "POST" и "GET".

Если вы хотите использовать «GET», следуйте совету Навида

Если вы хотите использовать «POST», найдите два возможных решения ниже:

1) Легко: включить ваши переменные непосредственно в данные

function getprice (gender, weight) {

         $.ajax({ data: "gender" : gender,
    "weight" : weight, 
    url: 'selectprice.php',
    type: 'post'
    beforeSend: function() {
 $("#result").html("in progress..");},
       success: function (reponse){
     $("result").html(reponse);
              })}}

selectprice.php:

заменить

 $gender = $_GET["gender"];  $weight = $_GET["weight"];

с

 $gender = $_POST["gender"];  $weight = $_POST["weight"];

2) Немного сложный: используйте stringify

function getprice (gender, weight) {
    var data={
    "gender" : gender,
    "weight" : weight
   };

var str_num = JSON.stringify(data);

         $.ajax({ data: str_num, 
    url: 'selectprice.php',
    type: 'post'
    beforeSend: function() {
 $("#result").html("in progress..");},
       success: function (reponse){
     $("result").html(reponse);
              })}}

selectprice.php:

заменить

 $gender = $_GET["gender"];  $weight = $_GET["weight"];

с

$json_data_from_js= json_decode($_POST['data']);
$gender = $json_data_from_js->gender ;
$weight = $json_data_from_js-> weight;
0 голосов
/ 03 июля 2019

Вам необходимо обновить строку:

url: 'selectprice.php?weight='+weight+'&gender='+gender,

Или вы можете передать data сразу после url

url: 'selectprice.php',
data: {weight:weight, gender,gender},
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...