Hope this is the correct forum to place this question.
How would i run a php script in a javascript file? I have a php script named connection.php, it accesses a mysql database and runs queries. I would like to run the php script from a javascript file named initializeMap.js. The files are shown below with the php shown first.

        $servername = "localhost";
        $username = "root";
        $password = "";

        // Create connection
        $conn = new mysqli($servername, $username, $password);

        // Check connection
        if ($conn->connect_error) 
        {
            die("Connection failed: " . $conn->connect_error);
        }
        $query = "SELECT site,latitude,longitude,pollution FROM pollution_monitoring.locations";
    $result = mysqli_query($conn,$query);

        while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
        {
            $site=$row['site'];
            $latitude=$row['latitude'];
        $longitude=$row['longitude'];
        $pollution=$row['pollution'];

            echo ("addMarker($latitude,$longitude,'<b>$site</b><br/>$pollution');\n");
        }

and the java script is

$("#googleMap").load('connection.php');

var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",     
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
google.maps.event.addDomListener(window, 'load', initialize);

function addMarker(lat,lng,info)
{
    var pt = new google.maps.LatLng(lat,lng);
    bounds.extend(pt);
    var marker = new google.maps.MarkerImage({position:pt, icon:icon,map:map});
    var popup = new google.maps.InfoWindow({content:info, maxWidth:500});
    google.maps.event.addListener(marker,"click",function()
        {
            if(currentPopup !== null)
            {
                currentPopup.close();
                currentPopup = close;
            }  
        }
    );

    google.maps.event.addListener(popup,"closeclick",function()
    {
        map.panTo(center);
        currentPopup = null;
    }
    );
}
function initialize() 
{
  var mapProp = 
  {     
    center:new google.maps.LatLng(-29.335989,27.483622999999966),
    zoom:17,
    mapTypeId:google.maps.MapTypeId.HYBRID,
    mapTypeControl:true,
    zoomControl:true,
    scaleControl:true,
    streetViewControl:true,
    overviewMapControl:true,
    rotateControl:true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},navigationControl: true,navigationControlOptions: 
        {
            style: google.maps.NavigationControlStyle.SMALL
        }                                                                                                                                              
  };

  //php script is to run here

  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
  google.maps.event.addDomListener(window, 'load', initialize);
}

I am doing this so ii can plot markers on a google map with the markers comming from a database. the output of the php file (ran independently) is

addMarker(-29.3136256880662,27.480760216713,'<b>Pioneer Kingsway</b><br/>364.9883117675 (PPM)');
addMarker(-29.3150382892309,27.486897110939,'<b>Parliament Kingsway</b><br/>364.0746765136 (PPM)');
addMarker(-29.3147029,27.5021021,'<b>Lakeside</b><br/>364.9379577636 (PPM)');
addMarker(-29.306296,27.486722,'<b>Limkokwing</b><br/>363.6354675292 (PPM)');
addMarker(-29.312631,27.489722,'<b>Central Bank</b><br/>363.7650146484 (PPM)');
addMarker(-29.298105,27.454757,'<b>Maseru Bridge</b><br/>364.5924377441 (PPM)');
addMarker(-29.316783,27.476915,'<b>Pioneer Mall</b><br/>363.5439453125 (PPM)');

I would like the marker to be added to google with the coordinates and have the last parameter to the function (addMarker) be displayed when the marker is cliked on. I am able to get the google maps but I cannot figure out how to add the markers. what i would like to have is the markers be displayed. i hope my question is clear.

Recommended Answers

All 14 Replies

please show me what to edit/add or guide me towards a tutorial. been at this for days.....

i tried adding

$.ajax({
  url: "connection.php",
  context: document.body
});

to the javascript where I want the php to run

Something like this:

$.ajax({
    url: 'connection.php',
    dataType: 'json'
})
.done(function (data) {
    if (data.locations) {
        for (var i = 0; i < data.locations.length; i++) {
            addMarker(
                data.locations[i].latitude, 
                data.locations[i].longitude, 
                data.locations[i].site, 
                data.locations[i].pollution);
        }
    }
    else {
        alert('No results');
    }
});

