I want to send geographic data (latitude & longitude) to a mySQL database with Ajax call and PHP script. Both Ajax and PHP scripts look ok for me but nothing goes to the database. I've try different syntax and option (like PDO with array) to manage MySQL but still nothing... Do you have an idea of what is going wrong ?
Thank you very much for your help,
Flo.
The Jquery code of my Html page is simple :
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajaxSetup({
url: "insert-in-bdd.php",
type: "POST",
});
$.ajax({
data: 'latitude='+latitude+'&longitude='+longitude,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
});
}
}
The first PHP script I try (insert-in-bdd.php) is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$latitude = ($_POST['latitude']);
$longitude = ($_POST['longitude']);
$db = mysql_connect(localhost, root, "");
$select = mysql_select_db(madb, $db);
mysql_query('INSERT INTO location (lat,lng)
VALUES (:longitude, :longitude)');
}}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
The second PHP script I try (with PDO and array), same name : insert-in-bdd.php is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=madb', 'root', '');
$req = $bdd->prepare('INSERT INTO location(lat, lng) VALUES(:lat, :lng)');
//$req = $bdd->prepare('UPDATE location SET lat = :lat');
$req->execute(array(
'lat' => $_POST['latitude'],
'lng' => $_POST['longitude']
));
}}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
I would do:
$query="insert into location (lat,long) values('".$_POST['latitude']."','".$_POST['longitude']."');";
mysql_query($query,$connection);
You seem to have forgotten the connection from the mysql_query(), and I'm not sure about using :latitude etc.
For your first code block try the following for the mysql query:
"INSERT INTO location (lat,lng) VALUES ('" . $latitude . "', '" . $longitude . "')"
Also, it's very important to clean up your data before inserting into the database - this kind of code leaves you open to sql injection.
You should use the function mysql_real_escape_string around your variables. You can either put it in when you assign the post variables to the $longitude and $latitude, or in the query itself.
You need to have a mysql connection available when you call the function.
Related
I have problem to get jsonp from my server by id.
I am sure that my php is good, but i don't know how to parse id from php server to htlm-jquery.
My php page is:
<?php
header('Content-type: application/json');
include 'config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);
$id=$_GET['id'];
$sql = "select * from ios where id=$id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
////////////////////
?>
And this works great, i got json object by id in php.
You can check for example http://www.dr-trkuljic.com/tekst.php?id=1 (you can try with id 2, 3, and 4) you will get result.
But i don't know how to parse that in jquery in my html page
I am using this in my html page:
$(document).ready(function(){
var output = $('.nesa');
$.ajax({
url: 'http://www.dr-trkuljic.com/tekst.php',
dataType: 'jsonp',
data: 'id',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
So, my question is how to parse (show) by id in my html page?
To be precise how that result from my server http://www.dr-trkuljic.com/tekst.php?id=1 get in my html page?
Thank you.
1 If you are on the same domain
In php change
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
to
echo json_encode($records);
JS success:
success: function(data, status){
var jsonData = JSON.parse(data);
var total = jsonData.length;
for(var i = 0; i < total; ++i){
var ispis = jsonData[i].naziv + " " + jsonData[i]item.tekst;
console.log("My ispis ", ispis);
}
}
2 if you want to use JSONP. (get response from another domain or phonegapp )
When you need a response from another domain you can't use AJAX request, what you can do is load a new script in document for example in tag, You load that script as js script with your response. Inside that js script you put your response in some variable, and also you can call some function that is defined in already loaded js file. for example
echo "var myVar = " . json_encode($records) . '; myCallbackFunc();';
Than load that file as js file to your document
and somewhere in that or where ever js that you want to get response - myVar will contain your response that you can use, and when response load your callback function will be called
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.dr-trkuljic.com/tekst.php?id=1';
head.appendChild(script);
function myCallbackFunc(){
// Do something with myVar
var total = myVar.length;
for(var i = 0; i < total; ++i){
var ispis = myVar[i].naziv + " " + myVar[i]item.tekst;
console.log("My ispis ", ispis);
}
}
EDIT
Just double check if server response - javascript syntax is ok.
As I felt my previous answer was incorrect, allow me to edit:
After you remove the '(' and ')' from around the json array, you can simply use this quick and easy shorthand format for your jQuery http call: (all parsing is already performed because of the Content-Type header). You are then free to access the appropriate properties of the object.
For further examples on how to use jQuery's $.get() and $.post(), etc... visit this link:
http://api.jquery.com/category/ajax/shorthand-methods/
$(document).ready(function(){
var output = $('.nesa');
var idNumber = 1;
$.get('http://www.dr-trkuljic.com/tekst.php', {id: idNumber}, function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
}).fail(function(){
output.text('There was an error loading the data.');
});
});
To overcome cross-domain errors, you can send this header in your php file with the appropriate url of where you're working from:
header("Access-Control-Allow-Origin: http://your-domain-or-localhost");
I'd like to store some div content when a button is pressed. I need/want to save the html tags as well in order to reuse.
When I replace the post variables by any type of string, it works flawlessly. I tried cleaning the html variable from line breaks but it didn't do it, tried also to shell the $HTML post in a $var = <<<HTML HTML, but this didn't work either.
Here is the javascript :
$("#save").click(function(){
var pageHTML = $("#page_wrap").html();
var name_page = "name";
jQuery.ajax({
type: "POST",
url: "php/saveModel.php",
data: { nHTML: pageHTML,
page : name_page
},
success:function(data){
var responseData = jQuery.parseJSON(data);
var new_div = responseData.message;
$("#page_wrap > *").remove();
$("#page_wrap").prepend(new_div);
$('.editable').aloha();
}
})
})
And here is the php :
<?php
mysql_connect('localhost','name','pwd');
mysql_select_db('db');
mysql_query("SET NAMES 'utf8'");
$id = $_POST['page'];
$HTMLpost = $_POST['nHTML'];
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
if($insertSignup){
$status = "success";
$message = "OK";
}
else {
$status = "error";
$message = "NOT OK";
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
Thanks !
Simple answer: use mysql_real_escape_string() to change the quotes to make it safe for entry into the database.
$HTMLpost = mysql_real_escape_string($_POST['nHTML']);
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
Longer answer: You should not be using the mysql_() functions as they are being depreciated. Check out prepared statements with PDO or mysqli instead - they will safely handle this for you (and they are not being depreciated).
Reading: http://php.net/manual/en/pdo.prepared-statements.php or google for more - plenty of examples around. Best to learn now before you get stung when the mysql_() functions do get removed.
I cannot get my $_POST to work for some reason..Here is the code:
*Javascript that gets called from href onClick event:*
function feedVote(postId, vote) {
if(vote == "1") {
document.getElementById('voteUpSpan' + postId).innerHTML = "Thank you for voting!";
document.getElementById('voteDownSpan' + postId).innerHTML = "";
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
}
}
So it spoofs a image and runs my voteUp.php page passing the parameters without changing the current page.
<?php
$id = $_POST['postId'];
$con = mysql_connect("localhost", "username", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$update = mysql_query("UPDATE posts SET upvote = upvote + 1 WHERE id = '$id'");
mysql_close($con);
echo "$id";
?>
The echo "$id"; returns nothing so its obviously not even putting a variable in $id which is why my sql statement is not being run but why...
When I run the code in Google Crome, I use the network tracking feature under Inspect source code and this is the url it fires off when it runs my spoof image.
test.com/voteUp.php?time=1327644851907&postId=35
**I editted some of the information out like my database name and username/password and website url.
Those parameters are known as GET params, not POST.
Use the $_GET super global (use it in the same way as $_POST) to access them.
If you want post, do some jquery ajax post, like this:
Instead of:
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
change it with this:
$.ajax({
url: "voteUp.php",
cache: false,
type: 'POST',
data: {time: d.getTime(), postId: postId},
success: function(data){}
});
Note: you need jquery on that webpage!
Variables that appear in the query string of the URL (i.e. after the ? character) are accessed using the $_GET array rather than $_POST.
I wonder whether someone may be able to help me please.
I'm currently working on a website that through a User Input Form, XML and PHP, users will add and save google map information to my SQL database.
I've successfully been using one of the examples on the Google site which explains how to use PHP and XML to save user defined information to the database.
The example use the $GET method, but from the information I've been reading on the web, the $POST option does seem the better method to use.
However when I change my coding to the $POST method I can create a record on the database but the values keyed into the form are not copied scross to the database. I know that I'm perhaps making a really stupid beginners mistake, but I just wondered whether someone may be able to tell me what I need to do to get it to work.
I've included cut down versions of the files below.
Many thanks
Chris
HTML Form Submit Button
function savedata() {
var locationname = document.getElementById("locationname").value;
var returnedaddress = document.getElementById("returnedaddress").value;
var url = "phpfilename.php?locationname=" + locationname + "&returnedaddress=" + returnedaddress;
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('POST', url, true);
request.send(null);
}
function doNothing() {}
</script>
HTML Form
<body>
<label><br />
</label>
<form name="searchforlocationformgeocode" id="searchforlocationformgeocode">
<div>
<label for="address">
<div align="center">
<p>Location Name</p>
<p>
<input name="locationname" type="text" id="locationname" size="80" />
</p>
</div>
<p align="left"><label>Returned Address</label> </p>
<div align="left">
<input name="returnedaddress" type="text" id="returnedaddress" size="100" />
</div>
PHP File
<?php
require("phpfilename.php");
// Gets data from URL parameters
$locationname = $_POST['locationname'];
$address = $_POST['returnedaddress'];
// Opens a connection to a MySQL server
$connection = mysql_connect ("xxxxxxxx", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO tablename " .
" (locationname, address) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($locationname),
mysql_real_escape_string($address));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
You are passing the values using a query string, to get them you need to use $_GET.
var url = "phpfilename.php?locationname=" + locationname + "&returnedaddress=" + returnedaddress;
To use $_POST, instead of adding the encoded name/value pairs to the end of the URL, send them via the request.send() method:
request.send("locationname=" + locationname + "&returnedaddress=" + returnedaddress);
A general rule of thumb is that if your target page is supposed to just retrieve some info using GET is just fine however if your data is supposed to make any changes to the database etc. you should always use POST.
BTW, your form tag must contain the method you are using to submit the data in this case method="post"
<form name="searchforlocationformgeocode" id="searchforlocationformgeocode" method="post">
So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan