通过POST或AJAX JQuery将JSON对象发送到PHP

时间:2015-04-09 11:28:33

标签: php jquery ajax json laravel-4

我为我的问题检查了许多答案,但没有一个能为我工作。 我在json中创建了script stackoverflowphp对象,但工作正常,但当我尝试将其发送到$.post时(我使用 < em> laravel框架 )与var_dump,对象returns NULL的{​​{1}}。

在Chrome调试的网络标签中,POST request已经很好,但php无法获取任何数据。 我已经在这个项目中使用了POST Ajax而没有问题,除了这个。

如何将我的对象正确发送到PHP?

有一个JQuery脚本可以获取表单值并在JSON对象中转换它们:

jQuery.fn.serializeObject = function() {
    var arrayData, objectData;
    arrayData = this.serializeArray();
    objectData = {};

    $.each(arrayData, function() {
        var value;

        if (this.value !== '') {
            value = this.value;

            if (objectData[this.name] != null) {
                if (!objectData[this.name].push) {
                    objectData[this.name] = [objectData[this.name]];
                }

                objectData[this.name].push(value);
            } else {
                objectData[this.name] = value;
            }
        }
    });

    return objectData;
};

编辑2:这是我用来解决问题的两种方法:

$('#details_form').on('submit',function(e){

e.preventDefault();
var json_enc = JSON.stringify($('#details_form').serializeObject());

$.post(
        $("#details_form").prop('action'), 
        { 'json_enc' : json_enc }, 
        function(data) 
        { alert(data.msg) }, 'json'); });

没有JSON的第二种方法:

$('#save').on('click',function(e) {

var form = $(this).closest('form') ;
e.preventDefault();

var result = form.serialize();

var ajax = $.post(
    form.data('action'),        {
        'data': result
    },
    function(data) {
        alert(data);
    }
);

ajax.fail(function(data){
    alert('fail (see console for details)') ;
    console.log(data) ;
}) ;

})

第一个函数返回此JSON对象:

{
    "_token": "HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3",
    "id": "contact_1",
    "name": "John",
    "surname": "Wayne",
    "address": "2nd street",
    "contact": ["656346843", "56196856"]
}

第二个函数返回:

_token=HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3&id=contact_1&name=Gino&surname=Megna&address=kjwebgflk+645&contact=656346843&contact=6548198189&contact=

使用两个JQuery函数,返回PHP(使用var_dump($ _ POST)):

array(6) { ["_token"]=> string(40) "HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3" ["id"]=> string(9) "contact_1" ["name"]=> string(4) "Gino" ["surname"]=> string(5) "Megna" ["address"]=> string(13) "kjwebgflk 645" ["contact"]=> string(0) "" }

这是我的表格:

<form method="POST" action="http://localhost/rubrica/public/contact_process" accept-charset="UTF-8" class="form-bootstrap" id="details_form" autocomplete="off">
<input name="_token" type="hidden" value="HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3">
<input id="contact_id" name="id" type="hidden" value="contact_1">
<div class="bg_contact">
    <div class="image_contact">
        <label for="immagine" id="" class="">Add Image</label>
        <input name="image" type="file" id="immagine"> </div>
    <div class="rif_contact">
        <div class="name_contact">
            <input placeholder="Name" id="name" name="name" type="text" value="John"> </div>
        <div class="surname_contact">
            <input placeholder="Surname" id="surname" name="surname" type="text" value="Wayne"> </div>
    </div>
</div>
<div class="address">
    <div class="label_address">
        <label for="address">Address</label>
    </div>
    <input placeholder="Address" id="address" name="address" type="text" value="2nd street"> </div>
<div class="bg_details">
    <label for="contacts">Contacts</label>
    <div class="content_detail">
        <input type="text" name="contact" class="contact_details" placeholder="Telephone" value="656346843" id="detail_161">
        <button onclick="delete_detail_exist(this,161)" id="remScnt" type="button">Remove</button>
    </div>
    <div class="content_detail">
        <input type="text" name="contact" class="contact_details" placeholder="Telephone" value="56196856" id="detail_160">
        <button onclick="delete_detail_exist(this,160)" id="remScnt" type="button">Rimuovi</button>
    </div>
    <div class="content_detail">
        <input placeholder="Telephone" class="contact_details" id="p_scnt" name="contact" type="text">
        <button id="addScnt" onclick="add_detail_field(this)" type="button">Add</button>
    </div>
</div>
<input id="save" type="submit" value="Save"> </form>

PHP方法:

public function contact_process() {
    $result = trim (Input::get('result'));
    $json = json_decode($result);
    var_dump($json);
}

3 个答案:

答案 0 :(得分:1)

代码$(this).serializeObject()应序列化此内容.......在您的情况下是一个按钮。

尝试

var json_enc = JSON.stringify($('#details_form').serializeObject());

所以也要编辑JS

$.post(
             $("#details_form").prop('action'), 
             { 'result': json_enc }, 
             function(data) 
             { alert(data.msg) }, 'json');

答案 1 :(得分:0)

假设您只想将表单发送到php页面(用于保存或监视器)而不重新加载当前页面,我不知道您为什么需要json。

我可以在下面给你一个简单的例子,但也许我不太了解你想做什么。

JS部分:

jQuery(document).on('click','#save',function(e) {

                var form = jQuery(this).closest('form') ;
                e.preventDefault() ;

                var ajax = $.post(
                    form.data('action'),
                    form.serialize(),
                    function(data) { alert(data) ; }
                );

                ajax.fail(function(data){
                    alert('fail (see console for details)') ;
                    console.log(data) ;
                }) ;
            }) ;

HTML部分(没有太多变化)

<form method="POST" action="#" data-action="./contact_process.php" accept-charset="UTF-8" class="form-bootstrap" id="details_form" autocomplete="off">
            <input name="_token" type="hidden" value="HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3">
            <input id="contact_id" name="id" type="hidden" value="contact_1">
            <div class="bg_contact">
                <div class="rif_contact">
                    <div class="name_contact">
                        <input placeholder="Name" id="name" name="name" type="text" value="John"> </div>
                    <div class="surname_contact">
                        <input placeholder="Surname" id="surname" name="surname" type="text" value="Wayne"> </div>
                </div>
            </div>
            <div class="address">
                <div class="label_address">
                    <label for="address">Address</label>
                </div>
                <input placeholder="Address" id="address" name="address" type="text" value="2nd street"> </div>
            <div class="bg_details">
                <label for="contacts">Contacts</label>
                <div class="content_detail">
                    <input type="text" name="contact" class="contact_details" placeholder="Telephone" value="656346843" id="detail_161">
                    <button onclick="delete_detail_exist(this,161)" id="remScnt" type="button">Remove</button>
                </div>
                <div class="content_detail">
                    <input type="text" name="contact" class="contact_details" placeholder="Telephone" value="56196856" id="detail_160">
                    <button onclick="delete_detail_exist(this,160)" id="remScnt" type="button">Rimuovi</button>
                </div>
                <div class="content_detail">
                    <input placeholder="Telephone" class="contact_details" id="p_scnt" name="contact" type="text">
                    <button id="addScnt" onclick="add_detail_field(this)" type="button">Add</button>
                </div>
            </div>
            <input id="save" type="button" value="Save">
        </form>

你的php contact_process.php部分:

<?php

    var_dump($_POST) ;

答案 2 :(得分:0)

又出现了另一个问题。

我的JQuery函数可以获取所有表单字段值并将它们推送到数组中:

$(document).ready(function() {
        $('#details_form').submit(function(e){
    e.getPreventDefault();
    var result = $(this).serializeObject();
    $.post($(this).prop('action'),{
                'data': result
            },
            function(data){
                alert(data.msg);
            },
        'json'
    );
    return false;
});

});

它的效果非常好(它发送所有数据):

{"_token":"w35HLqCZi61ki9QOlu6MFwWxYNbBoiEJkcQ58G2b","id":"contact_1","name":"t","surname":"fg","address":"iiiiiiiiiiiiiiiiiiiii","contact[]":["16151515","2325556"]}

但加载我定位$(this).prop('action')的网页,而不是立即通过提醒发回json响应。

但是,如果我删除e.getPreventDefault();,JQuery脚本会返回错误500并返回错误:{"error":{"type":"ErrorException","message":"array_filter() expects parameter 1 to be array, null given","file":"C:\\xampp\\htdocs\\rubrica\\app\\controllers\\ContactController.php","line":145}}就好像PHP无法获得任何内容......

这是我的PHP函数:

 public function contact_process() {
        $contact_id = trim(Input::get('id'));
        $contact_name = trim(Input::get('name'));
        $contact_surname = trim(Input::get('surname'));
        $contact_address = trim(Input::get('address'));
        $telephones = array_filter(Input::get('contact'));
if ($contact_id !== '' &&  $contact_name !== '' && $contact_surname !== '' && $contact_address !== '' && $telephones !== '') {

        if ($contact_id == 'new') {

            $new_contact = new Contact;
            $new_contact->name = $contact_name;
            $new_contact->surname = $contact_surname;
            $new_contact->address = $contact_address;
            $new_contact->save();
            $LastInsertId = $new_contact->id;

            foreach ($telephones as $value) {
                $new_detail = new Detail;
                $new_detail->telephone = $value;
                $new_detail->contact_id = $LastInsertId;
                $new_detail->save();
            }

            $response = array(
                'status' => 'success',
                'msg' => 'Nuovo contatto aggiunto'
            );

            return Response::json($response);

        } else {

            list($tmp, $id_temp) = explode("_", $contact_id);

            $get_contact = Contact::find($id_temp)->first();

            if ($get_contact) {

                $get_contact->name = $contact_name;
                $get_contact->surname = $contact_surname;
                $get_contact->address = $contact_address;
                $get_contact->save();

                $delete_details = Detail::where('contact_id', '=', $id_temp)->delete();

                foreach ($telephones as $value) {
                    $new_detail = new Detail;
                    $new_detail->telephone = $value;
                    $new_detail->contact_id = $id_temp;
                    $new_detail->save();
                }

                $response = array(
                        'status' => 'success',
                        'msg' => 'Contatto aggiornato'
                );

                return Response::json($response);

            }
        }
}
        $response = array(
                'status' => 'error',
                'msg' => 'Compila tutti i campi ed inserisci almeno un numero di telefono'
        );

        return Response::json($response);

    }