0

I am very new to jQuery/AJAX and I am looking for help. This is the relevant code-snippet:

$(function () {
    $('.button').on('click', function (event) {

        event.preventDefault(); //prevents page from refreshing

        $.ajax({
            type: 'POST',
            url: 'test2.php',
            data: ?????
            success: function (data) {
                alert('form was submitted');
                $('.text').html(data);
            }
        });
    });
});  

So, the data I want to pass is for one data: $('#form').serialize(), and for the other data: { test : test.name },
Basically I want to send a whole form and another parameter. How do I correctly express my wishes to jQuery?
I have tried the following options and they did not work:

$.ajax({
                type: 'POST',
                url: 'test2.php',
                data: $('#form').serialize(), data: { test : test.name },
                success: function (data) {
                    alert('form was submitted');
                    $('.text').html(data);
                }
            });  

and

$.ajax({
                type: 'POST',
                url: 'test2.php',
                data: $('#form').serialize(), { test : test.name },
                success: function (data) {
                    alert('form was submitted');
                    $('.text').html(data);
                }
            });  

and

$.ajax({
            type: 'POST',
            url: 'test2.php',
            data: $('#form').serialize()
        });
$.ajax({
            type: 'POST',
            url: 'test2.php',
            data: { test : test.name },
            success: function (data) {
                alert('form was submitted');
                $('.text').html(data);
            }
        });  

The php document basically just echos out said data.
Help a newbie out!

Denis
  • 5
  • 3

2 Answers2

0

Create an object to hold all your information:

var dataToSend = {};
dataToSend.form = $('#form').serialize();
dataToSend.extraData = { test : test.name };

then post it:

$.ajax({
    data: dataToSend
})
Stuart
  • 6,630
  • 2
  • 24
  • 40
  • interesting, I have never looked into objects until now. Thank you very much, I'll try it out – Denis Aug 23 '17 at 14:57
0

Try

data = {}
data["form"] = $('#form').serialize();
data["test"] = test.name;
$.ajax({
            type: 'POST',
            url: 'test2.php',
            data: data,
            success: function (data) {
                alert('form was submitted');
                $('.text').html(data);
            }
        });  

You need to supply a JSON object to the data property for your ajax. What I did was basically create a new object, and add 2 elements.

Hope this helps!

N. Ivanov
  • 1,795
  • 2
  • 15
  • 28