将表单转换为Ajax以将PHP插入到SQL中 [英] Form to Ajax to PHP for Insert into SQL

查看:143
本文介绍了将表单转换为Ajax以将PHP插入到SQL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经非常努力地获得这个功能的简单工作模型。我的实际网站规模较大,但是我忽略了脚本,使事情变得简单(并排除故障)。



当我点击发送时,我一直收到500错误通过表单,我一直无法弄清楚我做错了什么。
(我建立了一个简单的数据库来捕获这个项目)。

(这个PHP文件被命名为sample2.php目录为html。)



我的数据库的屏幕截图:



我的HTML文件:

 < html> 
< head>
< meta charset =utf-8>
< script src =// ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js\"> ;</script>
< / head>
< body>
< div name =maindivid =maindiv>
< span> sample1:< / span> < input id =sample1name =sample1width =300pxtype =textvalue =sample1text/>< br />>
< / div>

< input type =buttonname =senditvalue =Do itid =sendit/>

< script language =javascripttype =text / javascript> ()
$(document).ready(function(){

$(#sendit)。 ;

$('#maindiv input')。each(function(){
fieldvalue.push([this.id,$(this).val()]);



console.log(fieldvalue);

$ .ajax({
url:sample2.php,
type :POST,
dataType:json,
data:JSON.stringify(fieldvalue),
success:function(){$ b $ alert(working);
}
});
});
});
< / script>
< / body>
< / html>

和我的PHP文件:

 < ;? 
$ pdo = new PDO(mysql:dbname = trialdb; host = extoleducation.ipagemysql.com,username,password);

$ id = $ _POST ['sample1'];

$ query-> bindValue(':sample1',$ sample1,PDO :: PARAM_STR);
$ sql =INSERT INTO sampletable(sampleline)VALUES(:sample1);;

$ query = $ pdo-> prepare($ sql);

if($ statment = $ pdo-> prepare($ sql)){
$ statment-> execute();
$ statment-> closeCursor();
exit();
}
?>


解决方案

你的PHP似乎混淆了。为简单起见,试试这样做:

 <?php 
$ pdo = new PDO(mysql:host = extoleducation.ipagemysql.com; DBNAME = trialdb, 用户名, 口令); (sample1));

if(isset($ _ POST ['sample1'])){
$ sql =INSERT INTO`sampletable`(`sampleline`)VALUES(:sample1);
$ query = $ pdo-> prepare($ sql);
#我发现绑定值更容易,只需将数组放入执行
#如果你得到它的工作,并真的想回去尝试
#bindValue(),你可以
$ query-> execute(array(':sample1'=> $ _ POST ['sample1']));
}

这是最基本的。如果你能做到这一点,那么你就可以从中解脱出来。如果你愿意 try / catch PDOException 想要排除任何不可预见的sql错误。



对于测试用途,我会试图不发送json,这样您可以更轻松地从 console.log()

  $(document).ready(function ){
$(#sendit)。on(click,function(){
//如果你没有序列化,我会做一个对象,而不是数组
var fieldvalue = {action:submit};
//循环并保存名称和值
$('#maindiv input')。each(function(k,v){
fieldvalue [$(v).attr('name')] = $(v).val();
});

$ .ajax({
url: sample2.php,
类型:POST,
//尝试在这里发送对象而不是json字符串
data:fieldvalue,
//在成功时添加回应,所以你可以看到
//你从页面返回的内容
success:function(response){
//检查你是否得到任何错误
console.log(response);
//这个值最小,因为它只告诉你
// ajax工作。它不会告诉你任何来自页面
alert(working)的
//响应;
}
});
});
});


I have tried very hard to get a simple working model of this to function. My actual Site is larger, but I've dumbed down the scripting to make things simple (and troubleshoot).

I keep getting "500" errors when I click to send the Form through, and I've been unable to figure out what I've been doing wrong. (I've set up a simple database to capture just this one item).

(The PHP file is named "sample2.php" within the same directory as html is in.)

A screenshot of my database:

My HTML File:

<html>
    <head>
        <meta charset="utf-8">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    </head>
    <body>
        <div name="maindiv" id="maindiv">
            <span>sample1:</span> <input id="sample1" name="sample1" width="300px" type="text" value="sample1text" /><br />
        </div>

        <input type="button" name="sendit" value="Do it" id="sendit"/> 

        <script language="javascript" type="text/javascript">
        $(document).ready(function(){

            $("#sendit").on("click", function() {
                var fieldvalue = [];

                $('#maindiv input').each(function() { 
                    fieldvalue.push([this.id, $(this).val()]); 
                });

                console.log(fieldvalue);

                $.ajax({
                    url: "sample2.php",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify(fieldvalue),
                    success: function() {
                        alert("worked");
                    }
                });
            });     
        });
        </script>
    </body>
</html>

and my PHP file:

<?
    $pdo = new PDO("mysql:dbname=trialdb;host=extoleducation.ipagemysql.com","username","password");

    $id = $_POST['sample1'];

    $query->bindValue(':sample1', $sample1, PDO::PARAM_STR);
    $sql = "INSERT INTO sampletable (sampleline) VALUES (:sample1);";

    $query = $pdo->prepare($sql);

    if($statment = $pdo->prepare($sql)) {
        $statment->execute();
        $statment->closeCursor();
        exit();
    }
?>

解决方案

Your PHP seems to be mixed up. For simplicity, try just doing this:

<?php
$pdo = new PDO("mysql:host=extoleducation.ipagemysql.com;dbname=trialdb","username","password");

if(isset($_POST['sample1'])) {
    $sql = "INSERT INTO `sampletable` (`sampleline`) VALUES (:sample1)";
    $query = $pdo->prepare($sql);
    # I find binding values much easier just doing the array into the execute
    # If you get it working like this and really want to go back and try
    # bindValue(), you can
    $query->execute(array(':sample1'=>$_POST['sample1']));
}

This is as basic as it gets. If you can get this to work, then you just kind of build off of it. You may want to try/catch PDOExceptions if you want to troubleshoot any unforeseen sql errors.

For testing pursposes, I would be tempted to not send json, that way you can more-easily troubleshoot your php from the console.log():

$(document).ready(function(){
    $("#sendit").on("click", function() {
        // If you are not serializing, I would do an object, not array
        var fieldvalue = {"action":"submit"};
        // Loop through and save names and values
        $('#maindiv input').each(function(k,v) { 
            fieldvalue[$(v).attr('name')] = $(v).val();
        });

        $.ajax({
            url: "sample2.php",
            type: "POST",
            // Try just sending object here instead of json string
            data: fieldvalue,
            // On the success, add the response so you can see
            // what you get back from the page
            success: function(response) {
                // Do a check to see if you get any errors back
                console.log(response);
                // This has minimal value because it is only telling you
                // that the ajax worked. It's not telling you anything from the
                // response of the page
                alert("worked");
            }
        });
    });     
});

这篇关于将表单转换为Ajax以将PHP插入到SQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