After ajax action, data is not saved in the mysql database

Posted on

Question :

I am capturing latitude and longitude through the Cordova plugin, and after that I store it in two variables and then, through an ajax request, I transfer these values to a PHP script where I am saving the data to a table called a map. The problem is that it runs the ajax code, returns success information, nothing else in the database is saved … I can not find the error.

PHP:

if($_GET['acao']=='btnfinaliza'){

$latitude = $_GET['tlatit'];
$longitude = $_GET['tlongt'];

$SQL = "INSERT INTO mapa (lat, lng) VALUES ('$tlati','$tlong')";

$re = mysql_query($SQL, $serve);
}

Ajax:

$('#btn_finaliza').on('click', function(){

        var Cap = function(position){
            var coord = position.coords;
            var tlatit = position.coords.latitude;
            var tlongt = position.coords.longitude;
            $tlati = $('tlatit');
            $tlong = $('tlongt');
                    $.ajax({
                            type: "get",
                            url: $server+"/conecta.php",
                            data: "latitude="+$tlati+"&longitude="+$tlong+"&acao=btn_finaliza",
                            success: function(data) {
                                intel.xdk.notification.alert('Problema cadastrado', '', 'ok'); 
                            }
                        });

        }

        });

    

Answer :

You should get php by the same names as you sent by js, $_GET['latitude'] and $_GET['longitude']

data: "latitude="+$tlati+"&longitude="+$tlong+"&acao=btn_finaliza

change to:

$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];

$SQL = "INSERT INTO mapa (lat, lng) VALUES ('$tlati','$tlong')";
mysql_query($SQL, $serve) or die(mysql_error());

Do not use the mysql_ * functions already removed in php7, prefer MySQLi or PDO.

Recommended reading:

Why should not we use functions of type mysql_ *?

MySQL vs PDO – Which is the most recommended to use?

How to prevent SQL injection in my PHP code

Why parameterized SQL queries (name =?) prevent SQL Injection?

    

After cerning the syntax of the code, I discovered the error …
I was missing a _ in the php code. Was

if($_GET['acao']=='btnfinaliza')

More should be:

if($_GET['acao']=='btn_finaliza')

After the fix, the code worked and the data was saved to the database as expected.
Thanks for the help and I’ll follow the recommendations!

    

Leave a Reply

Your email address will not be published. Required fields are marked *