dongtan6336
dongtan6336
2016-08-17 10:36

从输入通过ajax获取变量到外部php

已采纳

I have this in index.php I would like to get my input data (range) as variable into my nova.php. When I am trying to use $range = $_GET['range']; in nova.php it shows : Undefined index: range. I think, I should put something like data:{range: range} into myAjax function. But of course it's not working

<input id="range" type="text" name="range" class="enter" value="">
<input type="button" onclick="myAjax()" value="Show nearby" />

my ajax

function myAjax() {
  $.ajax({
       type: "POST",
       url: 'nova.php',
       data:{action:'call_this'},
       success:function(html) {
         alert(html);
       }
  });
}

and my nova.php:

<?php
if($_POST['action'] == 'call_this') {
$con=mysqli_connect("localhost","tech","151987","portnew");
// Check connection 
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$range = $_GET['range']; 
// Perform queries
$query = $con->query("SELECT ( 6371 * acos( cos( radians(53.216908) )*
cos( radians( lat ) ) * cos( radians( lng ) - radians(7.453240) ) + 
sin( radians(53.216908) ) * sin( radians( lat ) ) ) ) AS distance,     
port_name FROM ports HAVING distance < '".$range."' ORDER BY distance LIMIT 0 , 20; ");

while ($row = $query->fetch_assoc()) {
    $port_list[] = $row['port_name'];
}
echo json_encode($port_list);
}
?> 

So basically this script is looking for nearby locations based on latitude, logitude. It's working when I put ...HAVING distance < 150 ORDER BY..., but I would like to set my range in input, and not using static range

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • douchengjue9892 douchengjue9892 5年前

    Check this jsFiddle

    and you ajax function should be

    function myAjax() {
    var range = document.getElementById('range').value;
      $.ajax({
           type: "POST",
           url: 'nova.php',
           data:{action:'call_this',range:range},
           success:function(html) {
             alert(html);
           }
      });
    }
    

    at php code change this line

    $range = $_GET['range'];
    

    to

     $range = $_POST['range'];
    

    also the input of type range should have a value defined. ex value="100". don't leave it blank

    点赞 评论 复制链接分享
  • dselp3944 dselp3944 5年前

    you are using $_GET and you should use $_POST or you can use $_REQUEST when you don't know how the datas are coming

    $range = $_REQUEST['range']; 
    
    点赞 评论 复制链接分享
  • doubi5127 doubi5127 5年前

    You are using post method so use $_POST not $_GET like,

    $range = $_POST['range']; 
    

    And you need to pass it in data like,

    data:{action:'call_this',range:$('#range').val()},
    
    点赞 评论 复制链接分享

相关推荐