When using AJAX, can I upload content without being around the form tag?

Asked

Viewed 61 times

2

should be placed the inputs, etc within a <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" />

The ajax:

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

1 answer

1

You can send AJAX as it suits you best. What is 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 right.

If you want to use the event submit of a <form> all right, but you might want to start an AJAX call 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.