0

I have a JavaScript array which contains JSON pairs of values of the form:

var myArray = [{attribute: "attributeID1", option: "optionID1"},
{attribute: "attributeID2", option: "optionID2"}];

I have a PHP script which wants to take that data in array form and search my database with it. I am not looking to remain on the page while this search is happening so I don't want to use AJAX - I just want to pass this data to the PHP script which will then render the new page.

What is the easiest way for me to do this?

2 Answers 2

1

Put it in a hidden input element. Then submit the form that the input element is in.

1

First, you'll need to grab a copy of json2.js so that you can convert your object into a JSON string.

https://github.com/douglascrockford/JSON-js

You can then stringify your object and place it in a hidden input field in the form.

document.getElementById('search').value = JSON.stringify(your_object);

Now that will be sent over the to PHP script where you can decode it using the built in function json_decode()

http://php.net/manual/en/function.json-decode.php

$object = json_decode($_POST['search']);
2
  • Hey Mike, thanks for the reply! I've downloaded json2.js now and included that line of code you provided. How do I include it in a hidden input field though? Commented Sep 2, 2012 at 16:47
  • document.getElementById('hiddenId').value = JSON.stringify(yourObject);, after the form is submitted, the json data is passed to the server Commented Sep 2, 2012 at 16:48

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.