Passing php array to javascript - php

I have created a Google Map using JavaScript (v3 api). I have popped a couple of markers onto this, just to show it can be done. I have added some text to a text box specific to each marker, just to see if it can be done. Both marker and text box are ugly, but that's a problem for a different day. The map takes up around 75% of screen width and 100% screen height.
I have a mySQL db of user posts. The data includes a post #id, a category, an ip address, a longitude value, a latitude value, a city, a user name, a heading and post content.
I have 'floated' a table containing post category and heading up beside the map, using PHP to query the db, shoving the db rows into an array and using this as the source for the table. This takes up the remainder of the display width.
Fine, so far.
I want to add a marker for each post so that the marker is located at the longitude and latitude from which the post originated. I want to add content to a marker text box that is specific to that post (e.g. city, user name, post heading, post content).
Further, I want to be able to link the posts in the displayed table to the map markers so that, for instance, a mouse-over event on a particular post in the table might cause the text box associated with that marker to become visible.
But I cannot seem to find a way to pass the PHP array to the Google Map JavaScript so that I can use this to add the markers as required.
Nor have I yet been able to find a way to associate a mouse over event on an object external to a Google map to a Google map marker.
I have done extensive research and have found similar requests for the former - passing a PHP array to JavaScript. The suggested solution is usually to create a string from the PHP array with some sort of separator, e.g. a comma, and pass this to JavaScript where it is reformed into an array. I do not believe this would work in my case.
My current code resides in a single file. The style stuff is located in a style section in the html head section and can be moved to a separate css file later. The Google map JavaScript are in script sections, again in the html head and can be moved to a separate js file. The body contains just a little html - divs for the map-canvas and the table with PHP
to acquire the database rows in a single PHP array and to create the html for the table.
I am aware that 'PHP is server side technology while JavaScript is client side' as has been indicated many times.
But surely there must be some way to pass an array of data obtained by PHP from a SQL db (not that the data origin is particularly relevant) to JavaScript code?
I apologise for being so verbose, and if my questions have been answered somewhere I have missed, or misunderstood. Or if I am being particularly stupid.
Take care.
Mike
Adding this by editing the original post.
OK. I might have found an answer to my second question: how to create a link from an external element to a Google map marker. http://econym.org.uk/gmap/mouseover.htm Always the way, after giving up looking for something that item is found.
Mike

Convert your PHP array to JSON, using json_encode.
Now you have a JavaScript object you can use.

$jsonString = json_encode($phpArray);
In javascript:-
var jsonStr = <?=$jsonString?>;

Related

Creating Interactive Poll With Results Page

I'm looking to create a poll/form that will allow the user to select a starting 11 for a football game (or soccer if you're American), and then submit it and then see an image of the most popular team selection among the fans (maybe most popular for each position instead of most popular team selection all together).
Ideally I would like the form to have options for formation (4-4-2, 4-3-3, 4-5-1 etc) that would change the layout/inputs on the form (but this is definitely not essential, would just be a nice touch - I would just stick with 4-4-2 otherwise).
My dream idea is that there will be a dashboard on the bottom that had player profile pictures that can be dragged and dropped into their positions; However having simple drop down boxes would work too (as long as a player cant be used twice - which is another stumbling block because you don't want the same player to be in both CB positions.)
Design Concept (Results page would basically be the same just without the bottom dashboard):
I have absolutely no idea how to approach this as it is way more complex than anything I have attempted in the past. (Forgot to mention I would like to be able to reset the results every week or so if possible)
So if someone could let me know if its do-able, and if it is, take me through how to do it step by step or even mock one up for me it would be much appreciated.
Thanks.
It doesn't have to be a form.
Here how you do it:
Create the divs for the squares on the field.
Assign each of them a unique id e.g.
id="square-1"
and give them a common class e.g class="field-square"
Create the divs for the squares outside the field. Give them a common class, and a unique id for each.
When you drop the squares, have a function that extracts the ids when they are dropped.
Then simply post them to your PHP site with jQuery.post()
Update
To extract the ids, in your callback (after you have dropped the square) do something like this:
square_id = square_id.replace('square-', '');
Since you've not assigned number ids (which you should, so that you can easily change the players in future by getting them from a database), you can simply get the ids using $(this).attr('id') in your callback.
Also look up http://api.jquery.com/jQuery.post/
I wouldn't even think about dragging and dropping at this point. Outline what the minimal viable product would be and come up with a set of steps to do that.
Going off the data you provided I would suggest something like this...
1) Build an html form that list simply a list of all the positions and a dropdown of all the possible players that can fill that position.
2) Fill out the form (select the players) and on form submit get the data echo'd as an array.
3) Create the graphic...I see two approaches....(1) server side (GD or Imagick are probably what you are going to want to use) or (2) CSS/html images
Either one will a fine approach....this step should probably be broken into little steps...start with simply displaying a list and an image of the player next to it...
HTML would be
echo "<img src='/images/players".$_POST["position1"]."' alt=''/>";
//(NOTE YOU HAVE TO CLEAN ANY DATA YOU ARE OUTPUTTING PROPERLY)
Imagick would be something like..
$bg = new Imagick("/images/bg.jpg");
$position = new Imagick("/images/players".$_POST["position1"]);
//Second image is put on top of the first
$bg->compositeImage($position, $position->getImageCompose(), 5, 5);
//new image is saved as final.jpg
$bg->writeImage('final.jpg');

