Create array with AJAX and send to another PHP page

Asked

Viewed 145 times

1

Is there any method of creating an array with AJAX to send the value of the selected input to another page where PHP will receive? there may be several input’s depending on the page, but page that will receive the values is unique for all

<div class="lista">
	<input type="checkbox" value="msc1_URL" checked>Musica 1</br>
	<input type="checkbox" value="msc2_URL">Musica 2</br>
	<input type="checkbox" value="msc3_URL">Musica 3</br>
	<!-- varias musicas aqui -->
</div>

2 answers

1

Jquery

$.post('paginaQueRecebeMusicas.php', $('#meu-form').serialize(), function(data){
    //callback - Executa algo apos finalizar o envio. Ex. limpar o form
)};

HTML

<form id="#meu-form">
     <!-- inputs -->
</form>
  • It would have how to do without the need for a form?

1


Using the method .map() with .get() you convert a collection of jQuery elements into a simple Javascript array:

var musicas = $(".lista input:checkbox:checked").map(function(){
   return this.value;
}).get();

console.log(musicas); // imprime ["msc1_URL", "msc3_URL"]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lista">
	<input type="checkbox" value="msc1_URL" checked>Musica 1</br>
	<input type="checkbox" value="msc2_URL">Musica 2</br>
	<input type="checkbox" value="msc3_URL" checked>Musica 3</br>
</div>

In this case you can send it to PHP via Ajax using the array stored in the variable musicas as data to be sent:

$.post('pagina.php', { musicas: musicas }, function(data){
    // trata o retorno, se quiser
});

Browser other questions tagged

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