when using AJAX, can I send content without being around the form tag?

2

you should put inputs , etc within <form id="algo" method="POST"></form> ?

<form id="algo" method="POST">
    <input type="text" value="NADA" name="valor1" />
    <input type="text" value="TUDO" name="valor2" />
</form>

Or I can send via ajax like this:

    <input type="text" value="NADA" name="valor1" />
    <input type="text" value="TUDO" name="valor2" />

Ajax:

$.ajax({
    url: "algumaurl.php",
    type: "POST",
    data: {
        valor1: $("[name='valor1']").val(),
        valor2: $("[name='valor2']").val(),
    },
    success: function(data){
        //faz algo
    }
});
    
asked by anonymous 25.09.2015 / 16:02

1 answer

1

You can send AJAX as you think best. What's important is the data you pass and how you start AJAX.

The data you put here:

data: {
    valor1: $("[name='valor1']").val(),
    valor2: $("[name='valor2']").val(),
},

So, how you did it is correct.

If you want to use the submit event of a <form> , fine, but you may want to start an AJAX call in another way. It's irrelevant. The <form> does not have to be present to use AJAX, it makes sense when you want to send a form to the server without AJAX, and is only useful for grouping data as in

data: $(form).serialize()
    
25.09.2015 / 16:04