开发者

Send multiple pieces of data through .ajax() for processing in PHP script

开发者 https://www.devze.com 2023-03-10 07:33 出处:网络
I\'m trying to send two separate groups of information through .ajax() to a PHP script for processing and running into problems.

I'm trying to send two separate groups of information through .ajax() to a PHP script for processing and running into problems.

In this scenario, the user enters a page and 1) a timer starts counting seconds and 2) the user has to fill out a series of inputs for a form. I'd like to send both groups of information (the current timer count and all the user inputs) to a PHP script when the user clicks a submit button.

I've can successfully send either one group of info OR the other but can't figure out a way to send both groups of data simultaneously through .ajax() at the same time.

Here is the jQuery I've got now, which attempts to send both pieces of data but fails:

 $(document).ready(function(){
    var count = 0;
    setInterval(function(){
        count++;
        $('#timer').html(count + ' secs.');
    },1000);

// displays user structureand suggested answers on structure page
$('#process_structure').click(function () {
    var text = $.ajax ({
        type: "POST",
        url: "structure_process.php",
        data: $('#inputs_structure').serialize(), data: {count: count},
        da开发者_StackOverflow社区taType: "json",
        async: false,
    }).responseText;
    $('#test_ajax').html(text); 
})
});

Any pointers would be greatly appreciated. Thanks!


Assuming structure_process.php accepts both pieces of data together, you can use serializeArray() instead of serialize(), append your extra piece of data, and then use jQuery.param() to convert the array to a string that jQuery.ajax() will accept.

$('#process_structure').click(function () {
    var postData = $('#inputs_structure').serializeArray();
    postData.push({name: 'count', value: count});
    var text = $.ajax ({
        type: "POST",
        url: "structure_process.php",
        data: $.param(postData),
        dataType: "json",
        async: false,
    }).responseText;
    $('#test_ajax').html(text);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消