0

I am new for jquery, ajax.... value from php file is return back thro' json_encode. My problem is here i dont know how to access those datas.

Here the Code...... js code....

<script>
 $(document).ready(function(){

     setInterval(ajaxcall, 1000);
 });
 var devid=1;
 function ajaxcall(){
    devid++;
    //alert(devid);
    $.ajax(
    {
     url: 'gettime.php',
     data:{devid:devid},

     success: function(data) 
     {

         //data = data.split(',');
         data1 = data.a;
         data2 = data.b;        

         var latlng = new google.maps.LatLng(data1, data2);
         //alert(data.lat);

         var options = {
            zoom: 14,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
         };
         var map = new google.maps.Map(document.getElementById('map_canvas'), options);

    }

    });
}

</script>

php file (gettime.php)

<?php 
    $vvid = $_REQUEST['devid'];
    echo $vvid;
    $sql= mysql_query("select * from maploca where id='$vvid'");
    $sqlqry = mysql_fetch_array($sql);
    $var1 = $sqlqry['latitude'];
    $var2 = $sqlqry['latitude'];
    echo json_encode(array("a" => $var1, "b" => $var2));
?>
Murali Daran
  • 21
  • 2
  • 10
  • You want to access this json array in js rite??? – Elavarasan Muthuvalavan - Lee May 08 '13 at 06:30
  • 2
    It is not clear what is your problem. In your js code you are already accessing data returned with json_encode (here: `data1 = data.a; data2 = data.b;`) , so how else you want to access it? – Viktor S. May 08 '13 at 06:34
  • You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 08 '13 at 06:44
  • thanks for ur reply... here in jquery i need to pass those variables in google map function. Then only i will show lat, lan in googke map. – Murali Daran May 08 '13 at 06:49

4 Answers4

2

Here in your ajax call dataType: "json", is missing

