Posting php multi dimentional array into a new window - php

I have an associative array I got from my database.
I would like to open a new window with that associated array posted to it.
I did manage to post it in ajax post, But it's not what I need because I want a new window!
Using a form is impossible because you cannot put that kind of data in an hidden input.
So how do I do it?

I think you are looking for JSON
Php example:
echo json_encode( array('int'=>123, 'char'=>'abc', 'array'=>array(1,2,3)) );
The javascript:
$.getJSON( "ajax/test.php", function( data ) {
console.log( data ); // data is a json-object
data.each(function(item){
console.log( typeof item.int ) // Number, value 123
console.log( typeof item.char ) // String, value '123'
console.log( typeof item.array ) // array/object, values 1,2,3
});
});
edit: the names int, char and array are choosen as example. One might want to avoid the usage of reserved names as variable names
edit: misread, changed to better answer

I used session as suggested by #CodeBird.
$_SESSION['temp_info'] = $array;
Then I just <a href> to another page.
Where I used the following code:
$array = $_SESSION['temp_info'];

Related

Decode json and display in table

I have a HotUKDeals API which when using the URL bellow gives me some JSON.
Im trying to use PHP to display it in a table but if i try and use a loop to go through the JSON i get errors.
If i try and decode i get "Object of class stdClass could not be converted to string"
So far I have this which i no gets the json and stores it in the variable .
I also have some JS which will go through JSON and put it in a table , but im having difficulties getting the JSON in the php variable into the JS.
Needed to remove code for work reasons !
To get the JSON into your jQuery code you'll have to use AJAX:
PHP file -
<?php
$tester = file_get_contents('http://api.hotukdeals.com/rest_api/v2/?key=d2c088ea340558b3b3517396963a341c&results_per_page=2&output=json');
echo $tester;
?>
jQuery AJAX -
$.get( "hotukdeals.php", function( data ) {
// now you can work with `data`
var JSON = jQuery.parseJSON( data ); // it will be an object
$.each(JSON.deals.items, function( index, value ) {
console.log( value.title + ' ' + value.description );
});
});
NOTE: The JSON that is returned has complex construction, so you will have to take care about how you extract during the loop and then place in the table.

Trying JSON Encoding of Ajax function sending values

I am using a hidden field and appending values with the following function.
$( "#invite_suggestion" ).autocomplete({
source: BASEURL + 'index.php/search_contacts_suggestion/',
select: function( event, ui )
{
$('#invite_id').val($('#invite_id').val()+ui.item.friend_id);
}
});
In the PHP side
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(array($_POST['invite_id'])):json_encode(NULL);
But Actually the final output of this is string ["4565"] and what i actually need is to JSON encode of individual values in field ["45","65"]
seperate the values by a comma in your js:
$('#invite_id').val($('#invite_id').val()+','+ui.item.friend_id);
then explode on the comma in php to create the array:
(isset($_POST['invite_id']))?json_encode(explode(',',$_POST['invite_id'])):json_encode(NULL);
on the PHP side I expect you'll want to do an 'explode' on the $_POST['invide_id'] to get an array of elements. $_POST['BLAH'] will only return a string.
e.g. something like...
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(explode($_POST[',', 'invite_id']))):json_encode(NULL);

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

How to unserialize a serialized array sent to the server using GET method with a jQuery Ajax call?

I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

Post an array from Javascript to PHP

I have an array in Javascript that i am trying to pass to php. my array looks like this.
Array[0]
"empNo" : "1347"
"empName" : "John Doe"
I am building this array from this javascript:
$('input[type=text]').each(function()
{
if ($(this).attr("value").length>0)
{
param[$(this).attr("id")]=$(this).attr("value");
}
});
Then I pass the array to php using
$.post("example.php",param)
Then in php when I try to interact with the post like this:
$emp=$_POST['empNo'];
$name=$_POST['empName'];
echo ($_GET[0]);//this is for testing
It throws an error saying that The Indexes of empNo and empName are not Defined.
It also says that 0 is an undefined offset.
Thanks for the help
Instead of looping through and manually building your data to pass just do this for the whole form.
var data = $('form').serialize();
$.post("example.php", data);
Then you should have access as you expect in your php script.
BUT make sure you're using the <input name="exampleName" /> attribute and then try to access them like this...
$value = $_POST['exampleName'];
while right now, it looks like you're trying to use the id instead of name
My first guess would be that $_POST has an array whose members are the values you are sending.
So, I think the values are in $_POST[1], $_POST[2], etc...
Try to print_r($_POST) and see where your variables went to.
Response to your comment:
I would tidy up things a bit, just a suggestion - especially the attr('value') part.
$('input[type=text]').each(function() {
if ( $(this).val() ) {
param[$(this).attr('id')] = $(this).val();
}
});
Try this
var param = $('form').serialize();
$.post("example.php", param);

Categories