【问题标题】:php file's code not executing through ajax callphp文件的代码未通过ajax调用执行
【发布时间】:2020-10-15 11:44:15
【问题描述】:

我的 PHP 文件中有一个按钮,当我单击该按钮时,我希望运行另一个 PHP 文件并将一些数据保存在 MySQL 表中。为此,我正在使用此链接 (How to call a PHP function on the click of a button) 中建议的 AJAX 调用,这是 StackOverflow 本身的答案。

这是我的 show_schedule 文件,我试图从中执行另一个 PHP 文件的代码:

$('.edit').click(function() {
        var place_type = $(this).attr("id");
        console.log(place_type);
        $.ajax({
            type: "POST",
            url: "foursquare_api_call.php",
            data: { place_type: place_type }
        }).done(function( data ) {
            alert("foursquare api called");
            $('#userModal_2').modal('show');
        });
    });

这里的“编辑”是按钮的类,并且该按钮的 id 正在控制台中正确打印。

这是我的foursquare_api_call.php 文件(应该在单击按钮时运行):

<?php
    session_start();
    include('connection.php');

    if(isset($_POST['place_type'])){
        $city = $_SESSION['city'];
        $s_id = $_SESSION['sid'];
        $query = $_POST['place_type'];
        echo "<script>console.log('inside if, before url')</script>";
        $url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
        $json = file_get_contents($url);
        echo "<script>console.log('inside if, after url')</script>";
        $obj = json_decode($json,true);
        for($i=0;$i<sizeof($obj['response']['venues']);$i++){
            $name = $obj['response']['venues'][$i]['name'];
            $latitude = $obj['response']['venues'][$i]['location']['lat'];
            $longitude = $obj['response']['venues'][$i]['location']['lng'];
            $address = $obj['response']['venues'][$i]['location']['address'];

            if(isset($address)){
                $statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
                $result = $statement->execute();
            }
            else{
                $statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
                $result = $statement->execute();
            }
        }
    }
?>

console.log 没有记录在控制台中,“temp”表也没有更新。谁能告诉我我在哪里犯错?或者甚至可以像这样执行PHP文件的代码?

【问题讨论】:

  • 你检查了网络标签吗?
  • “foursquare_api_call.php”文件有一个条目。
  • 那么当你点击它时会有什么反应
  • 先显示警告信息,再显示模型。
  • 但“temp”表中没有条目。

标签: javascript php jquery mysql ajax


【解决方案1】:

您的 JavaScript 正在向执行您的 PHP 程序的 URL 发出 HTTP 请求。

当它得到响应时,你这样做:

    .done(function( data ) {
        alert("foursquare api called");
        $('#userModal_2').modal('show');
    }

所以你:

  1. 提醒某事
  2. 显示模型

您绝不会对data 进行任何操作,因为它是放置响应的位置。

仅仅向浏览器发送一些包含脚本元素的 HTML 并不会导致浏览器将该 HTML 转换为 DOM 并执行所有脚本元素。

你需要明确地这样做。


也就是说,通过 Ajax 发送带有嵌入式 JS 的 HTML 块充其量是混乱

这就是为什么大多数 Web 服务返回格式为 JSON 的数据并将其留给客户端 JS 来处理该数据的原因。

【讨论】:

  • OP 在评论中说没有记录添加到表中,这是在 PHP 端完成的。
【解决方案2】:

要返回 php 代码的内容,你可以这样做

你可以调用这个函数

function check_foursquare_api_call(place_type) {
    var place_type= encodeURIComponent(place_type);
    var xhttp;
//last moment to check if the value exists and is of the correct type
    if (place_type== "") {
    document.getElementById("example_box").innerHTML = "missing or wrong place_type";
    return;
  } 
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("example_box").innerHTML = xhttp.responseText;
      $('#userModal_2').modal('show');
    }
  };
 
    xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
    xhttp.send();
}

这将允许您发送和执行foursquare_api_call文件的代码并将任何元素返回到example_box,如果需要,您可以返回整个模态, 您可以使用任何 POST / GET 方法,监控进度,在此处查看更多信息 XMLHttpRequest

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多