Unknown problem with (probably) POST method - javascript

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,

Related

PHP Undefined POST variables and unable to execute INSERT function [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Sql queries doesnt work when inside a php function

So the main problem is, when i make some query just after a post[] or whatever and its just in the main code of the php (not in a function) it works perfectly fine..
But, when i try and have that query inside a php function,it never works, and kinda hiding any other code on the rest of the page... I have a few divs after that php and sql query code, and they just dont show when i try to query through the function..
<script type="text/javascript">
function callPhpVoteAdd(name) {
var result = <?php voteAdd(name); ?>;
alert(result);
return false;
}
</script>
<?php
echo '</br>';
$allsql = "SELECT * FROM voting ORDER BY votes DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo '<form method="post">
name: "' .$name. '" - votes: "' .$votes. '" <input type="submit" name="'.$name.'" value="'.$name.'" onclick="callPhpVoteAdd(this.name)"/><br>
</form>';
}
}
function voteAdd($name) {
if($conn->query("UPDATE voting SET votes = votes + 1 WHERE name = '".$name."' ") === TRUE) {
echo "<script>alert('fuck yeah');</script>";
}
echo "shit";
}
So the button pressed calls the js function, which calls the php function
I guess you're misunderstanding the way JS and PHP works. PHP works server side, and JS, in your case, client side. And so, PHP generate the script/page before it's sent to the browser, so when JS runs it, all the <?php ?> are already replaced by static data.
So, to put it shortly and simply, you just can't call a PHP function from JS after your page is loaded, the way you tried to (because the call isn't there anymore - check your source code from your browser).
You need either to :
use a form with an "action" attribute ; this will send the data to server, and call the php script set in "action", where you can handle the sent data, and then reload the page with the new/updated data,
use ajax (almost the same thing : this sends data to server and call a php script to handle them, but instead of reloading the page, the output of the PHP script - with the data you need - will be sent back to JS, to a callback function, where you'll be able to use them to modify the page).

jquery / ajax to run php query using user input as criteria, then display query result without page refresh

I've spent the last 24 hours trying to find an answer, and while there are similar questions, the answers seem to be either more complicated than my use-case (so I don't understand it), or I find low-quality questions/answers.
My title really says it all, except for my code, but to reiterate in full sentences: I know how to update mysql database fields with user input and php using jquery. Separately, I know how to retrieve php query results using ajax. What I can't figure out is how to do both these things at the same time: Use ajax to set user input as a parameter of a php query, then also pull the results of that query.
I thought it was going to be simple once I figured these things out separately, but I just don't understand .ajax() well enough at all, and that's why I'm here.
Here is my code:
User Input Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pull from query</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<style>
#topRow {
margin-top:40px;
text-align:center;
}
</style>
</head>
<body>
<div class="container contentContainer" id="topContainer">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="topRow">
<textarea class="form-control"></textarea>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3" id="output" style="border:1px solid #000000;height:40px;margin-top:40px;text-align:center;">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
// "keyup" RUNS FUNCTION EVERY TIME USER USES KEYBOARD
$("textarea").keyup(function() {
$('#output').html("loading...");
var email = $('textarea').val();
$.post("5Query.php", {email:$('textarea').val()} );
// ACCESS QUERY RESULTS (HOPEFULLY!)
$.ajax({
url: '5Query.php',
dataType: 'json',
success: function(data)
{
var result = data
$('#output').html(result);
}
});
})
</script>
</body>
</html>
PHP Query in separate file
<?php
// SET DATABASE LINK AS A VARIABLE THAT CAN BE USED WHEN RUNNING QUERIES
$link = mysqli_connect(...connection stuff...);
if (mysqli_connect_error()) {
die("Could not connect");
}
// SELECT all fields FROM databasename
$query = "SELECT * FROM users WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
// CREATE ARRAY CONTAINING ALL VALUES FOR ROW MATCHING QUERY CRITERIA
$row = mysqli_fetch_array(mysqli_query($link, $query));
$name = $row['name'];
$error = 'I could not find that user name';
//echo json_encode($row);
if($row){
echo json_encode($name);
} else {
echo json_encode($error);
}
?>
As you can see, I tried using $.post() to set the query parameter, since that is the only way I know how, but it does return any results. When I hard-code a value into the php query that I know is in the mysql db table, rather than trying to post user input to the query, it correctly returns and displays the query result.
I'm hoping that some of you smart people can spot something obvious that a novice like me wouldn't see... I definitely feel like everything should take place within .ajax(), but I just don't know how to do it, and it's weirdly difficult to find the answer anywhere.
Please let me know how to improve my question, or where I might find an answer (although keep in mind that I'm a super-novice with ajax, so it's entirely possible that I may have seen an answer and just did not know what I was looking at).
remove the $.post then change ajax like this
$.ajax({
url: '5Query.php',
type: 'post',
dataType: 'json',
data: {
email: $('textarea').val()
},
success: function(data) {
var result = data
$('#output').html(result);
}
});
In php page you can access that variable like this $_POST['email']
You don't need both $.post and $.ajax. Use one of them
$.post("5Query.php", {email:$('textarea').val()}, function(result){ $('#output').html(result); }); //added callback function that will handle response
or you can use $.ajax()
// ACCESS QUERY RESULTS (HOPEFULLY!)
$.ajax({
url: '5Query.php',
data : { email: $('textarea').val() },
success: function(data)
{
var result = data
$('#output').html(result);
}
});
As you are return only string so you don't need to json_encode (if you want to return multiple records then you have to use it and you have to change your ajax success function accordingly.
Change these line in php code
if($row){
echo $name;
} else {
echo $error;
}

Pass data from mysqli to 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

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

Categories

Resources