doujiyan0971 2013-09-03 01:13
浏览 83
已采纳

通过AJAX将JSON数据发送到数据库

I'm having trouble sending a JSON array with AJAX to a PHP file which inserts the information in the correct columns in the database. The jquery and Json works fine, but it seems like the PHP side doesn't get the values correct, or maybe the json isn't encoded correct.

Any ideas how I can fix this?

JSON:

{
"Email": [
    {
        "Name": "My Name",
        "Phone": "1234567",
        "Email": "my@mail.com",
        "Interested_in": "Text text.",
        "User_id": "1"
    }
]
}

PHP:

$timeStamp = time();

$new_email = $_POST['NewMail'];

$email_info = $new_email->Email;

// New Email
mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info->User_id)."', '".safeSQL($email_info->Name)."','".safeSQL($email_info->Phone)."', '".safeSQL($email_info->Email)."', '".safeSQL($email_info->Interested_in)."', '0', '1')") or die("Query failed: " . mysql_error());

UPDATE:

Jquery for sending to PHP

    $( document ).on('click', '#send_touch', function(){

    new_email = [];

    new_email.push({
    Name: $('#name').val(),
    Phone: $('#phone').val(),
    Email: $('#email').val(),
    Interested_in: $('#interested_in').val(),
    User_id: $('#email_user_id').val()
    });

    new_email = JSON.stringify({Email: new_email}, null, "\t");

        $.ajax({
            url: "core.php",
            type: "post",
            data: { NewMail: new_email
                  },
            success: function(data){  

            },
            error: function(){
            }   
     });    

});

Also tried to change PHP to this:

$timeStamp = time();

$new_email = json_decode($_POST['NewMail']);

$email_info = $new_email->Email[0];

// New Hashtag
mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info->User_id)."', '".safeSQL($email_info->Name)."','".safeSQL($email_info->Phone)."', '".safeSQL($email_info->Email)."', '".safeSQL($email_info->Interested_in)."', '0', '1')") or die("Query failed: " . mysql_error());
  • 写回答

1条回答 默认 最新

  • dqssst0144 2013-09-03 01:16
    关注

    I believe you are missing the decode on the php side:

    $new_email = json_decode($_POST['NewMail']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