1

I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.

Thanks

a.js (this function listens onLoad of the page)

    function doFirst(){
    var button = document.getElementById("button");
    button.addEventListener("click", save, false);

    var buttons = document.getElementById("clear");
    buttons.addEventListener("click", clear, false);

    var buttonss = document.getElementById("submittodb");
    buttonss.addEventListener("click", toPHP, false);

        $.ajax({
            method: 'post',
            dataType: 'json',
            url: 'edit.php',
            data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
            success: function() {//some code to handle successful upload, if needed
            }
        });

        }

        function save(){

        var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

        var newItem = {
           'num': document.getElementById("num").value,
            'methv': document.getElementById("methv").value,
            'q1': document.getElementById("q1").value,
            'q2':document.getElementById("q2").value,
            'q3':document.getElementById("q3").value,
            'q4':document.getElementById("q4").value,
            'comm':document.getElementById("comm").value,

        };
        oldItems.push(newItem);

        localStorage.setItem('itemsArray', JSON.stringify(oldItems));}


edit.php


$parsed_array = json_decode($_POST['items']);

and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
user2162768
  • 69
  • 1
  • 7
  • Why not make a post to the server which you then use to render the new page? – David L Mar 12 '13 at 20:41
  • 1
    POST the data to a PHP script using AJAX. – Nick Pickering Mar 12 '13 at 20:41
  • If you are changing pages, then you can simply post the data to the server and render the new page. If you want to stay on the same page then and still post the data to the server, then your best bet is to use ajax. – War10ck Mar 12 '13 at 20:42
  • @NicholasPickering could you put an example please cause im pretty new to javascript and AJAX – user2162768 Mar 12 '13 at 20:42
  • You need to learn AJAX to do what you want: http://www.w3schools.com/ajax/default.asp – Nick Pickering Mar 12 '13 at 20:48
  • Possible duplicate to http://stackoverflow.com/questions/5035547/pass-javascript-array-php – Mihai8 Mar 12 '13 at 21:02
  • Try analyzing `var_dump($_POST);`, it should give you some idea on what the contents of `$_POST` are. This is so called "echo-debugging", so if you appearto have normal debugger (e.g. XDebug) - use it. – J0HN Mar 15 '13 at 11:35

3 Answers3

4

In order to pass this array to PHP you need to:

  1. JSon-encode it
  2. Make an AJAX or POST request to PHP
  3. Parse the passed array into PHP array

If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as

$.ajax({
    method: 'post',
    dataType: 'json',
    url: 'the URL of PHP page that will handle the request',
    data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
    success: function() {//some code to handle successful upload, if needed
    }
});

In PHP you can parse the passed array with just

$parsed_array = json_decode($_POST['items']);

There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.

More on $.ajax, and json_decode for reference.

J0HN
  • 26,063
  • 5
  • 54
  • 85
  • where do i declare this stuff in the js file or in the php file that i want it to appear? (im new to all this stuff) – user2162768 Mar 12 '13 at 20:52
  • `$.ajax` goes to javascript file. `$parsed_array = json_decode($_POST['items']);` - to the file that will respond to the url you've set in the `$.ajax` call. Spend some time reading about AJAX, it's not as hard as it may look like. – J0HN Mar 12 '13 at 20:55
  • Hey man i just tried it and i get a undefined index... any ideas? – user2162768 Mar 14 '13 at 13:52
  • Update the answer with the code you use and the error you get. I've got no psychic powers, you know :) – J0HN Mar 14 '13 at 14:46
  • UPDATE: Ive read the console log and it says json_decode() expects parameter 1 to be string, array given – user2162768 Mar 15 '13 at 18:54
  • @user2162768 well, it looks like $_POST['items'] is itself an array. I'm kind of detached from PHP for a year, so I'm not sure, they might have added auto JSON decoding. Anyway, try to examine the contents of $_POST, identify the data you pass and than just make sure you are trying to access it, but not something else. Mechanical debugging, can't help with that much, I'm afraid. – J0HN Mar 15 '13 at 19:01
0

You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.

Basically, you need to send the data from the client (browser) back to the server where the database hosted.

Marc Audet
  • 46,011
  • 11
  • 63
  • 83
0
  1. Call JSON.stringify(oldItems); to create the json string

  2. Do a Do a POST request using AJAX.

Probably the simplest way is using jQuery:

$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
  // it worked.
});
Yogu
  • 9,165
  • 5
  • 37
  • 58
  • how do i declare JQuery in my .js file (never used it before sorry!) – user2162768 Mar 12 '13 at 20:45
  • [Download it here](http://jquery.com/download/) and include it in your html file. – Yogu Mar 12 '13 at 20:47
  • Thanks man i will try it out now =] P.S the JSON.stringify i put in the js file and the $.post i put in my html file? – user2162768 Mar 12 '13 at 20:49
  • 1
    If you would prefer not to have to download it and host it yourself you can use the Google CDN. Place `` in the head of your html file. – War10ck Mar 12 '13 at 20:50
  • No, everything is javascript. I already embedded the `JSON.stringify` in the code sample. – Yogu Mar 12 '13 at 20:55
  • How do i print the contents in the Array in the php? because i will be calling the function in a different file (so, sorry!) – user2162768 Mar 12 '13 at 20:57
  • This is a new question. Tip: They are stored in `$_POST['items']`. Note that I changed the code sample; it had a mistake. – Yogu Mar 12 '13 at 20:59
  • Hey man i just tried it and i get a undefined index... any ideas? – user2162768 Mar 14 '13 at 13:54