Update your php with:

$data = array ();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $data['locations'][] = array (
        'latitude' => $row['latitude'],
        'longitude' => $row['longitude'],
        'site' => $row['site'],
        'pollution' => $row['pollution']
    );
}

echo json_encode($data);

still does not work. are there any files i need to import in order to use the function "$.ajax()?

Member Avatar for diafol

have you referenced the jquery file itself, e.g.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

That needs to go before any jquery flavoured javasccript that you need to use.
If you place this in the head section and any other js in the head section, then you may need to enclose your jQ with .ready(), otherwise, as seems to be the current fashion you can place your jQ reference and js/jQ at the bottom of the page just before the </body> tag and do without the .ready()

if is not too much, this is all my code.
its made up of the following.
1. the my sql database
2. the php script

<?php

        $servername = "localhost";
        $username = "root";
        $password = "";

        // Create connection
        $conn = new mysqli($servername, $username, $password);

        // Check connection
        if ($conn->connect_error) 
        {
            die("Connection failed: " . $conn->connect_error);
        }
        $query = "SELECT site,latitude,longitude,pollution FROM pollution_monitoring.locations";
    $result = mysqli_query($conn,$query);
        $data = array();
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) 
        {
            $data['locations'][] = array 
                (
                    'latitude' => $row['latitude'],
                    'longitude' => $row['longitude'],
                    'site' => $row['site'],
                    'pollution' => $row['pollution']
                 );
        }
        echo json_encode($data);

?>

3. my jsp file,this is the page that is is seen from the browser.

<html>
<head>
    <title>Congestion Viewer</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" type="text/css"/>
        <script src="jquery.mobile-1.4.5/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script src="jquery.mobile-1.4.5/jquery.mobile-1.4.5.js" type="text/javascript"></script>
        <script src="http://maps.googleapis.com/maps/api/js?key=API&sensor=true"></script>   
        <script src="map/initializeMap.js" type="text/javascript"></script>
        <script src="map/mapwithmysql.js" type="text/javascript"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <link href="map/mapcavas.css" rel="stylesheet" type="text/css"/>
        <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
    <div class="ui-body-b ui-body">
            <div data-role="navbar">
                <ul>
                    <li><a href="#popupLogin" data-icon="grid" data-rel="popup" data-position-to="window" data-translation="pop">Login</a></li>   
                    <li><a href="#popupRegister" data-icon="edit" data-rel="popup" data-position-to="window" data-translation="pop" >Register</a></li>
                    <li><a href="#popupCheckStatus" data-icon="info" data-rel="popup" data-position-to="window" data-translatin="pop">View Status</a></li>
                    <li><a href="update.jsp" data-icon="eye">Update Status</a></li>
                    <li><a href="#" data-icon="delete">Logout</a></li>                   
                </ul>
            </div>
            <div data-role="popup" id="popupLogin" data-theme="b" class="ui-corner-all">
                <form id="check-user" class="ui-body ui-body-a ui-corner-all">
                    <div style="padding:10px 20px;">
                    <input type="text" value="" name="login_name" id="login_name" placeholder="username" />
                    <input type="password" value="" name="password" id="password" placeholder="password" />
                    <button type="submit" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check">Login</button> 
                    </div>  
                </form>
            </div>
            <div data-role="popup" id="popupRegister" data-theme="b" class="ui-corner-all">
                <form id="register" class="ui-body ui-body-a ui-corner-all">
                    <div style="padding:10px 20px;">
                        <input type="text" value="" name="register_name" id="register_name"  placeholder="username" />
                        <input type="text" value="" name="register_number" id="register_number" placeholder="cellphone" />
                        <input type="password" value="" name="password" id="password"  placeholder="password" />
                        <button type="submit" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check">Register</button> 
                    </div>  
                </form>
            </div>
            <div data-role="popup" id="popupCheckStatus" data-theme="b" clss="ui-coner-all">
                <form id ="viewStatus" class="ui-body ui-body-a ui-corner-all"> 
                    <div style="padding: 10px 20px;">
                        <input type="text" value="" name="check_country" id="check_country" placeholder="country"/>
                        <input type="text" value="" name="checkCity" id ="checkCity" placeholder ="city"/>
                        <input type="text" value="" name="checkJunction" id="checkJunction" placeholder ="junction"/>
                        <button type="submit" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-location">View Status</button>
                    </div>
                </form>    
            </div>
        </div>
