Skip to content Skip to sidebar Skip to footer

Sending Array Of Strings From Js To Php?

Is there any way to send array of strings from JavaScript to PHP? I have a game that runs on localhost and I want to track it events using Google Analytics. Google Analytics only t

Solution 1:

An example is always the most helpful:

// javascript part - use jQuery for example

$.ajax({
    url: "your-php-file.php",
    data: ['abc','def'] // your array
});

// PHP part your-php-file.php
die($_POST); // you will see the $_POST[data] = array('abc', 'def');

if you want to send the data the other way around, from PHP to javascript, add to your php file something like.

 echo json_encode (array('data_from_php'));

 // and in JS you have a callback on success for querying a php file
 $.ajax({
    url: "your-php-file.php",
    //data: [], // we dont send nothing this timesuccess: function(data){
        console.log(data); // data will be a js array containing a string 'data_from_php'
    }
});

Solution 2:

You can use AJAX to send data from a client to a server. I would recommend using a library like jQuery for these tasks as they make it much easier then writing them yourself. AJAX will be able to send data to a PHP script which can handle the data for you.

Here is an AJAX tutorial: http://www.w3schools.com/ajax/ajax_intro.asp

And here is a link to jQuery AJAX tutorial: http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html

Solution 3:

I'd use php on your localhost, if this is for a once off or running as a service. If you need this to work on client machines you will run in to many security things to worry about.

In php use file() or file_get_contence()

Otherwise have a look at json_encode and decode in php to transfer objects

Post a Comment for "Sending Array Of Strings From Js To Php?"