0

I have received help here und stackoverflow making an invite function. In a AJAX based search box, it is possible to invite teams. When searching for a team, finding it and then selecting it - the team will be stored in an array. However, I need the data from the array in PHP.

My question: can I transfer the javascript array to PHP using AJAX? The code can be seen below here. The AJAX part is made using jQuery.

//AJAX based search
var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j("#search_results").slideUp();
    $j("#button_find").click(function(event){
        event.preventDefault();
        search_ajax_way();
    });
    $j("#search_query").keyup(function(event){
        event.preventDefault();
        search_ajax_way();
    });
});

function search_ajax_way(){
    $j("#search_results").show();
    var search_this=$j("#search_query").val();
    $j.post("search_team.php", {searchit : search_this}, function(data){
        $j("#display_results").html(data);
    })
}
// <----- AJAX search ends ------>

//Add-remove teams

//Functional object for team
var Team = function (id, name) {
    this.name = name;
    this.id = id;
}

//Array which will contain teams
var TeamList = [];

//Checking if the team is already added
function containsTeam(id) {
    for (var i = 0; i < TeamList.length; i++) {
        if (TeamList[i].id == id) {
            return true;
        }
    }
    return false;
}

// Removed team by onclick-event
function removeTeam(id) {
    for (var i = 0; i < TeamList.length; i++) {
        if (TeamList[i].id == id) {
            TeamList.splice(i, 1);
            document.getElementById('teams').removeChild(document.getElementById('ta'+id));
        }
    }
}

function addTeam(tid) {
    // Grab the input value
    var teamName = document.getElementById(tid).innerHTML;
    var teamID = document.getElementById(tid).id;

    // If empty value
    if(!teamName || !teamID) {
        alert('An error occured.');
    } else {
        if(containsTeam(teamID) == false) {
            TeamList.push(new Team(teamID, teamName));

            // Create the teams with the value as innerHTML
            var div = document.createElement('div');
            div.className = 'team-to-invite';
            div.setAttribute('onclick', 'removeTeam('+teamID+')');
            div.onclick = function() { removeTeam(teamID) };
            div.id = 'ta' + teamID;
            div.innerHTML = teamName;

            // Append it and attach the event (via onclick)
            var teams = document.querySelector('#teams').getElementsByTagName('div');
            document.querySelector('#teams').appendChild(div);
        }
    }
    return false;
}

The teams are stored in TeamList().

Thanks in advance.

2
  • The answer to your question is, yes, you can send an array of data from javascript to a server-side script using AJAX. Are you having a problem with a specific part of your code? Commented May 24, 2013 at 22:23
  • I first wanted to get confirmed that this was possible in my situation. Commented May 24, 2013 at 22:42

2 Answers 2

1

The current best way to do this is to encode the array into a string, which is the only format you can POST to a PHP script.

JSON encoding is currently the most popular standard for sending data like this over the internet. Here is an example of some encoded data:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

In general, you will use jQuery's JSON encoding to encode the array, post this data to your PHP script, and then decode it at the PHP end.

POSTing an array with jQuery

var dataToSend = { 
    data: TeamList
};
jQuery.ajax({
    type: 'POST',
    url: "myPhp.php",
    data: JSON.stringify(dataToSend),
    dataType: "json",
    success: function(data){ alert(data); }
});

PHP to Decode the JSON

<?php
$foo = file_get_contents("php://input");
$decoded = json_decode($foo, true);
var_dump($decoded); //Print out the data
$myArray = $foo => data;
6
  • I am familiar with the whole thing about json, and it seems proper to do it that way in this case. I tried out your code, but nothing seems to happen. I made a "send_data"-function that is called when submitting the form (onclick-event). Then I put the data you proposed in that send-data function. Now, is it okay to receive the data in the same file as the script and the data is filled? I fill out the fields and invite the teams in create_cup.php <- can the data be received in this file too? Commented May 24, 2013 at 22:49
  • My code is simply an example, to show you how to transport the data. As you can see, in the javascript, you create a data object that contains "data" which has the contents of whatever is in your TeamList array. Note that it's posting it to myPhp.php - change this to your php script. I recommend just testing it out with a simple one so that you can be sure your data is posting correctly. You should see an alert when you get data back, which with only the code I've shown should just be your data object. Commented May 24, 2013 at 22:52
  • jsfiddle.net/hskrijelj/sNkgw/1 I have made a simple example. However, no alert appears. Commented May 24, 2013 at 23:04
  • @hskrijelj And you expect myPhp.php to exist on jsFiddle? Commented May 24, 2013 at 23:14
  • No, not at all. I just wanted to show you my index file. myPhp.php is placed on my localhost containing the code used to decode the JSON. My firebug actually notifies that a AJAX call has been made. But why does the alert not appear? Commented May 24, 2013 at 23:19
-1

can I transfer the javascript array to PHP

You can only transfer strings from a browser, where you javascript executes, to a server, where your php executes. But there are well recognized string formats, e.g. json, that can be converted to arrays and such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.