Is it possible to add an overlay in google maps api on user side e.g. with rmb click?

I'm working on a project of mine, which would require users to add markers on a google maps api map, that would be later on passed to a DB, which would store all overlay coordinates and once the map is loaded (in case the user has the required permissions, of course), a for loop will add all markers from the DB into the page and will visualize them (circles with static radius, but various coordinates). So long story short, I need a way to enable the users to put those markers themselves there and a way to read the LatLng coordinates and pass them to a script, which will flush them in the DB. One way (in case it's possible, of course) is to use the context menu and add an option like "set marker here", that would pass the coords to a function flushing them to the DB. Of course the workaround is RMB-> what is here, copy the coords and enter 'em in a input field, which almost inevitably will doom the project to an epic fail, because nobody will do that, but instead will just enter some random numbers, which would be moronic, because the project basically depends on those coordinates.
So is there a way to somehow automate the adding process of an overlay element in the api, that I could use? I googled around for a few days, tried to find something in the v3 help too, but didn't find anything really helpful so far..
Thanks in advance! All comments and help would be appreciated!
Cheers,
vlex

Save information to database after jquery callback

I'm new here and I'm very new at programming but I need some serious hand-by-hand help here.
I was searching jquery and found a script to drag and drop stuff on the screen, basicly i just want to move some divs around, thats the easy part, the script I found has a callback function that writes onto the div that you just moved "dropped", this is exactly what I need but instead of writting dropped I want to save the 2 postion variables into a database (mysql), this is so that if I close the browser and open it again the div's will be on the last place I dropped them.
Can you help? Is there a jquery user interface with this already built in ?
I think this is easy to do with jquery ajax functions right? basicly I should send the serialized data (json right?) into a page that processes that data once its feed into it, then jason returns the handler with success or even with some output right?
It would be cool for the dragabble div to have a handler with last know position retrieve by jason from an external page that acts like a buffer to the database.
Is this the correct pipeline?
Best Regards
Joricam
you have kind of a vague question here, but I can try to help you get closer to the answer.
Imagine two sides of the puzzle:
When the page loads, the two (or more) DIVs are drawn on the screen. If you want them to draw in a specific order, you need to keep track of that in the database. So be sure your db has a field called something like display_order, and then display the DIVs in that order. (You can usually just add ORDER BY display_order to the SQL, so they are retrieved in the order you want, and then draw the DIVs right out in a loop.)
When someone drags and drops a DIV, you use AJAX/JSON/etc to tell your PHP script the new order. In this case, when that happens, rather than draw the word 'dropped' in the DIV, you should instead immediately update the display_order fields in the database. This way you are remembering each DIV's position.
Does that help/make sense?
UPDATED: thinking more about your question, here is the pseudo code:
in "display.php":
Fetch the contents for each DIV from the database, with ORDER BY display_order on the rows.
Draw them on the screen, looping through each database row.
Also in this HTML, use the jQuery script you already have to call another PHP script (dragged.php) when a row is dragged.
in "dragged.php":
This script is called when a row is dragged on the screen.
Currently it puts the word "dropped" in the DIV that is dragged. That's not helpful, so remove that.
Instead, you now know (from the variables passed to you) that a specific DIV needs to be in a specific place.
So grab a list of the DIVs from the database, then change the order of them (by altering the display_order column) based on the new position(s) you know.
Save that back to the database, so when display.php is called again next time, it draws the DIVs in the order you want.
Hope this helps explain further. If you are still struggling, I respectfully suggest you try to write the code, and post a more specific question about the part that you're stuck on. This will help you get a good answer quickly. (You may also want to Google this one a lot; I'm sure there are code samples out there showing how to do all this.)

