Ajax成功返回

时间:2015-04-28 10:45:37

标签: javascript php jquery html ajax

有人可以帮我解决这个问题 我有这个php文件,用于将数据插入我的数据库,所有这些都是由ajax函数发送的

<?php
header('Content-type: application/json');
ini_set('max_execution_time', 300);
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
$num= $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = explode(",", $_POST['hora']);
$a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$c = array_fill_keys(array_keys(array_diff($a,$hora)),null) + $a;
ksort($c);
for ($i=0; $i<17; $i++){
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(mysql_error($mysqli));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if(!$stmt->execute()){
    echo json_encode(array('status' => 'error','message'=> 'Opppss...Os Registo(s) não foram gravado(s)'));
}
else{
   echo json_encode(array('status' => 'success','message'=> 'Registo(s) gravado(s) com sucesso'));
}
$stmt->close();
}
$mysqli->close();
?>

这是我的ajax功能

function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
var data = 'dia='+ dia + '&sala='+ sala + '&hora='+ tempos + '&num='+ num;
$.ajax({ 
type: "POST",
dataType: "html",
url: "registerBd.php",
data: data, 
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error:function(response){
console.log("Aqui 2");
alert("something went wrong");
}});
return false;
}

由我的表格调用

 <form method="post" id="salas" name="salas" onsubmit="postData()" >

但即使我的数据插入dabase

,我的功能也始终出错

新更新

新的插入php命名为registerBd.php

<?php
header('Content-type: application/json');
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
    $horas = $c[$i];
    $stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
    $stmt->bind_param('ssi', $dia, $sala, $horas);
    if (!$stmt->execute()) {
        echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
    }
}
echo json_encode(array('status' => 'success', 'message' => 'Registo(s) gravado(s) com sucesso'));
$stmt->close();
unset($stmt);
?> 

修改为ajax

 <script>
             function postData(){
                var dia = document.getElementById('dia').value;
                var sala = document.getElementById('sala').value;
                var tempos = [];
                var s = document.getElementById('hora');
                for (var i = 0; i < s.options.length; i++) {
                    if (s.options[i].selected == true) {
                        var valores = s.options[i].value;
                        tempos.push(valores);
                    }
                }
                console.log(tempos);
                var num = document.getElementById('num').value;
                    $.ajax({ 
                            type: "POST",
                            dataType: "json",
                            url: "registerBd.php",
                            data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
                            success: function (response) {
                            console.log(response);
                            $('#ajaxDivOk').css("display", "block");
                            $('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
                            alert(response);
                         },
                            error: function(jq,status,message) {
                            console.log( message );
                            alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
                            }
                       });
                       return false;
                }
        </script>

但是仍然有同样的问题,并且在chrome控制台中,insertBd.php在插入后是红色的,所以我认为问题应该在这里,即使所有内容都记录到数据库中

新的更新...这真的很奇怪 删除了registerDb.php中的2行

unset($smtp);
?>

使用debug而不使用 我明白了 检查图像 http://postimg.org/image/8wtwxod3r/

没有debuger http://postimg.org/image/5nctzrjkv/

检查底部似乎registerBd.php被取消了......为什么?

所以现在我迷失了

更新3

我称之为ajax函数

<form method="post" id="salas" name="salas" onsubmit="postData()" > 

我的ajax功能

<script>
             function postData(){
                var dia = document.getElementById('dia').value;
                var sala = document.getElementById('sala').value;
                var tempos = [];
                var s = document.getElementById('hora');
                for (var i = 0; i < s.options.length; i++) {
                    if (s.options[i].selected == true) {
                        var valores = s.options[i].value;
                        tempos.push(valores);
                    }
                }
                console.log(tempos);
                var num = document.getElementById('num').value;
                    $.ajax({ 
                            type: "POST",
                            dataType: "json",
                            url: "registerBd.php",
                            data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
                            success: function (response) {
                            console.log(response);
                            $('#ajaxDivOk').css("display", "block");
                            $('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
                            alert(response);
                         },
                            error: function(jq,status,message) {
                            console.log( message );
                            alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
                            }
                       });
                       return false;
                }
        </script>

和我的registerBd.php

<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
    $horas = $c[$i];
    $stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
    $stmt->bind_param('ssi', $dia, $sala, $horas);
    if (!$stmt->execute()) {
        echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
    }
}
$response = "Registo(s) gravado(s) com sucesso";
echo json_encode($response);
$stmt->close();

在实模式中我有这个

Request URL: http://localhost/multiple/registerBd.php
Method: POST
Status: Request was cancelled.

Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Origin: http://localhost
Referer: http://localhost/multiple/registo_salas.php
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.44 (KHTML, like Gecko) JavaFX/8.0 Safari/537.44
X-Requested-With: XMLHttpRequest

Request data

dia=2&sala=5&hora%5B%5D=1&hora%5B%5D=2&hora%5B%5D=3&num=3

CallStack
send ([native code]:0:0)
send (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:25552)
ajax (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:21305)
postData (registo_salas.php:104:26)
onsubmit (registo_salas.php:116:27)

更新4

我不知道这是不是你的意思......但我认为不是(我的错......)

<script>
            $('#salas').on('submit', function(event) {
                event.preventDefault();
                function postData(){
                var dia = document.getElementById('dia').value;
                var sala = document.getElementById('sala').value;
                var tempos = [];
                var s = document.getElementById('hora');
                for (var i = 0; i < s.options.length; i++) {
                    if (s.options[i].selected == true) {
                        var valores = s.options[i].value;
                        tempos.push(valores);
                    }
                }
                console.log(tempos);
                var num = document.getElementById('num').value;
                event.preventDefault();
                    $.ajax({ 
                            type: "POST",
                            dataType: "json",
                            url: "registerBd.php",
                            data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
                            success: function (response) {
                            console.log(response);
                            $('#ajaxDivOk').css("display", "block");
                            $('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
                            alert(response);
                         },
                            error: function(jq,status,message) {
                            console.log( message );
                            alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
                            }
                       });
                       return false;
                }
              });

我得到了

未捕获的ReferenceError:postData未定义@ubisto_salas.php:120

1 个答案:

答案 0 :(得分:1)

我在这里看到一些问题:

  1. 您正在发送回json,但是在ajax调用中指定了dataType: "html",。您应该将其更改为dataType: "json",
  2. 您正在混合使用mysql apis:
    or die(mysql_error($mysqli));
    当您使用mysql_*时,不能使用任何mysqli_*函数。您需要以下内容:
    or die(mysqli_error($mysqli));
  3. 如果你确实返回了json,你需要确保你的错误消息也是有效的json,所以第二个应该是真的(也适用于其他实例):
    or die(json_encode(mysqli_error($mysqli)));
  4. 一个潜在的问题是您没有在ajax调用中正确编码查询字符串。你可以让jQuery使用一个对象来处理它:
    var data = {'dia': dia, 'sala': sala, etc.};
  5. 修改:根据您的上次更新,您似乎没有取消默认的提交事件。您确实从您的函数返回false,但您没有对该值执行任何操作。

    你应该改变:

    <form method="post" id="salas" name="salas" onsubmit="postData()" >
    

    为:

    <form method="post" id="salas" name="salas" onsubmit="return postData();" >
    

    虽然,在使用jQuery时,更好的解决方案是删除内联javascript并将其移动到脚本部分:

    $('form').on('submit', function(event) {
      event.preventDefault();
    
      // the rest of your javascript that is now in your `postData()` function
    });