简体   繁体   中英

send json into php using jquery

I have a JSON from a PHP file and I want to send that output to another PHP file. This is my JavaScript:

var data_1;
$.ajax({
  type:"POST",
  url:"sd.php",
  success:function(result){
        data_1 = result;
        test(data_1);
        var st = JSON.stringify(data_1);
        $.post('get.php',{q:st},function(data){
            window.location = "get.php";
        });
  }
});

And my PHP file to store the JSON:

<?php 
     $obj = json_decode($_POST['q']);
     echo $obj;
 ?>

But it outputs nothing. What should I do? Please help.

$.ajax({
url: 'sd.php',
type: 'POST',
data: JSON.stringify(data_1), // data_1 is a javascript object here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(returned_data) {
    alert(returned_data);
}
});

You may try this i wrote for you, but its not tested

/**
 * Created by vladimirnikolic on 3/24/14.
 */
$('#submit').click(function(e){
    e.preventDefault();

            var form_data = $('#your_form').serializeArray();

            var submit_data = serializedFormToDTO(form_data);
            $.ajax({
                url: 'sd.php',
                type: 'POST',
                dataType: 'json',
                data: submit_data
            })
            .done(function(xhr) {
                $.post("get.php", {
                        q: submit_data
                    },
                    function (data) {
                        // handle data here
                        // console.log(data);
                    }, 'json');
                }
            )
            .fail(function(xhr) {
                var response_text = $.parseJSON(xhr.responseText)
                console.log(response_text);

            })
});
function serializedFormToDTO (data, json) {
    json = (typeof json !== 'undefined') ? json : false;
    if ((json !== true) && (json !== false) ) {
        console.log('invalid value of second parameter (should be true/false for json output)');
        return false;
    }

    var result = {};
    for (var i = data.length - 1; i >= 0; i--) {
        result[data[i].name] = data[i].value;
    }
    if (json === true) {
        result = JSON.stringify(result);
    }

    return result;
}

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