Looking for design/architecture suggestions for a simple HTML game

Imagine that HTML page is a game surface (see picture).
User can have n number of boards (blue divs) on his page. Each board can be moved, re-sized, relabeled, created new and removed.
Inside each board there are m number of figures (purple divs). Each of these user can move inside the board or to another board, re-size, change color and label, delete, add new.
The goal of the game is not important, but let's say it is to rearrange figures in a certain way so that they disappear.
But the goal of the programmer is to save the whole game surface in the database for every user of the site, and to load it later when he returns.
So, how do I go about data exchange between client and the database?
Here's how I think it can be, but maybe there is a better way.
In the database I think of creating tables users, boards and figures.
Then I can SELECT all that belongs to a user and create his HTML page (surface).
But then, user will be able to change all of those properties of boards and figures and I don't know how to track those changes and how to save them back to the database. Is this a situation where JSON should be used?
Yes, if Javascript is an option, then basically you should generate a document (xml or json or plain text, doesn't really matter that much, though json is probably easiest if you're using javascript) that describes the serialized state of the board.
You can then track all changes client-side in a javascript object, and have javascript serialize that as a string that you then transfer to the server using XHR.
I would say that generally, in this scenario, you're best off with each object being a DOM element of some kind (div, span, whatever), because that way the browser can do all the work for you on figuring out positions and such, just absolutely position it all and work from there.
I'm assuming this is mostly going on with javascript when they're playing and that you already know how to do that. Well, each figure has propertes, like this:
-board (the one it's in)
-id
-label
-width
-height
-color
-x position (relative to board)
-y position (relative to board)
So each of those properties will be held in a javascript variable or array while playing. Likewise, the boards also have properties:
-id
-label
-width
-height
-color
-x position (relative to page)
-y position (relative to page)
So you will hold these in javascript variables as well.
When you save you just need to pass all of those variables over to the server. So make your XHR with your JSON string. Once your server receives the request you translate the JSON back into variables you can stick in the database. The way you're planning your database sounds appropriate.
To restore you would just SELECT the appropriate info for that user and (either with a normal page load or XHR) and use your javascript that moves everything around to create and position the objects where they need to go.

How can I convert language of a div?

I am recently working in a project. There I need to convert language from English to Japanese by button click event. The text is in a div. Like this:
"<div id="sampletext"> here is the text </div>"
"<div id="normaltext"> here is the text </div>"
The text is come from database. How can I convert this text easily?
Assuming that you have both the English and the Japanese version in the database, you can do two things:
Use AJAX to load the correct text from the database and replace the contents of the div. There are tons and tons of tutorials on the internet about AJAX content replacement.
Put both languages on the website and hide one using CSS display:none. Then use some JavaScript to hide/display the correct div when a button is clicked.
The first is technically more complex but keeps your page size small. The second one is very easy to do, but your page size is larger because you need to send both languages.
If the div is small and there is only one or two of these on the page, I recommend number two, the CSS technique. If the div is large (i.e. a complete article) or there are many of them then use the first method.
If you mean translating the text, you cannot do it easily. To get some idea of the best attempts that software can make at translating natural languages, go to Google Translate or Babelfish. It's not that good, but it's sometimes an intelligible starting point.
If you just mean setting the language attribute on an element, then assign a new language code to the lang property of the div element object.
document.getElementById("normaltext").lang = "en-US";
I don't know the language code for Japanese; possibly ja-ja.
Assuming your literals have an id in your database you could put that id as a class in your div. Then with jquery fetch the ID, send it to your Ajax back-end and fetch the translated one.
First, if you have the texts in a database it really doesn't matter if you render it in divs, tables or whatever.
First you need a php api for some translation service. Here is just an example that might give you some ideas.
$textArray = getTextForThisPage();
?>
...
english_to_japanese($textArray["text1"]);?>
...

Categories