简体   繁体   中英

send JSON Object via POST or AJAX JQuery to PHP

I checked many answers for my question but none of them worked for me. I created an json object with a script that i found in stackoverflow , and works fine, but when i try to send it to php (i use laravel framework ) with $.post , the var_dump of object returns NULL .

In Network tab of Chrome Debug , the POST request has gone good but php can't get any data. I have already used POST Ajax in this project without problems except this.

How i can send my Object correctly to PHP?

There is a JQuery script that get form values and convert them in JSON Object:

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;
};

EDIT 2: this is the two method i'm using to resolve the problem:

$('#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'); });

2nd method without 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) ;
}) ;

})

The first function returns this JSON Object:

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

The second function returns:

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

With both JQuery functions, returns in PHP (with 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) "" }

This is my form:

<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 Method:

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

The code $(this).serializeObject() should serialize the content of this.......in your case this is a button.

try

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

so edit the JS too

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

Assuming you just want to send your form to a php page (for saving or wathever) without reloading the current page, i don't know why you need json.

I can give you a simple example below wich can do it, but maybe i didn't understand well what you want to do.

The JS part :

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) ;
                }) ;
            }) ;

The HTML part (not many changes)

<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>

And your php contact_process.php part :

<?php

    var_dump($_POST) ;

Another problem was born.

There is my JQuery function that get all form fields value and push them in array:

$(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;
});

});

it works really good (it send all of data):

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

but loading the page that i target $(this).prop('action') instead send back json response immediatelly via alert.

But, if i remove e.getPreventDefault(); the JQuery script returns error 500 with this response: {"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}} like if PHP can't get nothing......

This is my PHP function:

 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);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM