【问题标题】:Trying to send data to a alert in AJAX from PHP and MySQL尝试从 PHP 和 MySQL 将数据发送到 AJAX 中的警报
【发布时间】:2018-04-29 20:44:46
【问题描述】:

我在 ajax 中构建此代码以将数据从表单发送到 php 文件以在同一页面中显示警报,我在网上查看了几个示例但无法解决。

我只想从警报中的 php 返回“回声数据”,但我一直只收到一条消息,例如“Oportunidade cadastrada com sucesso!”。

似乎 php 没有正确执行 if/else,而是 idk。 有人可以帮忙吗?

//AJAX

    $("#formulario_op").on('submit', function (e) {
        $('#cadVaga').modal('hide');    
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "cadastraop.php",
            data: $('#formulario_op').serialize(),
            success: function (data) {
                alert(data);
                location.reload();
            }
        });
    return false;
    });//END AJAX

//php

require("conexao.php");

$name = $_POST['name'];
$descricao = $_POST['descricao'];
$valor = $_POST['valor'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];

$sql = "SELECT lat,lng FROM anuncios WHERE lat = '$lat' and lng = '$lng' ";
$testa_local = mysqli_query($link, $sql);

if($row = mysqli_fetch_array($testa_local)){  // if the lat and lng already in the database
    if ($lat == $row['lat'] && $lng == $row['lng']) {
        echo "Favor alterar o marcador.";   
    }

}else{

$query = ("INSERT INTO `anuncios` (`name`, `address`, `lat`, `lng`, `type`, `descricao`, `situacao`, `tempoAtivo`, `valor`, `FKCategoria`) VALUES ('$name', 'any', '$lat', '$lng', 'qualquer 1', '$descricao', 'ativo', '2018-04-28', '$valor', '1')");

mysqli_query($link,$query);

echo "Oportunidade cadastrada com sucesso!";

}

【问题讨论】:

  • AJAX 不是一种语言。您正在进行 AJAX 调用,看起来像是 jQuery....
  • 你能用 MySQL 客户端(比如 phpmyadmin 什么的)检查你的 MySQL 表吗?您的条目是否已添加到表格中?
  • 是的,在“phpmyadmin”中,表中的条目是正确的。
  • 所以你永远不会得到“Favor alterar o marcador.”?尝试回显查询,将其输入您的 phpmyadmin 并检查结果
  • 您是否尝试过已经是表中单个记录的一部分的“lat”和“lng”值?否则,您的代码似乎可以正常工作。 (虽然imo在if中有多余的if,但imo不需要检查两次)。

标签: php jquery mysql ajax


【解决方案1】:

在 PHP 中(替换):

echo "Oportunidade cadastrada com sucesso!";

与:

echo json_encode(['answer':'Oportunidade cadastrada com sucesso!']);

在 JQuery 中:

success: function (data) {
            alert(data);
            location.reload();
        }

与:

success: function (data) {
            let str = JSON.parse(data.responseText);
            console.log(str.answer)

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多