Pass data from mysqli to javascript - javascript

I want to pass the results of a query to javascript (I want to make an interactive quiz about fish species). This seems to be easy with json_encode, but the structure of my php array makes it difficult to access? Even console.log does not work, so there is probably an error, though I have been checking this code more than i would like to admit. I am pretty sure the error is in the small javascript part though. The code (this is all in a .php file):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<?php
$con = new mysqli("localhost", "root", "", "marinefish");
$query = "SELECT Commonname, Scientificname FROM allseafish";
$result = $con->query($query);
while ($row = $result->fetch_array()){
$rows[] = $row;
}
/*
Structure rows:
array(544) {
[0]=>
array(4) {
[0]=>
string(7) "Allfish"
["Commonname"]=>
string(7) "Allfish"
[1]=>
string(11) "Omni pisces"
["Scientificname"]=>
string(11) "Omni pisces"
}
*/
mysqli_free_result($result);
mysqli_close($con);
?>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript">
var ars = <?php echo json_encode($rows) ?>;
console.log(ars);
alert(ars[0][0]);
</script>
</body>
</html>
Any suggestions, or easy-to-understand links/ tutorials are very welcome!
I tried: http://www.dyn-web.com/tutorials/php-js/json/multidim-arrays.php which seems very clearly explained, but couldn't help me. I also have tried to simplify the structure of the php array, but without success.
And I tried to change the echo json_encode($rows) into print(json_encode($rows)).
As you may have noticed, I am new with this, so all basic tips will be a great help.
Thank you!

A better solution would be to separate your javascript from PHP through post/get requests by creating a new PHP page (e.g. Query.php) that is specific for Database response:
... MYSQL CODE ...
echo json_encode($rows); // Echo everything into body
And Using jQuery (or equivalent Ajax request):
$.ajax({
type: "GET",
url: 'query.php',
dataType: "json",
success: function(your_php_reponse_as_json){
console.log(your_php_reponse_as_json);
}
});
Note that this code will be essentially asynchronous as the request for the MYSQL Query is sent in another page using async JavaScript. Additionally you can customize your query reponse with $_POST & $_GET:
PHP Code:
$get1 = $_GET['js_sent'];
// Alternatively
$post1 = $_POST['js_sent'];
Edit: You'll need to serialized data before sending.
For the complete jQuery solution refer here jQuery Ajax POST example with PHP

$.post("checkproduct.php", {"useremail" : emailVal}, function(data) {
//use data returned from checkproduct.php.the value returned from checkemail.php is retrieved as data.
});
The above code post method to post variable to checkproduct.php here we are passing useremail and the value is emailVal and this is also a variable. and in checkproduct.php you need to echo/return your result. and resultant data can be use in the function as data

Related

Unknown problem with (probably) POST method

This task is quite simple but I just can't seem to get it to work. What the outcome should be is explained in the picture below. I guess that there is some kind of a problem with POST in php, but I'm not sure. Do you see what's the problem that's causing this not to work?
Problem: No results are shown when there should be.
<?php
$conn = mysqli_connect("localhost", "root", "", "podaci");
if($conn === false){
die("Konekcija nije uspešna. " . mysqli_connect_error());
}
$number = $_POST['number'];
$result_array = array();
/* SQL query to get results from database */
$sql = "SELECT brojKartice, imeVlasnika, prezimeVlasnika, adresaVlasnika,
ostvareniBodovi, ostvareniPopust FROM podatak WHERE brojKartice = '".$number."' ";
$result = $conn->query($sql);
/* If there are results from database push to result array */
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
/* send a JSON encded array to client */
echo json_encode($result_array);
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
</head>
<body>
<div class = "container" >
<strong>Unesite broj kartice: </strong><input id="number" name="number" required/>
<input type="button" id="getusers" value="Provera"/> <br><br>
<div id="records"></div>
</div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#getusers').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'provera.php',
data: {
number: $('#number').val()
}
});
});
});
$(function(){
$("#getusers").on('click', function(){
$.ajax({
method: "GET",
url: "provera.php",
}).done(function( data ) {
var result= $.parseJSON(data);
var string='<table width="100%"><tr><th>#</th><th>Korisnik</th><th>Adresa</th><th>Bodovi</th><th>Popust</th><tr>';
/* from result create a string of data and append to the div */
$.each( result, function( key, value ) {
string += "<tr> <td>"+value['brojKartice'] + "</td><td>"+value['imeVlasnika']+' '+value['prezimeVlasnika']
+ "</td><td>"+value['adresaVlasnika']+ "</td><td>"+value['ostvareniBodovi']+ "</td><td>"
+value['ostvareniPopust']+"</td> </tr>";
});
string += '</table>';
$("#records").html(string);
});
});
});
</script>
</body>
</html>
CREATE DATABASE podaci;
CREATE TABLE podatak (
brojKartice VARCHAR(10) NOT NULL,
imeVlasnika VARCHAR(20) NOT NULL,
prezimeVlasnika VARCHAR(30) NOT NULL,
adresaVlasnika VARCHAR(50),
ostvareniBodovi VARCHAR(10) NOT NULL,
ostvareniPopust VARCHAR(10) NOT NULL,
rokVazenja DATE NOT NULL
);
INSERT INTO podatak VALUES
('0123456','Đorđe','Anđelković',NULL,'15','150','2021-1-9'),
('6543210','Snežana','Bojović',NULL,'20','200','2021-5-3'),
('9876543','Goran','Stojadinović',NULL,'10','100','2021-9-7'),
('3456789','Bojana','Marković',NULL,'25','250','2021-12-15');
Welcome. Here are a few pointers to help you identify the source of the issue:
Is your browser making the HTTP requests that you expect? By glancing at your Javascript, you expect both a POST and a GET. If you are using Google Chrome, check Dev tools - Network
What HTTP requests is the server receiving? You can debug your PHP code by following the official debugging documentation and reading its comments. Especially:
<?php print_r($_POST); ?>
Is the server answering the data you are expecting? Check the HTTP verb (GET or POST) used to get the number (hint: line 8 of your code). Now check on which HTTP call (GET or POST) you put the Javascript callback to handle the server response.
Answer: your PHP code reads the number from the POST request, but your Javascript code only supports responses from the GET request.
Simplify your Javascript by moving the callback (the function block passed as argument of the .done() method) from the GET request to the POST request. Then delete the Javascript code dealing with the GET request.
Alternatively, replace $_POST with $_GET and remove the POST call.
First of all, you have two event handler for #getusers button. This doesn't make sense in the first place. Whenever you assign multiple event handler on a html element only the last one will trigger. In this case, it's only the ajax call with the GET method. And on your server side (php), this variable $number = $_POST['number']; will not have a value because the method was GET.
So to solve this you have two options I can think of:
#1. Move the first ajax call that you have where you have the POST request and then place it where you have the ajax call with GET method. In short, replace GET with POST event.
#2. Change your php code to use $_GET and update your ajax call for GET to adhere with the PHP change.
You can remove either of the event handler of your button and just bind only one.
Here is for a quick reference on javascript event handler and addEventListeners: https://gist.github.com/belmer/5e433aabbab24086af5c12ce0fb7323c
Best regards,

