0

How can I pass a a javascript array vArray to File.php , and retrieve the two values from vArray.

I tried:

<input type="button" id="button" onClick = "send_V();" >

<script>
// Creat Array with Values from checkboxes
$('input[type=checkbox]:checked').each(function() {
    vArray.push($(this).val());
});

// Set array to only 2 values ( disable checkboxes)
var n = $('input[type=checkbox]:checked').length >= 2;  
$('input[type=checkbox]').not(':checked').attr('disabled',n);

// Send array to File.php where I can manipulate its value1, and value2 to query db
function send_V(vArray)
{
    $.ajax({
        type: "POST",
        url: "File.php", 
        beforeSend: function () {
            $("#result").html("<option>Loading ...</option>");
        },
        data: "vArray="+vArray,
        success: function(msg){
            $("#result").html(msg);
        }
    });
} 
</script>

and on the php side ( File.php)

$value = $_POST['vArray'];
var_dump(vArray);

but I am not able and sure how to manipulate a javascript variable. can someone show me a simple and effective method ? What is wrong in this logic? Thanks

vegemite4me
  • 6,621
  • 5
  • 53
  • 79
Awena
  • 1,002
  • 5
  • 20
  • 43
  • 5
    client-side: serialize into json. server-side: decode into php array with json_decode() – Marc B Dec 02 '13 at 15:56
  • It doesn't have to be JSON; it depends on what the server wants. If the "data" parameter is a JavaScript object with a "vArray" property that has the array as its value, then jQuery will POST to the server a set of parameters based on the property name ("vArray[]"). – Pointy Dec 02 '13 at 16:06

4 Answers4

2

Use json. Encode array in js (How do I encode a javascript object as JSON?), decode it in php (http://php.net/manual/ro/function.json-decode.php).

Community
  • 1
  • 1
zozo
  • 8,230
  • 19
  • 79
  • 134
1

Pure javascript for modern browser (needs support for formData & xhr2)(chrome,safari,ios,android,ie10)

js

var vArray=['a','b','c'],
json=JSON.stringify(vArray);//this converts the array to a json string

function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
 c=new XMLHttpRequest;
 c.open(e||'get',a);
 c.onload=b;
 c.send(d||null)
}
function whatever(){
 console.log('json posted',this.response)
}

ajax('page.php',whatever,'post',{'json':json});

page.php

<?php
print_r(json_decode($_POST['json']));//converts the json string to a php array
?>

Another solution is to post the whole form

html

<form>
<input name="a" value="x">
<input type="radio" name="b" value="x">
//and many other input & text fields
</form>

js

function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
 c=new XMLHttpRequest;
 c.open(e||'get',a);
 c.onload=b;
 c.send(d||null)
}
function whatever(){
 console.log('form posted',this.response)
}

var form=document.getElementsByTagName('form')[0],
    fd=new FormData(form);

ajax('page.php',whatever,'post',fd);

php

<?php
print_r($_POST);
?>

xhr2

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

formData

https://developer.mozilla.org/en-US/docs/Web/API/FormData

cocco
  • 16,442
  • 7
  • 62
  • 77
1

If you set up the ajax call with an object for the "data" parameter:

$.ajax({
   type: "POST",
   url: "File.php", 
   beforeSend: function () {
     $("#result").html("<option>Loading ...</option>");
   },
   data: { vArray: vArray },  // here
   success: function(msg){
     $("#result").html(msg);
   }
 });

Then jQuery will create HTTP request parameters like this:

 vArray[]=first value
 vArray[]=second value

etc. On the server side, when you access

 $vArray = $_POST['vArray'];

you'll get the array back. You don't have to explicitly mess with JSON if you don't want to, in other words.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

I have tried the following that seems to work fine :

<script language="JavaScript" type="text/javascript">
function ajax_post(){

// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();

// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>

It is working really well for me. Code taken from http://www.developphp.com/view.php?tid=1185

Answers by @Pointy and @Cocco might be correct, I could not manage to implement it right with Jquery, neither wanted to use a Form.. Hope this helps someone

Awena
  • 1,002
  • 5
  • 20
  • 43