0

I have this simple jQuery function:

$(document).ready(function () {
    var books = {};
    books.id = '1';
    books.author = 'Bob';

    $.post('/index.php',
    {
       books: books
    },
    function(data, textStatus)
    {
       alert(data);  
    });
});

And this index PHP script:

<?php

  foreach($_POST['books'] AS $key) {
       echo ''.$key['id'].' is written by '.$key['author'].'';
  }

?>

I want to loop through the jQuery array and display the id and author of each key in the array. I don't know the correct way to access the values in the array. It seems I'm doing it wrong.

2
  • 1
    you're passing a single object in books, not an array. you should also use json_decode in the php to parse the data into an php object Commented Sep 30, 2014 at 17:54
  • 1
    var books = [{id:1, author: 'Bob'}, {id:2, author: 'Bill'}] Commented Sep 30, 2014 at 18:04

1 Answer 1

2

You have misunderstood the difference between {} and [] in JavaScript:

  1. {} is an object
  2. [] is an array

In your case you should pass an array of book objects for this to work in your php script. Example:

var books = [
    {
        id: 1,
        name: "The Da Vinci Code",
        author: "Dan Brown"
    },
    {
        id: 1,
        name: "Gray Mountain: A Novel",
        author: "John Grisham"
    }
]

To add more elements to the array after it has been initialized, you can simply use push:

books.push({id: 3, name: "Avatar", author: "Lisa Fitzpatrick"});

Will output:

1 is written by Dan Brown
2 is written by John Grisham 
3 is written by Lisa Fitzpatrick
Sign up to request clarification or add additional context in comments.

1 Comment

hey mate :) How can i push more elements to this array after it has been initiated?

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.