pass data from mysql to javascript - javascript

Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.
Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?
admin.php
<?php
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
echo json_encode($data);
?><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
What I've tried
js/admin.js
$(document).ready(function() {
$.ajax({
url: '../admin.php',
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
})
});
I received a "404 Not found" error in the console

The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.
Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
<? } ?>
Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.
To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.

Related

JSON data not populating bootstrap table properly

Been trying to get a work around for this for hours now, but I just can't get my bootstrap table to being populated in a correct way. Here is my HTML:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="https://v40.pingendo.com/assets/bootstrap/bootstrap-4.0.0-beta.1.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.css" type="text/css">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.js"></script>
<script src="client.js"></script>
<table class="table" id="maintable">
<thead>
<tr>
<th data-field="queue">#</th>
<th data-field="nation_name">Nation</th>
</tr>
</thead>
</table>
</body>
</html>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$con = mysqli_connect('localhost','root','','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql = "SELECT queue, nation_name FROM nations WHERE queue IS NOT NULL ORDER BY queue ASC";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo json_encode($row);
}
} else {
echo "0 results";
}
mysqli_close($con);
?>
JS:
url = "ws://localhost:8080";
ws = new WebSocket(url);
// event emmited when connected
ws.onopen = function () {
console.log('websocket is connected ...');
// sending a send event to websocket server
ws.send('connected');
}
// event emmited when receiving message
ws.onmessage = function (ev) {
console.log(ev.data);
}
$.ajax({
type: 'POST',
url: 'getqueue.php',
data: {},
success: function(response) {
alert(response);
$(function () {
$('#maintable').bootstrapTable({
data: response
});
});
},
error: function() {
//something
}
})
The JSON data that is sent to the page from PHP looks exactly like this:
{"queue":"1","nation_name":"Afghanistan"}{"queue":"2","nation_name":"Sweden"}
But when the page is loaded this is the result:
Screenshot
Why is the JSON data not being populated the way I want it? Ie, two rows containing 'queue' and 'nation_name'
The issue is this code returning multiple JSON strings in one:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo json_encode($row);
}
}
Instead you need to build one JSON string as an array of rows, and return it:
if (mysqli_num_rows($result) > 0) {
$output = array();
while($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
echo json_encode($output);
}
The fix to your next problem is that you are not using the bootstrap library correctly. You must set columns and tell it what fields to use or else it has no idea what to put where. Fix what #Matt S told you to do for the PHP side, then make my edits for the client side. (I'll make an edit in his answer that he can peer review if he wants). On top of setting the columns you can actually get rid of your ajax request entirely as bootstrapTable supports giving it a url directly.
$('#table').bootstrapTable({
url: 'getqueue.php',
columns: [{
field: 'queue',
title: '#'
}, {
field: 'nation_name',
title: 'Nation'
}]
});

Connecting to database via PHP and displaying contents on browser

I am connecting to an SQL server via PHP script and displaying the contents retrieved on the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
All 3 files are in the same folder.
The browser just displays a null and I don't hit any of the logging information from the .php file. Is my method right? Am I using the right javascript event?
Change your connection.php in this way:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
You need to change mime type of your response. Moreover you cannot print out anything else than json data. That's way I removed from your code these lines:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
Try using a relative pathname for connection.php here: d3.json("connection.php"
Something like "/dirname/connection.php".
You can test connection.php alone using a full pathname, like http://www.yourserver.xxx/dirname1/dirname2/...connection.php

Populate a dynamic dropdown based on value inserted in the text-box

Please someone help, I am really going to be crazy!.
I have a PHP form with some questions and one of the question is "Which are your favourite movies?" for which I used jQuery auto-complete feature which works fine!. However, It is possible that users forget the name of a movie, but remember an actor that played in that movie. So, I would like to enable user typing an actor/actress name in the auto-complete textbox (e.g., "Tom Cruise") and based on inserted actor name, a dynamic dropdown menu should be added which contains list of movies that the actor (e.g, Tom Cruise) has played in them.
This is what I tried but not work :((
<html>
<?php
print_r($_POST);
?>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
</head>
<body>
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php", //php file which fetch actors name from DB
minLength: 2,
select: function (event, ui){
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
}
});
});
</script>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
include('Connection.php'); //connection to the DB
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $q));
$html = "";
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $row->movieImdbId . '">' . $row->movieImdbId . '</option>';
$html .= $option;
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
Question: Why when user insert an actor name in the text-box, the dropdown menu is populated but is EMPTY?
In your ajax call, you send a POST request, and you try to get the params with $_GET in you php.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags.
$("#movieImdbId").html(response).show();
});
change the $.post method to $.get.
OR
if(isset($_GET['q']) && !empty($_GET['q'])){
$q = $_GET['q'];
}
change $_GET to $_POST.

PHP SQL Query to Select Tag

I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);

How to read data from database with json PHP JQUERY Ajax?

Im trying to read data from mysql database and pass it to my javascript file.
I have search alot on internet and have found examples that doesnt work in my case.
.html file
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('#getdata').click(function(){
alert("hello");
$.ajax({
url: 'db.php',
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
and .php file
<?php
echo 'hello';
$user = 'root';
$pass = '123';
$host = 'localhost';
$db = 'internetProgrammeringProj';
$connect = mysql_connect($host,$user,$pass);
$select = mysql_select_db($db,$connect);
$query = $_POST['query'];
$mysql_query = mysql_query("SELECT * FROM ratt ");
$temp = "";
$i = 0;
while($row = mysql_fletch_assoc($mysql_query)){
$temp = $row['id'];
$temp .= $row['namn'];
$temp .= $row['typ'];
$temp .= $row['url'];
$temp .= $row['forberedelse'];
$array[i] = $temp;
$i++;
}
echo json_encode($array);
?>
alert(xhr.statusText); gives parsererror
and
alert(thrownError); gives SyntaxError: JSON.parse: unexpected character
firebug doesnt display any error in console.
QUESTION: How do i get my program to get the content from the database and pass it with json to display it with alert in ajax?
I just successfully ran this code.
All I had to do is remove the echo "hello" at the beginning which messes up your JSON.
Some more tips you can use for future development:
Don't use alert('message'). Use console.log('message'). You can view the output of console.log in "Developer's Area". In chrome you simply press F12. I think that in FF you need to install firebug or something.
output_string in function success is actually an object.
The "Developer's Area" in chrome also lets you see the response from backend. If you have used it you could have seen your output is hello{ "key":"value"} and immediately notice the nasty hello in the beginning. Read more about it at http://wiki.mograbi.info/developers-tools-for-web-development

Categories

Resources