javascript php array to javascript

php array loading into javascript

so I am a total php/javascript noob.

I’m trying load a full php array into a javascript array. I wrote this for Javascript:

I already checked if the php array is correctly filled with data. When I write a output line in javascript, like

it only gives me the first entry in the php array so it seems like everytime the for loop is repeated its initialising the php file from scratch and so setting the counter to 0. How can i fix that?

6 Answers 6

The above code will then output a script tag contain a varible called myarray, then contents of which will be JSON specifying the above array (json_encode formats the array in to javascript internal syntax- the array will probably look like [‘cat’,’dog’,’bat] )

You can then get values from the JavaScript array as so:

Your PHP code is executed before your Javascript, thus it doesn’t make sense to use it this way.

Instead, you should do something like this:

In fact, if your PHP is that simple, you don’t need a function:

In both case, you’ll have a Javascript like that:

This is a common mistake for people starting web development. The important thing to realize is that all of your PHP code runs before the javascript starts*. If you take a look at the javascript that gets to the browser you’ll see

which explains why each element is the same. A nicer way to do this is to use json_encode in PHP to just transfer the array into a JS variable. Like this:

*For the people writing comments about Javascript running at the same time as the PHP, either by starting the JS early or using AJAX, yes, I’m aware, but for a beginner the model of PHP totally generates then JS starts running is simpler to understand.

Источник

JSON PHP Array to Javascript

in javascript, it give me errors. I was wondering if there is a limitation on what sort of php arrays JSON can/cannot do.

5 Answers 5

First you need a PHP file on a Apache server somewhere with PHP installed. Make a file like this:

localhost:8888/myfile.php

Then your JavaScript (in this example I use jQuery):

This should be a start to get PHP arrays in to your JavaScript.

As @Allendar said you can’t embed PHP inside a JS file. You could, however, add a function in your JS file to load the JSON data, and then embed that data in a script tag in your PHP file.

Edit: this is assuming you only need to get the data into JS once at page load, in which case you can skip making AJAX requests.

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

Passing PHP JSON to Javascript and reading

var stuff = ; var arr = new Array(); arr= JSON.parse(stuff); document.write( arr[0].cust_code );

JSON can handle any type of array (albeit it will cast associative arrays as objects). The problem you are probably facing is that you are trying to output with PHP when the data is available only on Javascript.

To clarify: once the page has loaded, PHP cannot do anything. Only javascript can process things on client side, PHP works only on the server and has no knowledge of the state of the client.

I’ve never tried to do something like this but I think that you’re having issue because json_encode returns a json encoded string. You then need to decode this string on the javascript side of things. Try something like the following:

Источник

passing PHP objects to javascript [duplicate]

I have objects in php that each represents a «item» and all info associated with it.

And when the user browses the page, these objects should be passed to javascript. Ideally, mirroring the same structure, so I can use Raphael to display each item and its info as separate shapes on my site.

However, how do you get an object from php to javascript?

4 Answers 4

You can convert the PHP object to an array, and then use JSON function to encode it. After that, decode it from JavaScript. Here are some basic steps:

Convert the PHP object to an array.

Using json_encode() to encode that PHP array.

Pass JSON-encoded data to PHP

Decode JSON from JavaScript using JSON.parse or you can use jQuery.parseJSON to do that.

This is an interesting tutorial about passing a JavaScript object to a PHP object. You might find it useful by watching some other featured/related videos.

Late answer, but I am very surprised no one mentioned what is, arguably, the «correct» way to deploy this functionality.

The jsonSerialize will be called when you attempt to use json_encode on the object. You can think of this interface as a sort of «magic method» specific to the native JSON encode function, equivalent to __toString for strings.

Putting it in action, you have an object that looks like this:

When I am implementing this in my projects, I usually put a toArray method in the objects, which generates the array, and I have jsonSerialize use it:

. this way I can also make use of the array form, if I so choose. This is also handy if you’ll be implementing object serialization with __sleep

Источник

How do I pass variables and data from PHP to JavaScript?

I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?

I have code that looks like this:

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

18 Answers 18

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

In this post, we’ll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

index.php (or whatever the actual page is named like)

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It’s still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Implementation Example

Implementation is relatively straightforward:

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

This example uses jQuery, but it can be adapted for another library or vanilla JavaScript.

I’m going to try a simpler answer:

Explanation of the problem

First, let’s understand the flow of events when a page is served from our server:

So really, the core thing to remember here is that HTTP is stateless. Once a request left the server, the server can not touch it. So, that leaves our options to:

Solutions

That’s the core question you should be asking yourself is:

Am I writing a website or an application?

Website

Sending more requests from the client after the initial request is done is slow as it requires more HTTP requests which have significant overhead. Moreover, it requires asynchronousity as making an AJAX request requires a handler for when it’s complete.

