Building a messaging system for my site and i have been stuck for days. I have this PHP link
<a href='user_msg.php?hash=$hash'>$name</a>
When you click on the link, it takes you to a page where you can send message to a user you've connected to (this connection is binded by the $hash)
in the page for sending the message, i hid the $hash in and hidden input value="$hash" and it sends the message to row in database with the $hash with the following scripts (They have no issue and work fine)
var msg_area = $('.msg_area');
msg_area.scrollTop(msg_area.prop("scrollHeight"));
$('#send_rep').submit(function (e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');
var posting = $.post(url, {rep_msg: $('#rep_msg').val(), hash: $('#hash').val()});
posting.done(function (data) {
alert('success');
});
});
PHP script to send
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['rep_msg']) && !empty($_POST['rep_msg']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_GET['hash'];
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['rep_msg'];
$hash = $_POST['hash'];
$rsql = <<<EOF
INSERT INTO messager (message, group_hash, from_id) VALUES('$rep_msg', '$hash', '$my_id');
EOF;
$rret = $db->exec($rsql);
$ursql = <<<EOF
SELECT * FROM User WHERE ID = '$my_id';
EOF;
$urret = $db->query($ursql);
while ($urrow = $urret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urrow['fname'];
$from_img = $urrow['image'];
header('Location: user_msg.php?hash=' . $hash);
}
}
The above Ajax Request and php script work fone to sedn the messages to database.
The issue not is getting the messages from database
This is the script i am currently using (not working)
PHP script to get message
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_GET['hash']) && !empty($_GET['hash']))
{
$hash = (int)$_GET['hash'];
$us_id = $_SESSION['log_id'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hash';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM User WHERE ID = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['image'];
if ($from_id != $_SESSION['log_id']) {
echo "
<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><div class='from_txt'><p>$messages</p></div></div>";
} else {
echo "
<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><div class='rep_txt'><p>$messages</p></div></div>";
}
}
echo "<input style='display: none' type='text' class='hash' name='hash' value='$hash' id='hash'>";
}
}
Ajax Request
setInterval(function() {
$('.msg_area').load("get_msg.php");
}, 2000);
But the get is not working. I suspect fro some reason, its not getting the $hash. Please is there a solution to this or am i trying something impossible.
Any help would be appreciated. If more info is needed please ask. Thanks in advance
Maybe $hash = (int)$_GET['hash']; would be $hash = (int)$_POST['hash'];
And you have more than just one $_GET...
In your ajax request you are using POST so you will need to get the hash with the POST as well: if (isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_POST['hash'];
Using '' in PHP indicates the actual string you are writing.
If you want to use a PHP variable in a string you should use "", so try changing $name
Check this for more info:
http://php.net/manual/en/language.types.string.php
Then, how do you hide your hash in the input?
You could use <input value="$_GET['hash']" ... />
In the script to send , does it enter the if? Try adding statements to see if SQL returns any error.
Hope this helps.
Answer to the question was to create a PHP SESSION for the $hash($_SESSION['hash'] = $hash) and to use this session all over the site with session_start().
Related
Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.
I have the following PHP file
<?php
//Load the database configuration file
$db = new mysqli("localhost", "*****", "*****", 'kkVoting');
//Convert JSON data into PHP variable
$userData = json_decode($_POST['userData']);
if (!empty($userData)) {
$oauth_provider = $_POST['oauth_provider'];
//Check whether user data already exists in database
$prevQuery = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData ->id."' AND status = 1";
$prevResult = $db ->query($prevQuery);
if ($prevResult ->num_rows > 0) {
echo '<script type="text/javascript">
alert("hello");
window.location = "end.php"
</script >;
} else {
//Insert user data
$query = "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData ->id."', first_name = '".$userData ->first_name."', last_name = '".$userData ->last_name."', email = '".$userData ->email."', gender = '".$userData ->gender."', locale = '".$userData ->locale."', picture = '".$userData ->picture ->data ->url."', link = '".$userData ->link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."', status=0";
$insert = $db ->query($query);
}
}
?>
A JSON object is passed from an HTML file and it is being inserted into the database here. I want to redirect to another page if the entry already exists (and its status is 1). Is there a way to redirect to end.php inside the if{}.
echo js doesn't work. Header("Location: end.php"); also does not work.
I don't have much experience in PHP. But, I think echo js doesn't work because it is not an HTML file.
Please help.
so I have a little bit tricky or rather say odd situation.
I have php and mysql database, for frontend I am using angular.js
So I am creating service, that sends data, via post request to php.
So everything is working properly when I am sending input values via name html attribute.
But problem appears when I am trying to send hardcoded text variable from for loop.
I know it's very hardcoded way for doing it but i don't know how to do it differently.
So here is my php
<?php
$conn = mysqli_connect('localhost','nemkeang','nemkic23','interventure');
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$text = $_POST['first_name'];
$text2 = $_POST['last_name'];
$text3 = $_POST['date'];
$text4 = $_POST['author'];
$text5 = $_POST['note'];
$text6 = $_POST['skill'];
$target = "/assets";
$target = $target . basename( $_FILES['cv_file_name']['name']);
//This gets all the other information from the form
$file_name= $_FILES['cv_file_name']['name'];
$file_name2= $_FILES['cv_file_name']['name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['cv_file_name']['tmp_name'], "./".$file_name)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['cv_file_name']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
}
$sql = "INSERT INTO user (first_name, last_name, skill, date, cv_file_name, cv_url, author, note)
VALUES ('$text','$text2','$text6','$text3','$file_name','$file_name2','$text4','$text5')";
if (!mysqli_query($conn,$sql)) {
die('Error: ' . mysqli_error($conn));
}
else {
echo "success";
}
mysqli_close($con);
?>
The php is working correctly it's sending data, but on the $text6 = $_POST['skill']; problem arrives.
So here is my angular service first
app.service('testpost',['$http',function($http){
this.saveRecipe = function(postdata){
let payload = new FormData();
payload.append("first_name", postdata.first_name);
payload.append('last_name', postdata.last_name);
payload.append('date', postdata.date);
payload.append('cv_file_name', postdata.cv_file_name);
payload.append('author', postdata.author);
payload.append('note', postdata.note);
payload.append('skill', postdata.skill);
return $http.post('login/post.php', payload, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
})
}
}]);
And it's also working correctly, when i log it to console, it shows correct values. Just don't send payload.append('skill', postdata.skill); value to php.
Here is my controller
app.controller('newUser',['$scope','$filter','testpost', function($scope,$filter,testpost) {
$scope.postdata = {}
$scope.arr = [];
let bar = document.getElementsByClassName('md-chip-content');
this.saveRecipe = function(postdata) {
for(var i = 0; i < bar.length; i++) {
$scope.arr.push(bar[i].innerText);
}
let skills = $scope.arr;
postdata.date = $filter('date')(postdata.date, "MM/dd/yyyy").split('/').join('-');
postdata.skill = skills[0];
postdata.skill2 = skills[1];
postdata.skill3 = skills[2];
postdata.skill4 = skills[3];
testpost.saveRecipe(postdata).then((data)=>{
console.log(data);
})
error:(err) =>{ return false};
}
}]);
Just to be clear i just want the value from postadata.skill to be sent to mysql via php. And I think the problem is in php because the value don't come from input type.
I hope that I've explained everything well. Thanks in advance.
I'm working on a contact page. It uses Slim 3 framework to redirect. Everything is fine, but I want to add some jQuery code to inform the user whether the email is sent or not.
this is my php code:
<?php
require 'vendor/autoload.php';
$app = new Slim\App();
//... slim views codes
$app->get('/', function ($req, $res, $args) {
return $this->view->render($res, "about.twig");
})->setName('home');
$app->get('/contact', function ($req, $res, $args) {
return $this->view->render($res, "contact.twig");
})->setName('contact');
$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();
$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];
if(!empty($name) && !empty($email) && !empty($msg) ){
$cleanName = filter_var($name,FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg,FILTER_SANITIZE_STRING);
}else {
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
// javascript: please fill the fields.
}
//sending mail
]);
$result=$mailer->send($message);
if ($result > 0) {
// javascript: your email has been sent
$path = $this->get('router')->pathFor('home');
return $response->withRedirect($path);
} else {
// javascript: error sending mail
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
}
});
$app->run();
As you can see there's basically two page: "contact" and "home".
there's a form in contact page, if form submission is successful and a email is sent, page would be redirected to "home", but if not it would redirect to "contact" again. Now I want to add jQuery code so I can tell the user email has been sent or not.
I've got in my HTML something like this:
<div id="feedback" class="success">
<h3>Success!</h3>
<p>You're email has been sent.</p>
</div>
and in my js file:
$(document).ready(function() {
$(".success").click(function() {
$("#feedback").addClass("dismissed");
});
});
Thanks a lot!
$message = "Your text";
echo "<script type='text/javascript'>alert('$message');</script>";
i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}
Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))