<div data-role="content" id="googleMap" style="width:100%;height:572px;">

</div>              
</div>
</body>
</html>

4. the Javascript file

var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",     
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
google.maps.event.addDomListener(window, 'load', initialize);

function addMarker(lat,lng,info)
{
    var pt = new google.maps.LatLng(lat,lng);
    bounds.extend(pt);
    var marker = new google.maps.MarkerImage({position:pt, icon:icon,map:map});
    var popup = new google.maps.InfoWindow({content:info, maxWidth:500});
    google.maps.event.addListener(marker,"click",function()
        {
            if(currentPopup !== null)
            {
                currentPopup.close();
                currentPopup = close;
            }  
        }
    );

    google.maps.event.addListener(popup,"closeclick",function()
    {
        map.panTo(center);
        currentPopup = null;
    }
    );
}
function initialize() 
{
  var mapProp = 
  {     
    center:new google.maps.LatLng(-29.335989,27.483622999999966),
    zoom:17,
    mapTypeId:google.maps.MapTypeId.HYBRID,
    mapTypeControl:true,
    zoomControl:true,
    scaleControl:true,
    streetViewControl:true,
    overviewMapControl:true,
    rotateControl:true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},navigationControl: true,navigationControlOptions: 
        {
            style: google.maps.NavigationControlStyle.SMALL
        }                                                                                                                                                  
  };

 $.ajax({
    url: 'connection.php',
    dataType: 'json'
})
.done(function (data) {
    if (data.locations) {
        for (var i = 0; i < data.locations.length; i++) {
            addMarker(
                data.locations[i].latitude, 
                data.locations[i].longitude, 
                data.locations[i].site, 
                data.locations[i].pollution);
        }
    }
    else {
        alert('No results');
    }
});

  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
  google.maps.event.addDomListener(window, 'load', initialize);

}

i have been able to do this using php with javascript embedded inside. viewable here, its a page hosted by 000webhost.

function addMarker(lat,lng,info) takes only three arguments so change the call to:

addMarker(
    data.locations[i].latitude, 
    data.locations[i].longitude, 
    data.locations[i].site + ' ' + data.locations[i].pollution);

map still does not load

Debug. Which part fails? I hate guesswork, and "does not work" is not helpful at all.

map still does not load

Member Avatar for diafol

map still does not load

Heh heh. So funny. Been laughing for minutes at that. OK, prit - get on with it. You've been told what the problem is - twice! Heh heh. For those of you who don't know, pritaeas is omniscient.

commented: Am glad someone is having a laugh ;) +14

sorry for the vague reply, was very frustrated. everything else that is supposed to be on the page loads. Without this piece of code

$.ajax({
    url: 'connection.php',
    dataType: 'json'
})
.done(function (data) {
    if (data.locations) {
        for (var i = 0; i < data.locations.length; i++) {
            addMarker(
                data.locations[i].latitude, 
                data.locations[i].longitude, 
                data.locations[i].site, 
                data.locations[i].pollution);
        }
    }
    else {
        alert('No results');
    }
});

the map loads but without any markers as the function addMarker() is not reviecing any parameters. with the code inserted, the map just does not load and no error is displayed.
thanks for the help

You havent changed the addmarker code which i posted in my previous reply.

If you put an alert, do you at least see the retutned locations?

use google.maps.marker()

the deprecated object google.maps.MarkerImage only defines the image.
(the also an example on the same page what to use now)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.