$.ajax(
{
 url: 'gettime.php',
 data:{devid:devid},
 dataType: "json",
 ....................
})
Deval Shah
  • 1,094
  • 8
  • 22
  • 1
    @MuraliDaran What does "wont't work" mean? You are getting wrong results or what? Have you checked console in browser for errors? – Viktor S. May 08 '13 at 06:57
  • @MuraliDaran You can check `alert(data1)` and `alert(data2)` for checking `lat` and `long` – Deval Shah May 08 '13 at 07:01
  • 1
    what it comes when `alert(data)` please provide output @MuraliDaran – Deval Shah May 08 '13 at 07:19
  • ya i check that alert(data1), it results "undefined" in alert dialog box – Murali Daran May 08 '13 at 07:20
  • 1
    @MuraliDaran Try to do `alert(data)` instead. What is returned? – Viktor S. May 08 '13 at 07:22
  • ya.. it returns some html code and last line is {a:null, b:null} – Murali Daran May 08 '13 at 07:25
  • 1
    @MuraliDaran Well, than simply change your php script so it will not return any HTML code. – Viktor S. May 08 '13 at 07:26
  • 1
    @MuraliDaran `echo json_encode(array("a" => $var1, "b" => $var2)); exit;` ,you should write this and in ur `PHP` script problem is there .. so `echo $vvid;` comment this line only data `json_array` would be `echo` there && try 'print_r($sqlqry);' to check for correct `lat` and `lng`. – Deval Shah May 08 '13 at 07:29
  • {main}( )..\gettime.php:0 20.0155373032mysql_fetch_array ( )..\gettime.php:24 {"a":null,"b":null} – Murali Daran May 08 '13 at 07:29
  • in your php code how `tr` and `td` comes ?? please look at this simple example.. for basic understaning llok at this [link] (http://blog.abdulmajeedpk.com/2011/04/jquery-json-php-simple-read-data-table-database/) – Deval Shah May 08 '13 at 07:41
1

As far as I can see, your code should work just fine. Except that you may have a problem in gettime.php. I do not see mysql_connect code there, so you query may fail to be executed.

Another possible problem there:

 $var1 = $sqlqry['latitude'];
 $var2 = $sqlqry['latitude'];
 echo json_encode(array("a" => $var1, "b" => $var2));

You are taking latitude twice, when I guess it should be something like:

$var1 = $sqlqry['latitude'];
$var2 = $sqlqry['longitude'];
echo json_encode(array("a" => $var1, "b" => $var2));

Anyway, check your PHP error log. Possibly you will find some error there (you will find it for sure if you are really missing mysql_connect code)

Also - learn how to use developer tools/firebug. It will help you a lot with debugging JS.

EDIT

Remember that your script must return ONLY json code. If there will be some garbage (Like html code) in response, browser will be unable to parse response and you will get error or simple string (instead of object) in data of success function.

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • Thanks for ur reply., I check out mysql. No more errors in db connection. here value also return to jquery, but my problem is i don't know how to get those php variables – Murali Daran May 08 '13 at 07:13
  • Try to add `header('Content-type: application/json');` before `echo json_encode` This will show jquery that request returns json – Viktor S. May 08 '13 at 07:25
  • 1
    I really missed that db connection. Now I cleared it and i got value for both 'a' and 'b'., here can you give me how to separate those values... – Murali Daran May 08 '13 at 07:44
  • @MuraliDaran your `jquery` code is enough for seperating this `json` – Deval Shah May 08 '13 at 12:58
  • 1
    dataType: "json", like suggested by @DevalShah or that header suggested by me should work just fine. If you add one of them (or both) it should return you `data` like a regular object. – Viktor S. May 08 '13 at 13:07
  • I made fault in specify lat,lan and in header i affix connection string. Then only i can't able to hit, after fix that the problem solved. Thanks Fangel, Deval Shah – Murali Daran May 10 '13 at 10:22
0

You are missing the the dataType property in ajax call by default data are return back by php script in text/xml format in order to change the default behavior you have to specify the right format that is json so your ajax call should be

ajax

$.ajax( {

url: 'gettime.php',

 data:{devid:devid},

 dataType: "json",

 type:post

})

php

$vvid = $_REQUEST['devid'];
echo $vvid;
$sql= mysql_query("select * from maploca where id='$vvid'");
$sqlqry = mysql_fetch_array($sql);
$var1 = $sqlqry['latitude'];
$var2 = $sqlqry['latitude'];
echo json_encode(array("a" => $var1, "b" => $var2));
Sandeep Garg
  • 1,292
  • 1
  • 13
  • 31
0

Finally problem has solved the code will be....

<script>
    $(document).ready(function()
    {
        setInterval(ajaxcall, 1000);
    });
    var devid = 1;
    function ajaxcall()
    {
        devid++;
        var veh = <?php echo $veh?>
        //alert(devid);
        $.ajax({
            url: 'gettime.php?devid='+devid+'&veh='+veh,
            success: function(data) 
            {
                var datasep = data.split(',');


                /*if(datasep2!=null && datasec2!=null)
                {*/
                var datasep1 = datasep[0].split(':');
                var datasep2 = datasep1[1].replace('"','');
                datasep2 = datasep2.replace('"','');

                var datasec1 = datasep[1].split(':');
                var datasec2 = datasec1[1].replace('"}','');
                datasec2 = datasec2.replace('"','');
                //alert(datasep2);
                var json = [
                { "lat":datasep2,
                "lng":datasec2 }]
                var latlng = new google.maps.LatLng(datasep2,datasec2);
                var myOptions = {
                    zoom: 18,
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                var polylineCoordinates = [
                new google.maps.LatLng(datasep2,datasec2)];
                var polyline = new google.maps.Polyline({
                    path: polylineCoordinates,
                    strokeColor: '#FF0000',
                    strokeOpacity: 1.0,
                    strokeWeight: 2,
                    editable: true
                });
                polyline.setMap(map);
                for (var i = 0, length = json.length; i < length; i++) 
                {
                    var data = json[i],
                    latLng = new google.maps.LatLng(data.lat, data.lng); 

                    // Creating a marker and putting it on the map
                var marker = new google.maps.Marker({
                position: latLng,
                map: map
                });
                }   
                /*}
                else
                {
                    datasem1 = datasep[0].split(':');
                    datasem2 = datasem1[1].replace('"','');
                    datasem2 = datasem2.replace('"','');
                    alert(datasem2);
                }   */
            }
        });
    }
    </script>

php code will be....

<?php //ob_start();
include "../../config/connection.php"; 
  //  header("Content-Type: application/javascript");
    //header('Content-Type: application/json');

    $vvid = $_REQUEST['devid'];
    $veh = $_REQUEST['veh'];
    if($vvid!='')
    {
    $sql= mysql_query("select * from maploca where id='$vvid' and veh_id='$veh'") or die(mysql_error());
    $sqlqry = mysql_fetch_array($sql) or die(mysql_error());
    $var1 = $sqlqry['latitude'];
    $var2 = $sqlqry['longitude'];
    echo json_encode(array('a' => $var1, 'b' => $var2));
    }
    else
    {
        echo "Empty Value";
    }

    //echo $_GET['callback'] . "([" . implode(",", $ll) . "]);";*/
?>
Murali Daran
  • 21
  • 2
  • 10