posting form data with ajax javascript and php - javascript

I'm trying to post form data though a POST AJAX call in JavaScript for a chat system I'm creating, how come the following is not working? I tried to get some documentation but I cannot find it.
<div id="view-chat-form">
<input id="message" type="text" name="chat_message" placeholder="write a message..."/>,
<input type="button" value="send" onclick="sendData()"/>
</div>
and using the followin AJAX code to send the request without loading the page with an hashed string to hide the chat id
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
and the followin php code to insert the message into the messages table
<?php
include "session.php";
include "connection.php";
$id = "";
$hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
$sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 's', $hashed_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count > 0){
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
} else {
mysqli_free_result($result);
mysqli_close($connection);
header("Location: chat_error.php");
}
$msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
$username = $_SESSION["username"];
$date = date("d/m/Y");
$time = date("H:i:s");
$sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
mysqli_stmt_execute($stmt);
?>

Don't understand why you are using php $_POST in javascript, it will not work. Try using document.getElementById() to grab the chat message.
The correct way is shown below.
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
Also in your PHP code, why using json_decode()? The post is not in JSON format. Correct that also.
Change below code
$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;
to
$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];

Do something like this
<script type="text/javascript">
function sendData(){
var id = <?php echo $hashed_id; ?>;
var msg = <?php echo $_POST['chat_message']; ?>;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(id,msg);
}
</script>

Related

Creating a PHP session variable after successful AJAX call

I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.

How can I send data by json in php

I'am trying to use w3school example in my localhost but when I run it , it gives me this error
Fatal error: Uncaught Error: Call to a member function bind_param() on bool in C:\xampp\htdocs\test\json_demo_db.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\json_demo_db.php on line 7
I've just copied code from w3school and replace information about my db
here is my code
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "blog");
$stmt = $conn->prepare("SELECT name FROM ? LIMIT ?");
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
and it's my html and js
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p>The JSON received from the PHP file:</p>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"users", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</body>
</html>
and this is the link of w3school's example ( PHP Database)
https://www.w3schools.com/js/js_json_php.asp
The prepare() method is returning FALSE because, you are not providing the table name to it.
And you are calling function bind_param() on FALSE.
Provide table name directly by:
$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");
So, your modified code should be:
$stmt = $conn->prepare("SELECT name FROM `$obj->table` LIMIT ?");
$stmt->bind_param("s", $obj->limit);

Javascript output online usernames in HTML table

I made a server that checks if people are online if they logged in, and want to put that information into a html table.
<?php
session_start();
include_once '../php\connect.php';
function removeRefresh(){
$query = connection()->prepare("UPDATE `online` SET `time` = `time`+1");
$query->execute();
$query = connection()->prepare("DELETE FROM `online` WHERE `time` > 5");
$query->execute();
}
function addOrRefresh($ID){
$query = connection()->prepare("SELECT COUNT('id') FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
$count = $query->fetchColumn();
if($count == 0){
$query = connection()->prepare("INSERT INTO `online`(`ID`, `time`) VALUES(:ID, 0)");
$query->bindParam(':ID', $ID);
$query->execute();
}
else{
$query = connection()->prepare("UPDATE `online` SET `time` = 0 WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
}
$action = filter_input(INPUT_GET, 'action');
if($action == 'heartbeat'){
removeRefresh();
$ID = $_GET['id'];
addOrRefresh($ID);
$query = connection()->prepare("SELECT u.username FROM `nusers` u INNER JOIN `online` o ON o.ID = u.ID");
$query->execute();
$onlineUsers = $query->fetchAll(PDO::FETCH_ASSOC);
$resultaat = "";
foreach($onlineUsers as $user){
$resultaat .= "<p>{$user['username']} <br></p>";
}
echo "$resultaat";
}
?>
You can register, and when you log in into the lobby, you are added into an 'online' table, that checks every second with the function 'heartbeat'.
Please excuse my poor English.
EDIT: I have systems working. I merely want to change the 'echo "$resultaat"' so that it puts the $resultaat into a tablerow.
adding after a '}' won't work, I've tried working around that, not certain if I tried all posibilities in that retrospect. After request, I've posted the entire document.
the other javascript part is integrated into another document; containing:
<?php
session_start();
$ID = $_SESSION['ID'];
if (isset($_POST['logout'])) {
session_destroy();
$query = connection()->prepare("DELETE FROM `online` WHERE `ID` = :ID");
$query->bindParam(':ID', $ID);
$query->execute();
}
?>
<html>
<head>
<title>Stratego</title>
<Link href="../layout/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="./js/HeartBeat.js"></script>
<script>
$(document).ready(function () {
heartbeat.setSpelerId( <?php echo $ID; ?> );
heartbeat.polling();
});
</script>
</head>
<body>
<form method='post' name='logout' action="../setup/logout.php">
<input type='submit' name='loggout' value='Log me out'>
</form>
Singleplayer
<div id="online-list">
</div>
</body>
<?php echo "<script>
function heartbeat(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
document.getElementById(\"online-list\").innerHTML = xhttp.responseText;
}
};
xhttp.open(\"GET\", \"./wachtruimterInterface.php?action=heartbeat&id=" . $ID . "\", true);
console.log('keeping in touch ༼つ ◕_◕ ༽つ');
xhttp.send();
}
setInterval(heartbeat, 1000);
</script>"; ?>
</html>
The console log is there to check if the connection is being maintained. People use their ID to login, no passwords.
This is how it looks now, with 1 person being online; named Luuk.
http://www.filedropper.com/screenproof
My goal is to get all the people that are online into a table.
I've tried
$resultaat .= "<tr><td>{$user['username']} <br></td></tr>";
}
echo "<table>$resultaat</table>";
Just now, doesn't seem to work, any tips on how to progress?
I've fixed the issue;
$resultaat = "";
foreach($onlineUsers as $user){
$naam= $user['username']
$resultaat .= "<tr><td>$naam</td></tr>";
}
echo "<table border=1>$resultaat</table>";

Replicate the same data request query, but using a JavaScript Ajax post

Replicate the same data request query, but use a JavaScript Ajax post so that it doesn’t refresh the page on button press, just requests another page and display in a section on the page.
i need some help changing this to a ajax post
my code
*<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
<html>
<head>
<title>csv with criteria</title>
</head>
<body>
<form action="csv2.php" method="post" enctype="multipart/form-data">
Select data range
<br>
<input type="date" name="dates" id="dates"> Starting date
<br>
<input type="date" name="datee" id="datee"> Ending date
<br>
Select what data you'd like
<br>
<input type="radio" name="success" value="1" checked> Yes<br>
<input type="radio" name="success" value="0"> No<br>
<input type="submit" value="show" name="submit">
<br>
</form>
</body>
</html>*
If you want to use AJAX request on form submit you should:
Import the jQuery library: e.g. <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
Create a new JavaScrpit file where you will catch the form submit event, send jQuery request and analize the response, e.g.:
$(document).ready(function(){
$("#myForm").submit(function(e){
e.preventDefault(); //stop sending the form
//here you should validate your form
//submit it via AJAX:
$.ajax({
url: "csv2.php",
data: { dates: $("#dates").val(), datee: $("#datee").val(), $('input[name='success']:checked', '#myForm').val() }
})
})
});
You can use another functions of AJAX object such as success or error callback functions: jQuery.ajax(). Don't forget to add ID to your form.
You can see this post where it's explained how to make a good ajax call to POST parameters. But you will need to separate this portion of code :
<?php
if(isset($_POST['submit']))
{
$success = $_POST['success'];
$dates = $_POST['dates'];
$datee = $_POST['datee'];
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = '*******';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '*******';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$tablename = 'login_attempts';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$fields = array();
$csv = array();
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$success = mysql_real_escape_string($success);
$sql = "SELECT * FROM $tablename WHERE success = '".$success."' AND attempted >='".$dates."' AND attempted <='".$datee."'";
$stmt = $dbh->query($sql);
$stmt->execute();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
exit();}
?>
into one another php file.

How to send Ajax requests cross-domain?

I've had a fit for the past few days trying to figure out how to communicate across domains with ajax requests.
I have this file...
<?php
header('Access-Control-Allow-Origin: *');
?>
<script>
function send(user){
var hr = new XMLHttpRequest();
var url = "http://forumchest.com/kb_exchange.php";
var data = "user="+user;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onload = function(){
if(hr.readyState == 4 && hr.status == 200){
var text = hr.responseText;
alert(text);
} else {
alert(hr.readyState + " " + hr.status);
}
}
hr.send(data);
}
</script>
<?php
include_once("conn.php");
$fetch_sites = mysqli_query($conn, "SELECT * FROM sites");
while($row = mysqli_fetch_array($fetch_sites)){
$site_id = $row['id'];
$site_address = $row['address'];
$fetch_subs = mysqli_query($conn, "SELECT * FROM subscriptions WHERE site='$site_id'");
while($row1 = mysqli_fetch_array($fetch_subs)){
$sub_user = $row1['user'];
$sub_username = $row1['username'];
echo "<script>send('$sub_username');</script>";
}
}
mysqli_close($conn);
?>
It is attempting to send an ajax request to the following file hosted on a different server with a different domain name.
<?php
header("Content-Control-Allow-Origin: *");
?>
<script>
function respond(user, posts){
var data = "user="+user+"&posts="+posts;
var hr = new XMLHttpRequest();
hr.open("POST", "http://xenforotest.esy.es/responder.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(data);
}
</script>
<?php
$conn = mysqli_connect("host", "user", "password", "db");
if(!$conn){
echo "this1";
} else {
echo "this2";
}
$user = $_POST['user'];
$fetch_user = "SELECT message_count FROM xf_user WHERE username='$user'";
$query_user = mysqli_query($conn, $fetch_user);
$row = mysqli_fetch_array($query_user);
$message_count = $row['message_count'];
echo "<script>respond('$user', '$message_count');</script>";
mysqli_close($conn);
?>
I am getting two responses from the first file saying "2 200" and "3 200". So I'm getting a readyState of 2 and a status of 200.
Why isn't this working?
It should be
header("Access-Control-Allow-Origin: *");
and not
header("Content-Control-Allow-Origin: *");
Cross domain is not relevant there. Your problem is that you send data as a url string.. POST data should be in formdata object of javascript

Categories