Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers

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

share|improve this answer

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']);
share|improve this answer
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? – user1058210 Sep 2 '12 at 16:47
document.getElementById('hiddenId').value = JSON.stringify(yourObject);, after the form is submitted, the json data is passed to the server – Elias Van Ootegem Sep 2 '12 at 16:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.