Pagina 1 din 1

Array asociativ cu date de formular trimis prin ajax

Scris: Lun Feb 01, 2016
de andras
Salut,
Intr-un formular am un array asociativ constituit din variabilele POST (id element=>valoare variabila POST). Care este cea mai eficienta modalitate de a-l transmite prin ajax catre fisierul PHP apelat cu ajax (adica model in MVC)?

Array asociativ cu date de formular trimis prin ajax

Scris: Lun Feb 01, 2016
de MarPlo
Salut
In JavaScript array-ul asociativ e de fapt obiect, creat cu: {prop:val,}.
Eu folosesc aceasta functie ajaxSend(), cum e in exemplu de dupa ea.

Cod: Selectaţi tot

<script>
/* Ajax Function
 Send "data" to "php", using the method added to "via", and pass response to "callback" function
 data - json object with data to send, name:value; ex.: {"name1":"val1", "name2":"2"}
 php - address of the php file where data is send
 via - request method, a string: 'post', or 'get'
 callback - function called to proccess the server response
*/
function ajaxSend(url, data, via, callback){
  var obajx =  (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');  // XMLHttpRequest object

  //put data from "data" into a string to be send to "php"
  var str_data ='';
  for(var k in data){
    k = k.toString();  //convert numeric key to string

    //build the string with data to be sent
    str_data += k +'='+ data[k].toString().replace(/\?/g, '%3F').replace(/=/g, '%3D').replace(/&/g, '%26').replace(/[ ]+/g, '%20').replace(/[\+]/g, '%2B') +'&';
  }
  str_data = str_data.replace(/&$/, '');  //delete ending &

  //send data to php
  obajx.open(via, url, true);
  if(via =='post') obajx.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  obajx.send(str_data);

  //check the state request, if completed, pass the response to callback function
  obajx.onreadystatechange = function(){
    if(obajx.readyState == 4){
/// alert(obajx.responseText);  //for debug
      callback(obajx.responseText);
    }
  }
}

//Example Usage
var form_data = {'id1':'val 1', 'id2':'val 2'};  //object with data to send
ajaxSend(form_data, 'test.php', 'post', function(resp){
  alert(resp);
});
</script>
Iar in php:

Cod: Selectaţi tot

$id1 = trim($_POST['id1']);
$id2 = trim($_POST['id2']);
//...  
- Daca acel array e de fapt un sir /text (cu mai multe key=>val) intr-un camp de formular, e bine sa fie intr-un format JSON valid; si il poti trimite direct ca sir JSON cu Ajax la php.

Array asociativ cu date de formular trimis prin ajax

Scris: Lun Feb 01, 2016
de andras
La varianta cu sir JSON intr-un cimp hidden nu m-am gindit, der ideea este foarte buna. Voi studia variantele.