I would not recommend making another request unless your site is an application for getting that information from the server.

You want fast response times which have a huge impact on conversion and load times. Making Ajax requests is slow for the initial uptime in this case and unneeded.

You have two ways to tackle the issue

Setting a cookie is really not very difficult, you just assign it a value:

Then, you can read it with JavaScript using document.cookie :

Here is a short hand rolled parser, but the answer I linked to right above this has better tested ones:

Cookies are good for a little data. This is what tracking services often do.

Once we have more data, we can encode it with JSON inside a JavaScript variable instead:

Application

My answer here explains how to load data using AJAX in JavaScript:

Now, the server just needs to contain a /your/url route/file that contains code that grabs the data and does something with it, in your case:

This way, our JavaScript file asks for the data and shows it rather than asking for code or for layout. This is cleaner and starts to pay off as the application gets higher. It’s also better separation of concerns and it allows testing the client side code without any server side technology involved which is another plus.

Simply use one of the following methods.

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

I quite like the way the WordPress works with its enqueue and localize functions, so following that model, I wrote a simple class for putting a scripts into page according to the script dependencies, and for making additional data available for the script.

The call to the enqueue_script() function is for adding script, setting the source and dependencies on other scripts, and additional data needed for the script.

And, print_scripts() method of the above example will send this output:

Regardless the fact that the script ‘jquery’ is enqueued after the ‘jquery-ui’, it is printed before because it is defined in ‘jquery-ui’ that it depends on ‘jquery’. Additional data for the ‘custom-script’ are inside a new script block and are placed in front of it, it contains mydata object that holds additional data, now available to ‘custom-script’.

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

-After trying this for a while

Although it works, however it slows down the performance. As PHP is a server-side script while JavaScript is a user side.

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

You could even pass a variable back to the PHP file such as this example:

Then in «your_php_file.php»:

Here is is the trick:

Here is your ‘PHP’ to use that variable:

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

Let’s say your variable is always integer. In that case this is easier:

Output:

Let’s say your variable is not an integer, but if you try above method you will get something like this:

But in JavaScript this is a syntax error.

So in PHP we have a function call json_encode that encode string to a JSON object.

You can use same method for arrays:

And your JavaScript code looks like this:

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

javascript php array to javascript. Смотреть фото javascript php array to javascript. Смотреть картинку javascript php array to javascript. Картинка про javascript php array to javascript. Фото javascript php array to javascript

I’ll assume that the data to transmit is a string.

As other commenters have stated, AJAX is one possible solution, but the cons outweigh the pros: it has a latency and it is harder to program (it needs the code to retrieve the value both server- and client-side), when a simpler escaping function should suffice.

So, we’re back to escaping. json_encode($string) works if you encode the source string as UTF-8 first in case it is not already, because json_encode requires UTF-8 data. If the string is in ISO-8859-1 then you can simply use json_encode(utf8_encode($string)) ; otherwise you can always use iconv to do the conversion first.

But there’s a big gotcha. If you’re using it in events, you need to run htmlspecialchars() on the result in order to make it correct code. And then you have to either be careful to use double quotes to enclose the event, or always add ENT_QUOTES to htmlspecialchars. For example:

However, you can’t use htmlspecialchars on regular JavaScript code (code enclosed in tags). That makes use of this function prone to mistakes, by forgetting to htmlspecialchars the result when writing event code.

It’s possible to write a function that does not have that problem, and can be used both in events and in regular JavaScript code, as long as you enclose your events always in single quotes, or always in double quotes. Here is my proposal, requiring them to be in double quotes (which I prefer):

The function requires PHP 5.4+. Example usage:

Источник

Passing a PHP array to JavaScript.

In this guide, we are going to show you how to pass a PHP array to your JavaScript code.

This is extremely useful if you need to pass data from the server to your JS code without using an AJAX request.

Convert your array into JSON.

The best approach is to convert your array into a JSON string and then pass it to your JavaScript.

To convert your PHP array into JSON, you can use the json_encode function. This function will return the JSON representation of the value that you have passed it.

For example, let’s say that we have a basic associative array that looks like this.

Now, let’s say that we want to pass the $cartInfo array to one of our JS scripts so that we can do something on the client’s side.

The first thing we’ll do is convert it in JSON.

If you echo out the $cart_info_json variable above, you will see that we are left with a string that looks like this.

Pass it to your JavaScript code.

After we have done that, we can pass the JSON string to our JavaScript like so.

Like with all JavaScript variables, you can use the console.log function to dump out its structure to the browser console.

In our example, the variable obj will look similar to this.

This means that we can now access the data like so.

And there you have it! Your PHP array is now accessible as a JavaScript variable.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *