.ajaxForm将数据传递到php

.ajaxForm passing data to php

本文关键字:php 数据 ajaxForm      更新时间:2023-09-26

我很难使用ajaxForm将数据传递到我的PHP文件中,以便插入MySQL数据库。

下面是JavaScript函数,它目前在表单提交过程中显示进度条,问题是姓名、电话和电子邮件的"帖子"不起作用,但附件上传起作用。

$(function() {
    var name = document.getElementById("name").value;
    var phone = document.getElementById("phone").value;
    var email = document.getElementById("email").value;
    var percent = $('.percent');
    var bar = $('.bar');
    $('form').ajaxForm({
        dataType:  'json',
        data : {
                name:name,
                phone:phone,
                email:email
                },
        beforeSend: function() {
            document.getElementById("bar").style.backgroundColor="rgb(51,166,212)";
            bar.width('0%');
            percent.html('0%');
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var pVel = percentComplete + '%';
            bar.width(pVel);
            percent.html(pVel);
        },
        complete: function(data) {
            document.getElementById("bar").style.backgroundColor="rgb(185,221,111)";
            percent.html("Done!");
            setTimeout(function(){
                modal.style.display = 'none';
                location.reload(); 
            }, 2000);
        }
    });
});

以下是要将值传递到的PHP文件中的代码。

<?php
include("sql_connection.php");
  $name = $_POST['name'];
  $phone = $_POST['phone'];
   $email = $_POST['email'];
$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ($name, $phone, $email)";
mysqli_query( $conn, $sql);
$dir = 'uploads/';
$count = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
foreach ( $_FILES['files']['name'] as $i => $name )
{
    if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
        continue;
    if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
        $count++;
}
}
  echo json_encode(array('count' => $count));
?>

有什么建议吗?

感谢

将SQL查询更改为:

$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ('".$name."', '".$phone."', '".$email."')";

否则,您需要在启动数据库连接的顶部更改include。

正如我在你的评论中所读到的,问题是输入可能不包含任何值。您何时启动Ajax请求?提交或页面加载后?

也许你可以在他应该获取信息的地方添加代码?

$.ajax 中缺少类型参数

$('form').ajaxForm({
    type: 'POST',
    dataType:  'json',
    data : {'name':name,'phone':phone,'email':email},
......................................

感谢您的帮助,SQL查询实际上是错误的,但我还需要为每个变量使用一个函数,以便在发布之前返回其当前状态。

感谢

    $('form').ajaxForm({
        type: 'POST',
        dataType:  'json',
        data : {
                name:function () {
                        return name = document.getElementById("name").value;
                    },
                phone:function () {
                        return phone = document.getElementById("phone").value;
                    },
                email:function () {
                        return email = document.getElementById("email").value;
                    }
                },