Send Javascript array via Ajax with jQuery for PHP file

Asked

Viewed 5,322 times

0

I want to send an array via jQuery using Ajax to another PHP file, but I don’t know how to access it in PHP.
I’m sending by GET I don’t know if that would be ideal either.

nome_receita is a variable and ingredientes is the array I need to "open" in PHP.

$.get("http://localhost/estudos/oquetemprahj/servidor.php?nome_receita="+nome_receita+"&&ingredientes="+ingredientes+"",function(retorno)
{
	alert(retorno);
});

  • Use console.log(return); and see the output in the browser console, to capture in php will depend on the type of request, in your case vc is using $.get(), get is captured by $_GET['nome_receita']. if you want to display the return, you need to give an "echo" on what was sent.

  • The ideal is that you use the POST method, and have this return in json. The get method is recommended for relatively fast requests, and they need to preserve variables in the url.

  • You can’t send a javascript array via get, it doesn’t work that way, you have to convert that array before sending, using serialize / unserialize, or send the json object structure via POST. Or convert this variable into a string: JSON.stringify(ingredientes)

4 answers

1

Just add [] after the variable name. Example:

$.get("http://localhost/estudos/oquetemprahj/servidor.php?nome_receita="+nome_receita+"&ingredientes[]=item1&ingredientes[]=item2&ingredientes[]=item3",function(retorno)
{
    alert(retorno);
});

Just replace item with key value. In PHP it will arrive as Array, you can do the test:

print_r($_REQUEST["ingredientes"]);

If it is a checkbox, for example, you can do the following:

<input type="checkbox" value="ingrediente_x" name="ingredientes[]">
<input type="checkbox" value="ingrediente_y" name="ingredientes[]">
<input type="checkbox" value="ingrediente_z" name="ingredientes[]">

0

I believe that for this type of scenario a POST be more appropriate, in this case try to do the following.:

var data = {
    nome_receita: nome_receita, 
    ingredientes: ingredientes
};

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://localhost/estudos/oquetemprahj/servidor.php", true);
httpRequest.responseType = "json";
httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpRequest.send(JSON.stringify(data));

if you want to test the shipment by GET, just replace the POST for GET in the open(...).

with jQuery you can try the following:

var data = {
    nome_receita: nome_receita, 
    ingredientes: ingredientes
};

$.get("http://localhost/estudos/oquetemprahj/servidor.php", data, function(retorno)
{
    alert(retorno);
});
  • I understood, but how would access this information in PHP?

  • @Eliezerb. to your doubt is how to send the data and not how PHP will receive and respond to the request.

0

In the PHP script that will receive the data, just access it using $_GET, or $_POST, if the method is post. So it would look something like this:

<?php
    $nome_receita = $_GET['nome_receita'];
    $ingredientes = json_decode($_GET['ingredientes']);
?>

I believe that as ingredients if it is an array, you have to use PHP’s json_decode() function.

It is also important to note that you used the & twice for the ingredient variable, in passing the URL.

0

I think you can use jQuery’s $.ajax function, but first you need to turn your array into a JSON string. A good way is to use JSON.stringify. Link to JSON.stringify documentation()

Code to make ajax call:

$.ajax({
  url: 'http://localhost/estudos/oquetemprahj/servidor.php',
  type: 'GET', // Tipo de requisição, podendo alterar para GET, POST, PUT , DELETE e outros metodos http
  data: {nomeReceita: nome_receita, ingredientes: ingredientes},
  success: function(resposta){
     //Bloco com a resposta do servidor caso a requisição ocorra normalmente
  },
  error: function(resposta){
    //Entrará aqui caso não de certo a requisição 
  }
})

Already in your php you will have to take this data and pass it from JSON string to object.

<?php

$nome_receita = $_GET['nome_receita'];
$ingredientes = json_decode($_GET['ingredientes']);

Browser other questions tagged

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