I'm trying to figure out how do I send a javascript array of x,y coordinates to a Mysql database? I don't have any forms or anything.
I'm very new the mysql so I basically know how to connect using this:
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
but I don't know how to connect that to the javascript. I know it has something to do with this code
jQuery.post(url, data);
Any help would be really appreciated!
I've put together this little one-page demo. Having a look at it might help you understand how it works.
To make it work, you need to put it on a server (no way!), and to have a table with x and y fields. Then, replace database credentials with your own.
References
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://api.jquery.com/jquery.ajax/
Live demo
http://shrt.tf/coordinates
Note
This one does not check for types (you can input any String), but you can add that.
test.php
<?php
// Replace these parameters to match your database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'mydatabase';
$table = 'coordinatesTable';
// Connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// If parameters are received
if(isset($_POST['x']) && isset($_POST['y'])){
$error_messages = array();
if ($mysqli->connect_errno) {
$error_messages[] = "Couldn't connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Prepare insert
if (!($stmt = $mysqli->prepare("INSERT INTO `$table` (x,y) VALUES (?,?)"))) {
$error_messages[] = "Couldn't prepare statement: (" . $mysqli->errno . ") " . $mysqli->error;
}
// Bind parameters x and y
if (!$stmt->bind_param("dd", $_POST['x'], $_POST['y'])) {
$error_messages[] = "Couldn't bind parameters: (" . $stmt->errno . ") " . $stmt->error;
}
// Execute the insert
if (!$stmt->execute()) {
$error_messages[] = "Couldn't execute the query: (" . $stmt->errno . ") " . $stmt->error;
}
// Prepare some data to return to the client (browser)
$result = array(
'success' => count($error_messages) == 0,
'messages' => $error_messages
);
$stmt->close();
// Send it
echo json_encode($result);
// Exit (do not execute the code below this line)
exit();
} // end if
// Fetch all the coordinates to display them in the page
$res = $mysqli->query("SELECT x,y FROM `$table`");
$rows = array();
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
$mysqli->close();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test page</title>
<style>
table{ border-collapse: collapse; }
th,td{ border: 1px solid #888; padding: .3em 2em; }
</style>
</head>
<body>
<h1>New coordinates</h1>
<p>
x: <input type="text" id="x">
y: <input type="text" id="y">
<button id="addBtn">Add</button>
</p>
<table id="coordinates">
<tr>
<th>x</th>
<th>y</th>
</tr>
<?php
if(count($rows)){
foreach($rows as $row){
?>
<tr>
<td><?=$row['x']?></td>
<td><?=$row['y']?></td>
</tr>
<?php
}
}
?>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function(){
$('#addBtn').click(postCoordinates);
function postCoordinates(){
var x = $('#x').val(),
y = $('#y').val();
if(x.length && y.length){
// Change this if it is on a different page
var url = window.location.href;
$.ajax({
'url': url,
'method': 'post',
'data': {'x': x, 'y': y},
'dataType': 'json', // The server will return json
'success': function(res){
if(res.hasOwnProperty('success') && res.success){
$('#x, #y').val(''); // Empty the inputs
$('#coordinates').append('<tr><td>'+x+'</td><td>'+y+'</td></tr>');
} else if(res.hasOwnProperty('messages')) {
alert( res.messages.join('\n') );
}
},
'error': function(x, s, e){
alert( 'Error\n' + s + '\n' + e );
}
});
} else {
alert('You need to provide x and y coordinates');
}
}
});
</script>
</body>
</html>
Search for ajax. Send the data from client side to server side:
For example:
$('selector').on('click', function(){
var coordinates = [x,y];
$.ajax({
method: 'POST',
url: 'yourURL',
data: {coordinates: coordinates},
success: function(response){
Console.log(response);
}
});
});
In PHP:
$coor = $_POST['coordinates'];
echo $coor;
//Search the manual of php for storing it in the database
NOTE: Don't use mysql because it is deprecated, use mysqli or PDO.
Related
Here is my situation:
I have a JS function that creates an XMLHttpRequest object. The request is opened, and I'm calling the "GET" method on a specified url. The request works, as in it gets to the url destination and executes the code in the destination, but I'm not sure how to access a variable in the destination code.
Here's what I've got:
JS:
function fillTestsTable()
{
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open("GET", "./db-queries/get-tests.php");
xhr.send(null);
}
PHP destination file:
<?php
$conn = mysqli_connect("localhost:3306" , "exampre2_tplugin" , ",Vyml.F!#(}{" , "exampre2_totaltoefltimeplugin");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$sql = "SELECT * FROM TOEFLTESTS";
$result = mysqli_query($conn, $sql);
//return $result;
?>
What I am trying to do is return the data in the $result variable in the php. Is there a way of doing this?
In PHP, return is used to return a value from the current function to where that function was called.
To output data in the HTTP response use echo or print.
Note that mysqli_query returns a mysqli_result object so you will need to extact the data you want from that (e.g. with fetch_array) and then convert it to a suitable text format (e.g. with json_encode).
For example: if you wanted to return JSON formatted data for your Ajax callback function to play with you might do something like this:
<?php
$conn = mysqli_connect("localhost:3306" , "exampre2_tplugin" , ",Vyml.F!#(}{" , "exampre2_totaltoefltimeplugin");
$data=[]; //store recordset here
$sql = "SELECT * FROM TOEFLTESTS";
$result = mysqli_query($conn, $sql);
if( $result ){ /* iterate through the recordset, add each row to output data */
while( $rs=$result->fetch_object() ){
$data[]=$rs;
}
}
/* send data back to the ajax callback function */
exit( json_encode( $data ) );
?>
There are many ways you could proceed with this but it helps to clearly define the purpose and identify how your app is to work. The callback will then manipulate the response data to add new rows to your HTML table. Knowing what the callback is to do will generally ( or can ) affect the format of data you return - in your case if it is simply to be new rows in an HTML table it would be better to format the data server-side as HTML and send back raw html text.
Using Ajax allows your app to request data of whatever sort without the need to reload the page ( usually a traditional form submission )
As a basic example of populating an HTML table following a basic ajax request ( POST rather than GET but would work the same )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'maps';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
ob_clean();
$sql='select `name`,`address`,`lat`,`lng` from `maps` limit 10';
$res=$db->query( $sql );
while( $rs=$res->fetch_object() ){
printf('
<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>',
$rs->name,
$rs->address,
$rs->lat,
$rs->lng
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Ajax: fetch data from db - add to table</title>
<script>
const ajax=function(url,params,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
};
</script>
</head>
<body>
<input type='button' value='Fetch Data' />
<table></table>
</body>
<script>
document.querySelector('input[type="button"]').onclick=function(e){
ajax( location.href, false, function(r){
this.innerHTML=r
}.bind( e.target.nextElementSibling ))
}
</script>
</html>
I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("#Submit").click(function (e) {
e.preventDefault();
if($("#Text1").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "ajax.php",
dataType:"text",
data:myData,
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
$("#mytable").append(row_data);
$("#responds").append(response);
$("#Text1").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$('table').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
alert(thrownError);
}
});
});
});
</script>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test_database";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully";
if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0)
{
$contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");
if($insert_row)
{
$mysqli->close(); //close db connection
}else{
header('ERROR');
exit();
}}
?>
<div class="form_style">
<textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
<button id="Submit">Add record</button>
</div><br>
<table class="table" id="mytable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
//initially filling the table with db data
<?php
$sql = "SELECT fname, lname, age FROM test_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
</table>
</body>
</html>
The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data
if you want to use php code in javascript then try below ==>
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";
The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.
In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.
Proper usage of the AJAX would be like this:
$.ajax({
// ...
dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
success: function (data) { // data will be an object already parsed from JSON string sent by server.
var row_data = "";
row_data += "<tr><td>";
row_data += data.txt1;
row_data += "</td><td>";
row_data += data.txt2;
row_data += "</td><td>";
row_data += data.txt3;
row_data += "</td></tr>";
}
});
Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:
header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => #$_POST['txt2'], 'txt3' => #$_POST['txt3']);
die();
This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.
You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.
I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().
SOLUTION: After a teamviewer session with #skobaljic he figured out that I was not actually opening the html in localhost but using the file system (as in file://...). I apologize for wasting everyone's time like that.
I am trying to send some php arrays through Ajax and print them out and despite getting a 200 OK response, there is no actual effect in the received html. The status text says "parsererror".
The files are the following:
<!DOCTYPE html>
<html>
<head>
<title>Page Title Woo!</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
<ul></ul>
<script type='text/javascript'>
$(document).ready(function(){
$.getJSON('DbGetter.php', function(data) {
console.log(data);
$.each(data, function(key, array) {
$('ul').append('<li id="' + key + '">'
+ array.longitude + ' '
+ array.latitude + '</li>');
});
})
.fail(function(error) {
console.log(error);
});
});
</script>
</body>
</html>
and the php:
<?php
$servername = "localhost";
$username = "testuser";
$password = "password";
$dbname = "Locations";
header('Content-Type: application/json');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM places";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//declare associative array
$array = array();
$num = 0;
// output data of each row
while($row = $result->fetch_assoc()) {
//store them in an array
$place = array(
'id' => $row["id"],
'latitude'=> $row["latitude"] ,
'longitude'=> $row["longitude"],
'place_name' => $row["place_name"],
'country_code'=> $row["country_code"],
'postal_code'=> $row["postal_code"]);
/*
echo "Coordinates: " . $row["latitude"]. " " . $row["longitude"]. " - Name: " . $row["place_name"]. " " . "<br>";
*/
//building the second associative array
$array[$num] = $place;
$num += 1;
}
echo json_encode($array);
} else {
echo json_encode("0 results");
}
$conn->close();
?>
I've tried looking at the value through firebug, but either I'm blind or it's just not stored anywhere in the DOM. I'm pretty new to web application in general so I don't know how to go about debugging it.
Running the php by itself I get: [{"id":"1","latitude":"57.0502","longitude":"9.9173","place_name":"1000fryd","country_code":"DK","postal_code":"9000"},{"id":"2","latitude":"58.0502","longitude":"10.9173","place_name":"same_place","country_code":"DK","postal_code":"9000"}]
Which are the 2 rows I expect.
There is also no XHR request marked by Firebug.
You're not encoding valid JSON here.. This will give you a "parseerror" if you try using JQuery's $getJSON with it. Notice the JQuery Ajax Source from lines 275-281.
echo json_encode("0 results");
You could probably change it to something like:
echo json_encode(["0 results"]);
You are using $.getJSON method, so the data is already parsed correctly. In case you do not get the JSON it would trigger fail.
So, just remove:
try { JSON.parse(data); } catch (e) { console.log('Not JSon') }
Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>