douge3492 2015-07-08 01:06
浏览 70
已采纳

如何通过AJAX将JSON发送到PHP?

I've tried over and over and it never works. I don't know how to receive the JSON on the server side.

JS

function newReport_compilation(){
 ...
 return JSON.stringify(formData);
}
var formData = newReport_compilation(); //takes all values from my form
...
$("#newReport_submit").on('click',function(){
ajaxRequestTwo("databaseButler.php?reqType="+2, "text", formData, function(returnedData){
console.log(returnedData); //To test
...
}}

function ajaxRequestTwo(reqScript, returnDataType, reqData, callback){
    $.ajax({
        type: "POST",
        dataType: returnDataType,
        url: reqScript,
        data: {fData:reqData},
        contentType: 'application/json; charset=UTF-8',
        success: function(data) {
            console.log("AJAX request success.");
            callback(data);
        },
        fail: function(){
            console.log("AJAX request failed.");
        },
        error: function(){
            console.log("Error!");
        }
    });
}

PHP (DatabaseButler.php)

function reportInsert(){
    def();
    //Establish a new connection
    $repInsCon = new Db();
    //Run the insertReport function from the DB class (Send it the report ID & the JSON data of the submitted form)
    $result = $repInsCon->insertReport($_POST['fData']);
    echo $result;
}
if(isset($_GET['reqType'])){
    ...
    }else if($_GET['reqType']=="2"){
        reportInsert();
    }
}

Deeper PHP (inside Db() class)

public function insertReport($jsonForm){
$newRepData = json_decode($jsonForm,true);
echo $jsonForm;
... //I have the SQL INSERT query part commented out here but I can't get here regardless
    }

It gives me an error saying Notice: Undefined index: fData in C:\wamp\www\HCSProjects\Pigeon\Main\databaseButler.php

I don't understand how you receive the JSON data on the PHP side? What is the JSON called once it reaches PHP? How do I receive it properly on the server side? :/

I've been looking into this for hours on end. There's no proper answer anywhere.

UPDATE
The AJAX request works fine because I get a 4 and a 200 on the response. The following line in the butler.php file is the problem: (I removed the reqType by the way.... i just made the url databaseButler.php with no additional parameters).

if(isset($_POST['req'])){

'req' in the above line is one my JSON values. I console.logged the JSON before I sent it to PHP. (My JSON is reqData. I console.logged formData which is the same thing)

{"id":"1615","na":"Y","ph":"905-525-9140","em":"h@mcmaster.ca","dep":"Residence Admissions","req":"PC Issues","cus":"","summ":"diwjdiwjdi","det":"","pri":"Low","dat":"07/08/2015","ti‌​m":"anytime"}

This is my newReport_compilation function by the way:

function newReport_compilation(){
    var formData = {id:hash(1),na:$("#newReport_name").val(),ph:$("#newReport_phone").val(),em:$("#newReport_email").val(),dep:$("#newReport_department").val(),req:$("#newReport_requestCategory").val(),cus:$("#newReport_otherRequest").val(),summ:$("#newReport_summary").val(),det:$("#newReport_details").val(),pri:$("input[type='radio'][name='priority']:checked").val(),dat:$("#newReport_date").val(),tim:$("#newReport_time").val()};
    return JSON.stringify(formData);
}

How do I get my JSON values on the PHP side? There's no help anywhere guys :/

UPDATE: FOUND A SOLUTION

For those interested:
The problem was the JSON.stringify(formData) in newReport compilation. Apparently you don't have to stringify formData if it was stored in JSON like form. It was like I tried to convert an already JSON string to JSON, which broke it.

Also, when you send data in both the URL and in JSON form, access everything using $_REQUEST and not $_POST or $_GET. However any JSON data you send over goes by the format you send the data. In my case I used POST. So to get ID or name or the server side (DatabaseButler PHP) you would use $_POST['id'] or $_POST['summ'].

  • 写回答

3条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 用Java实现双端队列
      • ¥150 ID3决策树实现分类
      • ¥20 二阶矩阵对角化和弹力平衡运动方程问题求解
      • ¥15 multisim10安装后,找不到NI License Manager的程序来安装许可证
      • ¥15 C++银行卡系统 Help!
      • ¥15 ubuntu 16.04.2 oss上传文件并显示耗时
      • ¥20 Kali破解WIFI密码中出现这个问题是什么意思
      • ¥15 R语言数据分析的相关问题
      • ¥15 模型导入SP后贴图纹理只有一个,拆了四张UV的,怎么解决?
      • ¥15 检索带order by 非常慢