how to send POST data with jquery ajax to PHP function

I want to send POST request with jquery AJAX to PHP function
but it don't give any respond.
JQuery
$.ajax({
url: 'ListProduk.php/SelectData',
type: 'POST',
success: function(data)
{
console.log(data);
}
});
PHP
<?php
include 'database.php';
function SelectData(){
$sql = "SELECT * FROM MsProduk";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
return json_encode($arr);
}
?>
Any ideas how to fix it?
When not using url rewriting (google mod_rewrite and pretty URL's), your parameters typically are going to be passed as a normal HTTP GET request. Here is an example of how your URL structure might look:
url: 'ListProduk.php?action=SelectData'
And then, in your PHP, you might handle it based on the action that is requested (Note: The action parameter is not something specific to web development, it's just an arbitrary name I assigned. It could be foo=SelectData as well)
if ($_POST['action'] == 'SelectData') {
// Run the code for selecting data
}
Finally, you wouldn't want to "return" the JSON data. You need to output it with the correct headers. It would look something like this:
header('Content-Type: application/json');
echo json_encode($data);

Echo php content into API javascript?

I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Trouble getting getJSON to work with codeigniter

I am trying to use getJSON so I can grab the latest information from my database. What I have done so far is store it into a array and json_encode(the array). That works because I can see the information on the view, but the issue is the ajax method does not pick it up. Maybe i am missing something really stupid.
Controller:
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arr = array();
foreach($queryresults as $row)
{
$arr[] = $row->postcode;
}
$data['arr'] = $arr;
echo json_encode($arr);
$this->load->view('answer', $data);
}
View:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
<script>
$.post('/localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
alert(data);
});
</script>
</script>
</head>
<body>
</body>
</html>
Var Dump of the $arr variable:
array(4) {
[0]=>
string(5) "test1"
[1]=>
string(5) "test2."
[2]=>
string(5) "test3"
[3]=>
string(5) "test4"
}
You are sending the $data array (which contains the $arr) to the view by calling it ( $this->load->view('answer', $data); ) and just right before it you echo the JSON data.
So what you do is call a view which on the top of it, before any html or javascript has a plain text containing the json encoded $arr.
This is obviously wrong and not what you are looking for.
You should do either of these options:
echo the $arr at the view, at the <head> section inside <script>
tags. You would not have to use AJAX call though.
just echo the
$arr at the controller but do not call a view after it. You should
probably make another Controller for this. One to echo the $arr and
one to call the View. This way you can do an AJAX call to the first
Controller.
pass the $arr to a view which will just echo the JSON encoded data.
This is like option #2 but it uses the View in order to show the
data and not the Controller, which is the most appropriate way to follow the MVC pattern.
Controllers should not echo anything.
I suggest to follow option #3.
So. if you want to echo out a JSON obj that can be pick it up using ajax, then u need to make sure that the output mime-type of your page can serve JSON data.
also notice that u cannt echo anything else with the json data that u want out of ur function. as i can see in your code u echo json then load a view ! u need to split that into 2 separate pages
Fix:
public function _JSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arr = array();
foreach($queryresults as $row)
{
$arr[] = $row->postcode;
}
return $arr;
}
public function json_body(){
$this->load->view('answer',array('data'=>$this->_JSON()));
}
public function getJSON(){
$this->output
->set_content_type('application/json')
->set_output(json_encode($this->_JSON()));
}
///note that $this->_JSON() now return ur $arr so u can use it in many methods.
now to load page u can go to /json_body 'rename it as u want'
and js should be
<script>
$.post('<?=base_url('welcome/getJSON')?>', function(data) {
alert(data);
});
</script>
<!--notice that base_url show echo out ur url base on ur config.php file-->
NOTE:
function getJson get use the power of CI Output class to set the mime-type of page and make sure this array is the only output. this is not a must but its just best practice. if u want u can relapce all 3 lines with simple echo json_encode($this->_JSON()); and it will work too !
I guess the problem is your post URL:
$.post('//localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
alert(data);
});
you missed double slash (//)

Categories

Resources