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条回答 默认 最新

  • du6jws6975 2015-07-08 01:20
    关注

    HTTP request can be POST or GET but not both and your code is trying to access variables through $_POST and $_GET, and that is not OK. I would suggest to use $_REQUEST instead and it will take care of it (if POST or GET). Despite of using type: "POST", jQuery will take it as a "GET" request because you are pointing to an URL with a querystring.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化