2
$('#btnsave').click(function() {
    var id = $('.nameact').attr('data-id');
    var img = $('#imguser').attr('src');
    var uname = $('#inpuname').val();
    var pass = $('#inpass').val();
    var canpublic = $('#selcanpublic').val();
    var about = $('#txtabout').val();
    $.post('btn-save.php', {id, img, uname, pass, canpublic, about}, function(data) {
        console.log(data);
    });
});

It works fine but because inpuname, inpass, selcanpublic, txtabout are all elements of a form (forma) I wonder is it possible to serialize that data and add them to $.post data?

Something like this:

$('#btnsave').click(function() {
    var id = $('.nameact').attr('data-id');
    var img = $('#imguser').attr('src');
    $.post('btn-save.php', {id, img, $('#forma').serialize()}, function(data) {
        console.log(data);
    });
});
  • 1
    Your second example is not valid at all. `serialize()` produces a querystring. While it's possible to append that to the object you send through jQuery it will require a lot of amendment to your serverside code which is not really what you're trying to do. I would guess you require something more like [this](https://stackoverflow.com/questions/10398783/jquery-form-serialize-and-other-parameters/10398820#10398820) which appends other parameters to the serialised string. – Rory McCrossan Jun 18 '18 at 07:19

2 Answers2

0

$('form').serialize() generates a querystring with values. So when you serialize your form it will send the values as url parameters.

It would generate as

http://example.com?id=value&img=value&uname=value&pass=value&canpublic=value&about=value

So there is one way you can send

var formData = $('#forma').serialize()+'&id='+idvalue +'&img='+imgValue;

 $.post('btn-save.php', formData, function(data) {
        console.log(data);
    });

or you can serializeArray() to form. It will create key-value pair of form elements.

var formData = $('#myForm').serializeArray();
formData.push({name: 'id', value: idValue});
formData.push({name: 'img', value: imgValue});
Manoz
  • 6,507
  • 13
  • 68
  • 114
0

You can use FormData() object. It stores form values.

EDIT you can use FormData() only with option processData: false,

$('#btnsave').click(function () {
    var formData = new FormData($('#forma'));
    $.ajax({
        url: 'btn-save.php',
        data: formData,
        type: "POST",
        processData: false,
        success: function(data) {
            console.log(data);
        }
    });
});
Krzysztof Janiszewski
  • 3,763
  • 3
  • 18
  • 38