Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

pass javascript array to php

Hi,

I have following input field:

html:

<input type="text" id="searchName" class="ui-autocomplete-input" autocomplete="off" placeholder="Add name (one at a time)">
                        <button id ="add" type="button" class="btn btn-success">Add</button>

Javascript / JQuery

<script type="text/javascript"> 
            jQuery(document).ready
            (
                function()
                {
                    var list = [];

                    $('#searchName').autocomplete(
                    {
                        source:'inc/suggest_name.php',
                        minLength:2,
                    });


                    $('#add').click(function() {
                        var item = $('#searchName')
                        $('#klist').prepend("<a href='#'><li><i class='icon-ok icon-large' style='color: #31AF43'></i>"+item.val()+"</li></a>");
                        list.push(item.val());
                    });

From the moment i type 2 characters in the textfield the autocomplete function shows names from the mysql database and if i select a name press the 'Add' button it shows them in a listview and adds the value to the Array 'list'.

Now i want to use the values inside the array in the php file data.php so i can run some queries on my database with these values.

I found all kinds of solutions on stackoverflow using ajax, json but i can't get it to work.

Some said the easiest thing was to make a string of the array and send it with ajax:

html:
<button id="data" class="btn btn-danger" >Show data</button>

script:
$('#data').click(function() {
                        var data_str = list.join(","); 

                        $.ajax({
                            type:           'post',
                            cache:          false,
                            url:            'inc/data.php',
                            data:           data_str
                        });
                    });

php:
<?php
    $array = explode(",", $_REQUEST["list"]);
        print_r($array);
?>  

Does anybody got some experience with this?

Can you simplify the question? It sounds straightforward, you want to type something in a text box, hit a button, then add it to an array.

Is that correct?

In the bottom code it looks like you're taking your array, creating a string, sending the string to php then creating an array. Could you just send over the data directly in array form?

Yes it's already doing that in my jquery -> list.push(item.val());

Now i want to use that array in a php function, it's possible with ajax but i can't get it to work.

2 Answers

I was able to do it like this:

$('#data').click(function() {
    var data_str = list.join(",");

    $.ajax({
           type: 'post',
           url: 'inc/data.php',
           data: {
                     source1: data_str
                    },
           success: function( data ) {
                     console.log( data );
                    }
           }); 
}););

I concatenate the array 'list' seperated by a comma inside the variable data_str and send that data to the php file.

<?php

$src1= $_POST['source1'];
$array = explode(",", $src1);

print_r($array);

?>

And restore the concatenated string back to an array inside the php-file.

Got the idea from: http://stackoverflow.com/questions/19462649/trying-to-pass-variable-values-from-javascript-to-php-using-ajax

EDIT: Noticed you are requesting 'list' in your php, but you never send list over! Try requesting data or data_str.

Found an answer that I think should work on stackoverflow. I don't personally use php, but this should work.

This looks similar to the $.ajax command you use, but uses the commands directly instead of the key-value pairs. Ideally, this would simplify your code.

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Pulled from here: http://stackoverflow.com/questions/8191124/send-javascript-variable-to-php-variable