This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How would I go about doing this? (AJAX)
Since the last time I asked this questions I failed horribly at being specific so I'm going to try again and be as as specific as possible.
First I have my data encoded in the json_encode function.
Looks like this for example:
{"test":"test value"}
What I want to do is make test into a javascript variable where it can hold the data of "test value". The json_encode data is on a page called index.php and the page that I want the variables to be defined in is called example.html. So what I want is in the javascript portion of the html is have a javascript variable called test and have it equal the string "test value".
Also I don't want jquery for this solution as I was restricted to not being able to do so. I can't use invisible forms and submit them.
Objects are associative arrays. They store key/values pairs. So All you have to do is:
var test = function(){}
test["hello"] = "world";
This will set hello as a variable and world as its value.
you can test this by doing
alert(test.hello);
Replace hello and world with the json key and value
var json = JSON.parse( {"test":"test value"} )
var testValue = json.test
Related
I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a two-dimensional php array, $phpar, in which both dimensions are indexed (0,1,2,...), and all values are plain text. Within a JavaScript function, I want to convert this array into a two-dimensional JavaScript array. I know the following code doesn't work, but it illustrates what I want to do.
jsfunction() {
var jsarray = new Array();
jsarray = <?php json_encode($phpar); ?>;
}
If the returned value is something other than a regular js array, like a JSON string, I need some help parsing that into what I want, please.
I'm not exactly sure where your problem is...but the basic operation of json_encode simply looks like:
<script type="text/javascript">
var jsarray = <?php echo json_encode($phpar); ?>;
</script>
Frankly, I don't see why the other people are suggesting throwing a javascript-compatible object/array into a string, and worse the way they did it is wrong. If you want a JSON object string, this is the correct way of doing it:
<script type="text/javascript">
var jsarray_string = <?php echo json_encode(json_encode($phpar)); ?>;
// ^ ^------ php array to js array
// '------------------ php string to js string
</script>
By the way, javascript objects can be accessed like arrays. Example:
var myArray = {1: 'hi', 2: 'bye'};
alert(myArray[2]); // this works!
The only difference is that myArray is not really a javascript array, eg, myArray.constructor is not Array().
What are you actually trying accomplish here in terms of you application's functionality?
PHP is a backend language and JavaScript is a frontend language. If you need the frontend to retrieve an object from the backend to use in your JavaScript you should use Ajax as opposed to putting PHP code inside your JavaScript.
Your Ajax method will call the relevant PHP method using an MVC-style URL ('/mycontroller/mymethod'). The PHP method should use use associative array(s) since JSON objects are key-value pairs. You should json_encode the array before returning it.
Here's some sample PHP code:
<?php #foo.php
public function bar() {
$array = ('first-name' => 'John', 'last-name' => 'Doe');
return json_encode($array);
}
On the frontend, your JSON object will consist of the same key value pairs as your associative array:
var getBar = function() {
$.get('/foo/bar', function(data) {
var string = 'My name is ' + data.first-name + ' ' + data.last-name';
alert(string);
}, json);
};
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I have to do a function that automatically take care of passing variables from PHP to JavaScript in a simple and safe.
Currently stored in a class variable array with the values of the variables, and then the idea is to extract in Javascript, but many doubts assail me what the (technically) best way to do this.
Also passes through my head several problems, especially when complex move to Javascript arrays or strings with accents, special symbols or symbols as quote or single quote, including problems with the function json_decode when work with chains with line breaks and carriage returns. (You get invalid JSON, I've had to do a cleaning function in PHP to avoid passing variables with these characters, but sometimes I need be)
I searched the web a lot, and I have found many answers but none terminade convince and more with the above problems.
An example:
The PHP Method (too simple):
var JsVars;
public function saveJsVar($key, $value) {
$this->JsVars[$key] = $value; //Possible need to clean certain characters like /n /r
}
The "javascript part"
<script>
var SistemVars = SistemVars || {};
<?php foreach ($JSVARS as $k => $var) { ?>
SistemVars.<?=$k?> = '' || '<?php echo $var ?>'; // Dont work with arrays only plain
<?php } ?>
</script>
Another option:
<script>
var SistemVars = SistemVars || {};
SistemVars = <?=json_encode($JSVARS)?> // Object, with plain and array BUT problems with certain characters.
</script>
The idea its use PHP (saveJsVar) to save plain variables and arrays, and set the vars in SistemVars object en JavaScript to use it like alert(SistemVars.ParamOne);
with your experience, what do you think is the best way to do this?
The 2nd option is the better way to do it, as it saves using a foreach loop. also, json_encode is made for this purpose, so why not use it :) And just FYI, <?= ...?> short tags for PHP are not used anymore Are PHP short tags acceptable to use?
<script>
var SistemVars = SistemVars || {};
SistemVars = <?=json_encode($JSVARS)?> // Object, with plain and array BUT problems with certain characters.
</script>
I like using hidden input elements and use/access their values with jQuery.
Doing this will allow you to keep your js clean - with no PHP code inside.
If you want to export all of your JS code into external files - this is the way.
$("#doStatus").click(function()
{
var serialized = $("#formStatus").serialize()
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
This code will return something like this:
tuitting=test&f%5B%5D=2&f%5B%5D=4&f%5B%5D=8&t%5B%5D=2&t%5B%5D=3&t%5B%5D=4
Where tuitting(the first value) is the value of the textarea, then we have:
-f this is the name of somecheckboxes that have the same names but different values
-t other checkboxes, same names, different values
As you may see the serialized function for "f" and "t" returns strange values, when they should only be simple number, like tuitting=test&f=1&f=3&t=9&t=10
Now when the ajax call the doStatusBox.php file nothing happens.
The doStatusBox.php file is made by a simple foreach php loop.
It will take the below variables:
$_GET['tuitting']
$_GET['t']
$_GET['f']
Foreach `$_GET['t'] and $_GET['f'] the loop will insert the relative values into the database.
This is not working at all. The php foreach can not recognize the results given by the jQuery serialize function and does not do simply anything.
What is the problem?
I should use another function instead of foreach?
Or the problem is in the jQuery serialized function?
Please help me.
`
Since we cannot see your HTML code, I can't say for sure what the problem is, but I suspect it's one of two problems:
(most likely) - your checkbox fields need to have a [] after the name. Example: name="t[]". If all of your checkboxes are name="t", then when multiple are posted, PHP will only see one of them. However, if you put brackets at the end of the name PHP will recognize the collection of values as an array that you can loop through.
(less likely) - the PHP script that receives this data should run urldecode() on the data. Example: $tuitting = urldecode($_GET['tuitting']);
Hope this helps!
I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1¶m2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.