简体   繁体   English

使用Ajax无法在SQL中插入数据

[英]Insert data in sql with ajax not working

I'm trying to insert data in a sql table using ajax and php, but it's not working. 我正在尝试使用ajax和php在sql表中插入数据,但是它不起作用。 My ajax give me the result like it works, but when i look at the table, there's not in it. 我的ajax给我的结果像它一样有效,但是当我看桌子时,里面没有。 Doing it without ajax works fine, so i guess my php is working ok. 不用ajax就能正常工作,所以我想我的php可以正常工作。

Here's the code: 这是代码:

HTML: HTML:

<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
    Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
    Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>

    <input type="submit" value="Enviar"/>
</form>

PHP: PHP:

    $passo = (isset($_GET['p'])) ? $_GET['p'] : "";


    switch($passo){

        case "cadUsr":
            cadUsr();
        break;

        default:
            getRetorno();
        break;
    }

    function getRetorno(){
        echo "Este texto foi escrito via PHP";
    }

    function cadUsr(){
    require("dbCon.php");
    require("mdl_usuario.php");

        $usr = $_POST["txtNome"];
        $idade = $_POST["txtIdade"];

        $resultado = usuario_cadastrar($con,$usr,$idade);

            if($resultado){
                echo "Cadastro efetuado com sucesso";
            } else {
                echo "O cadastro falhou";
            }
    }
?>

OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php. OBS:我需要将带有url参数的表单动作作为cadUsr传递,因此它在php中调用该函数。

AJAX: AJAX:

window.onload = function(){

        var xmlhttp;
        var frm = document.querySelector("#frmCadUsr");
        var url = frm.getAttribute("action");
        var nm = document.querySelector("#txtNome").value;
        var idade = document.querySelector("#txtIdade").value;

        frm.addEventListener("submit",function(e){
            e.preventDefault();

            try{
                if(window.XMLHttpRequest){
                    xmlhttp = new XMLHttpRequest();
                }

                xmlhttp.open("POST",url,true);
                xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");

                xmlhttp.onreadystatechange = function(){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        //alert("Deu certo");
                        console.log(xmlhttp.responseText);
                    }
                }
            } catch(err){
                alert("Ocorreu um erro.<br />"+ err);
            }
        });

} }

The PHP function to insert the data: PHP函数插入数据:

function usuario_cadastrar($conexao,$nome,$idade){


        if($nome == "" && $idade == ""){
            return false;
        }





        $sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);

        $resultado = mysqli_query($conexao,$sql);

            return $resultado;
    }

I think the problem is here servico.php?p=cadUsr . 我认为问题出在这里servico.php?p=cadUsr You copy the action -attribute from the form with a querystring. 您使用查询字符串从表单复制action属性。 If you cut the querystring from it, I think it will work. 如果您从中删除查询字符串,我认为它将起作用。

The main problem is being called by Hossein: 侯赛因称其为主要问题:

This : 这个 :

$passo = (isset($_GET['p'])) ? $_GET['p'] : "";

Will not work. 不管用。 You're doing a post, you can't get GET variables. 您正在发布帖子,无法获取GET变量。

You call value on value which will result in undefined and that will put no data in your database. 您按value调用value ,这将导致undefined并且不会在数据库中放置任何数据。

 xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");

So remove value and add the cadUsr variable to the querystring in the send function. 因此,删除value并将cadUsr变量添加到send函数中的querystring中。 Update PHP to: 将PHP更新为:

$passo = (isset($_POST['p'])) ? $_POST['p'] : "";

And it will work! 它将起作用!

You can see your callback codes by adding console.log(xmlhttp.responseText); 您可以通过添加console.log(xmlhttp.responseText);查看回调代码console.log(xmlhttp.responseText); to your readystate success function. 准备状态成功功能。

Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post. 另外,发送帖子时,您需要将requestheader content-type为x-www-form-urlencoded。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM