Cannot use echo after connection to database - javascript

I'm using ajax to send a request to php with some text.
$.get("process.php", { finalQuery : finalQuery }, function(data) {
alert("Data Loaded: " + data);
});
I know this works because in php I can put
$val = $_GET['finalQuery']; echo $val;
And it outputs the correct data.
However, if I put
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
pg_close($db);
It stops echoing the results back to javascript. If I use a different port or name, and it doesn't connect, it then goes back to sending the data to javascript and outputting the correct data.
So basically, when I connect to the database, I cannot communicate my results back with echo. What am I doing wrong?
EDIT(update):
Here's the complete php code
<?php
$val = $_GET['finalQuery'];
echo $val;
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
$result = pg_query($db, 'SELECT gid FROM "Perfect"');
while ($row = pg_fetch_row($result)) {
echo "gid: $row[0]";
echo "<br />\n";
}
pg_close($db);
?>
However, the problem still occurs as long as I use pg_connect. All the other lines can be removed and the problem persists. As long as I remove the pg_connect, the problem disappears and I can send the information back through echo
NEW EDIT(debugging) :
The connection to the database and the php code seems ok. After loading the php page with
error_reporting(-1);
ini_set('display_errors', 'On');
no errors are logged on the page, and the connection to the database is returning all the data properly on every page load.
The problem arises when I'm trying to connect to the php through javascript.
The page loads the data properly sometimes, but it's random, and most of the time nothing happens (not even php logged errors). If you there's no way the javascript-php connection isn't the problem then I'll keep debugging the code.

Here's the steps I'd take for debug:
Begin by ensuring the DB is running and that you can send it a query
successfully via console window DB GUI Tool (Navicat is my gui of
choice for DB's)
Load the PHP page directly. Check for output of
expected code or fatal PHP Errors
Check the browser console for errors. Since it appears to be a PHP
only page, this should be entirely clear of problems.
Check PHP logs
Check Postgres logs
More than likely, something between Postgres and PHP is the problem. Post any errors back on your question if you're still stuck after finding a clue.

Related

automatically load dynamic content with ajax and php

I have a PHP chat application that automatically get messages from database and displays it, currently everything works fine but page must be manually reloaded to display new messages .. How do I implement JQuery ajax to get the messages or silently refresh the specific messages list div without refreshing the whole page? Here is my code (not the full code on the page but the main PHP part I want to use ajax on)
Some answers I read online specified that the PHP code must be on a separate file but Some of the functions and variables in the code below depends on the main file holding this code therefore making it useless if put in a separate file.
<?php
// Attempt select query execution
global $db;
$id = $_GET["id"];
$sql = "SELECT * FROM msg WHERE id='$id' ";
if ($result = $db->query($sql)) {
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo '<div class="chat-messages-item ' . chattype($row['sender']) . '">';
echo '<div class="chat-avatar chat-avatar-lg circle"><img src="' . senderpic($row['sender'], 'thumbnail', '100', '100') . '" alt=""></div>';
echo '<div class="chat-messages-content">';
echo '<div class="chat-messages-bubble ' . $msg_visibility . '">';
echo '<p>' . $row['message'] . '</p>';
echo '</div>';
echo '<ul class="chat-messages-info">';
echo '<li>';
echo '<div class="chat-time chat-seen"><span>' . $row["time"] . '</span>';
echo '</li>';
echo '</ul>';
echo '</div>';
echo '</div>';
}
unset($result);
} else {
echo "<p class='lead'><em>No Chat</em></p>";
}
} else {
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
Thanks
[EDIT]
What i've tried :
1. Moving the code above into a separate PHP file and using jquery to to get the page with the following js code but nothing appears and no errors displayed. if i open the page in browser it displays the list of all messages
function update() {
$.get("aj/messages.php", function(data) {
$("#allmessages").html(data);
window.setTimeout(update, 10000);
});
}
here is the page structure
- Message.php (the main message page that displays other chat information like contacts, messages list, messages, send message input etc)
aj/msg.php (a php page that gets all the messages from database and wraps it in style/css/html which is also the php code above and expected to be inside a div with the id="allmessages" located inside Message.php)
As you mentioned, it is a good practice to separate your PHP Code and your HTML/JavaScript Code. Yes, this may mean you have to write more PHP Code, yet if PHP Scripts must use the same code snippet, this is where PHP include and include_once can be used so that you can store specific functions in one script and them import them to other scripts. Please see:
https://www.php.net/manual/en/function.include.php
Currently, there is not enough of an example to be able to properly answer your question. I would suggest that you either create a more functional PHP Script that can accept new Chat input or another that can show the current chat transcript from the Database.
In this use case, each member of the chat must send new data to the database and then periodically get/refresh their view of the transcript. You can send new data to the database at any time and then based on a specific refresh rate, look for differences in the transcript. So your JavaScript will have a few function. Something like
startChat()
sendMessage()
getMessages()
endChat()
These will send data to the PHP Script and the PHP Script may give a response. This can all be done with AJAX. AJAX is the use of HTTP GET or POST along with JavaScript. This is basically how a Client Side Script language like JavaScript can talk to a Server Side Scripting language like PHP. PHP is processed when the HTTP request is handled by the Web Server and once the data is sent to the browser, PHP can no longer interact with it, this is why it's a pre-processor. JavaScript can only run in the browser and is processed after all the data from the server is received by the browser.
So if you have some HTML like:
<div class="chat-window">
<div class="transcript">
</div>
<div class="user-input">
<input type="text" /> <button>Send</button>
</div>
</div>
You can use JavaScript to perform tasks when the User types in text and clicks the button. One of those tasks can be to collect the text entered by the User and send it to the PHP Script to be added to the Database. Another task can be to update the field if there are any new messages in the Database since the last time the script checked.
Using jQuery Framework for JavaScript, it might be something like:
function sendMessage(user, txt){
$.post("chat_input.php", { u: user, msg: txt });
}
This creates a HTTP POST call to a PHP Script with a payload of info, such as the User and some Text. You'll need to collect this information from the HTML based on a specific Event.
$(".user-input > button").click(function(){
sendMessage("jsmith", $(this).parent().find("input").val());
});
This bit of jQuery binds a anonymous function as a callback to the click event. When the User clicks the button, it runs that code in the function.
The PHP Code might be something like:
<?php
$user = $_POST['u'];
$txt = $_POST['msg'];
include_once 'db_conn.php';
$stmt = $mysqli->prepare("INSERT INTO 'chat' VALUES (?, ?)");
$stmt->bind_param("ss", $user, $txt);
$stmt->execute();
$stmt->close();
?>
As you can see, this is very rudimentary and will not answer your overall question. You must do a lot of research and I would advise you find example PHP/jQuery Chat example that you can learn from or begin taking some JavaScript/jQuery Tutorials.
See More:
https://api.jquery.com/jQuery.post/
https://api.jquery.com/click/
https://api.jquery.com/category/selectors/
Update
If your PHP Code is setup to collect some data and "send" it back to an AJAX script, then you would prepare it like any other PHP Page, and output the data to the page in some fashion.
<?php
$results = new array();
/* Assuming connection to DB */
/* Assuming SQL Query and result set is now in $results */
header('Content-Type: application/json');
echo json_encode($results);
?>
When you navigate to this page, you will see the collected data in JSON format. Something like:
[
{
"sender": "jsmith",
"message": "Hello World!",
"time": "12/27/2019 10:28:01"
},
{
"sender": "ssmith",
"message": "shut up john",
"time": "12/27/2019 10:28:12"
}
]
When AJAX sends a request to this script, it will get the data back and can then iterate each item in the array, create HTML for it as needed. You can use HTML or Text or XML too, I just use JSON when possible.
In jQuery, this function might look like:
function getMessages(){
var lastMessage = $(".chat-messages-item:last .chat-time").text().trim();
$.get("chatmessages.php", function(data){
$.each(data, function(i, msg){
if(lastMessage < msg.time){
var newMsg = $("<div>", {
class: "chat-messages-item " + chattype(msg.sender),
}).insertAfter($(".chat-messages-item:last"));
var av = $("<div>", {
class: "chat-avatar chat-avatar-lg circle"
}).appendTo(newMsg);
$("<img>", {
src: senderpic(msg.sender, 100, 100),
class: "thumbnail"
}).appendTo(av);
$("<div>", {
class: "chat-messages-content"
}).html("<p>" + msg.message + "</p>").appendTo(newMsg);
}
});
});
}
setTimeout(getMessages, 10000);
This is just an example based on your code.

Setting PHP Session variables with jQuery Ajax

I have a pretty simple issue which I just can't seem to resolve. I have the following ajax request which sets a PHP Session variable
$.post("http://mytestdomain.com/test.php", {"data": 'success'});
And this code in the PHP file to generate and echo the Session variables
session_start();
$_SESSION['test_text']= $_POST['data'];
echo "Pageviews=". $_SESSION['test_text'];
However this keeps returning the following error message
Notice: Undefined index: data in /var/www/test.php on line 2
If I post a demo URL into my browser like this
http://mytestdomain.com/test.php?data=11111
Then the results are echoed correctly.
So my question is, how do I pass via jQuery Ajax data to a PHP session variable and have it saved?
Thanks
In your test.php file, try the following:
session_start();
$_SESSION['test_text']= $_REQUEST['data'];
echo "Pageviews=". $_SESSION['test_text'];

Insert into MySQL database when user clicks on a Link

I am creating a website that has users log in and select a pdf document that they want to download. When they open up the document to view and possibly download, I want data to be logged into a database at the same time.
The code to send the data to the database works (Except for: Undefined index: learningMaterial). But when I want to have the pdf document open and at the same time log the user and other data, all that happens is the document opens up.
Any advice would be appreciated, even for overall better methods of going about what I'm trying to achieve here. Still inexperienced with PHP.
See code below.
HTML
<form name="myform" method='post' action="../includes/writeStats.php">
<input type='hidden' name='learningMaterial' id='learningMaterial' value='learningMaterial'>
<a href='../documents/test.pdf' id='mylink' class='courses' name='Driver Training'> Driver Training </a>
</form>
JS - In header
<script type="text/javascript">
function submitform(){
document.myform.submit(); }
var form = document.getElementById("myform");
document.getElementById("mylink").addEventListener("click", function () {
submitform();
});
</script>
PHP
<?php
$con=mysqli_connect("localhost","root","password","qmptest");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get latest log nr
$result = mysqli_query($con,"SELECT * FROM logbook ORDER BY log DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$log = $row['log'] + 1;
//If statement to check if log is 0(first entry) to go here
}
$date = date("Y/m/d");
session_start(); // Start a new session
$person = $_SESSION['currentUser'];
//Not sure if this is correct along with my HTML input
$material = mysqli_real_escape_string($con, $_POST['learningMaterial']);
//Insert into database
$sql="INSERT INTO logbook (log, date, person, learningMaterial)
VALUES ('$log', '$date', '$person', '$material')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Your way, clicking the link will override the form being submitted. This leads to the file opening and the form never going through.
Instead, you could try either opening the file in a new window by adding target="_blank" to the tag, or send the files URL through to the PHP, executing the database code then adding to the end:
header("Location: http://yourdomain.com/yourfile.pdf");
Your file is just a normal file being returned by your web server:
<a href='../documents/test.pdf' ...
So while you may be able to suggest to users or browsers that they should invoke some code before downloading this file, you can't actually require it. Any user can just request the file directly. And since PDF files don't execute PHP code (thankfully), your server-side PHP code has no way of knowing that the file has been requested.
What you can do is obscure the file itself behind a PHP request. You can create something like a download.php page which accepts the name of a file (test.pdf) and returns that file.
Be very careful when doing this. Don't just allow users to request any file and blindly return whatever they request. A user can request something like "../../../../../../../../../../etc/passwd" and if your code just builds a path and returns the file then you've just given users a sensitive file. It's best practice to keep a finite known list of identified files (perhaps in a database table) and let users request by the identifier rather than by the file path itself. That way the actual path is only ever known server-side in data that you control.
The main point here, however, is that by using such a page you inject some PHP code in between the user and the file. In order to get the file, the user needs to make a request to a PHP page. On that page you can record the act of the user having requested the file. (As well as perform authorization checks to validate that the user is allowed to view the file, etc.)
Never assume client-side code is going to do what you expect it to do. If you want to ensure something happens for anything approaching security or auditing purposes, it needs to happen in server-side code.

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Categories