Private Message Using JQuery and PHP - php

I am currently working on a Chat Application and ran into a slight hiccup, I want a message that is addressed to a user to only be visible to the user and the sender.
<script>
//PRIVATE MESSAGE
var username = '<?=$_SESSION['username'];?>'.toUpperCase();
$('#chatbox').children('.msgln').each(function(){
var msgln = $(this);
$$select = msgln.find('.messagelinebox');
$message = $$select.text();
if($message.indexOf('#') !== -1){
var $product = $message.substr($message.indexOf("#") + 1);
$$product = $product.substring(0,7).toUpperCase();
var receiver = $$product;
if(username = receiver){
$(this).show();
}else if(receiver = username){
$(this).show();
}else if(receiver != username){
$(this).hide();
}else{
$(this).show();
}
}
});
</script>
Any help will be appreciated.

As pointed out by everyone, you're going about things the wrong way.
However, there are some serious problems with your if() statement. This code:
if(username = receiver) {
/* code */
}
is exactly equivalent to the following:
username = receiver;
if(username) {
/* code */
}
If you want to test if two things are equal, use ==, not =. Also, if a==b, then there is no need to test for b==a. Your entire if ... else structure can be reduced to the following:
if (username == receiver) {
$(this).show();
}
else {
$(this).hide();
}
Your code only checks for messages that were sent to the current user. It doesn't check for messages sent by the current user. That's another thing you will have to fix.
But really, do this all on the server. Not in client-side Javascript.

Your question is not comprehensive. I would like to see the result of what you have done so far if at all the sample you gave works. And as a matter of fact, you need to sieve your codes (code structuring is important) so that I'll be able to help you.
file_name.php
<?php //your PHP codes here ?>
file_name.html
<html>Blah blah</html>
file_name.js
$(function(){
//your jquery...
})

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

Call Javascript function from within PHP block [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
I'm working on a project for school, and I'm struggling with the login page. In my PHP code, if the user enters an incorrect username or password, I want to call a Javascript function that displays a message and briefly changes the background colour where the message is shown. Here are my JS and PHP code blocks:
<script>
var flashContent = function () {
document.getElementById("outputlogin").style.backgroundColor = "#ffff00";
document.getElementById("outputlogin").innerHTML = "Incorrect login.";
function proxy() {
updateColor(0);
}
setTimeout(proxy, 50);
}
var updateColor = function (newColor) {
var hexColor = newColor.toString(16);
if (hexColor.length < 2)
hexColor = "0" + hexColor;
var colorString = "#ffff" + hexColor;
document.getElementById("outputlogin").style.backgroundColor = colorString;
function proxy() {
updateColor(newColor);
}
if (newColor < 255) {
newColor = newColor + 5;
setTimeout(proxy, 50);
}
}
</script>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(($username == "Ben") && ($password == "thepassword")){
//echo "SUCCESS";
session_start();
$_SESSION['bensedmgallerysesh'] = session_id();
header("Location:../index.php");
}else{
if($username != "" && $password != ""){
javascript:flashContent();
}
}
?>
Right now, after hitting the login button, I get the error message:
Fatal error: Call to undefined function flashContent()
How do I fix this?
You're trying to call a client side function in a server side script. You COULD do this:
if($username != "" && $password != ""){
?>
<script type="text/javascript">
flashContent();
</script>
<?php
}
But it might be smarter to actually separate the logic in a way that prevents you from trying to write server side processing like this. Organizational skills go a long way in this business.
Have you tried doing this:
echo '<script type="text/javascript"> flashContent(); </script>';
Instead of:
javascript:flashContent();
I dont think there is such thing like javascript: functionName()..
Javascript runs in user space, interpreted by the browser.
PHP runs in server space, and is processed by a preprocessor.
What you should do there is test the username and password in PHP, and if they are wrong send back a JSON reply to the client. In the client, parse the JSON data and show the corresponding message. You may want to do this with AJAX.
Hope that works
You cannot call a Javascript function like that with php, you would need to echo out the script calling the function in javascript. Something like this might work:
<?php
echo '<script> window.onload = function(){ flashContent(); } </script>';
?>
But that might not be a great way to do it. Php runs on the server before javascript runs on the browser. One better way to have the two languages communicate is to send AJAX calls to the php script.
EDIT
To clarify: You can echo out a call to a Javascript function in the script, and it will be run where you echoed it. But here, php will still just treat Javascript as a string to be printed on the document.

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

Dynamic script tag for cross-domain Ajax not working

I'm trying to use the dynamic script tag for cross-domain ajax, since I can't use PHP on the website where it's needed (we're using a CMS, so we can use HTML/Javascript, but no PHP).
The thing is, both scripts work well (javascript and php) on their own, meaning the script tag is well added, and the PHP scripts, when launched on its own, works as needed.
But it looks like the GET request is not processed when the script tag is added (using .appendChild).
Is there a way to make it work?
Here is the code, simplified :
PHP :
$email = $_GET['email'];
$source = $_GET['source'];
echo 'callback({"value": "true"});';
// sending the email through php
Javascript :
function dlPj() {
// Prompt the user for his email
var email = prompt('Enter your email', 'your email');
// If the script tag already exists, delete it
if (document.getElementById('script-pj') != null) {
var script_pj = document.getElementById('script-pj');
document.getElementsByTagName("head")[0].removeChild(script_pj);
}
// Create the script tag to call the PHP script
var s = document.createElement('script');
s.type = 'txt/javascript';
s.id = 'script-pj';
s.src = 'http://www.something.com/bel/pj.php?';
s.src += 'email=' + email;
s.src += '&source=' + document.location.href + '?';
document.getElementsByTagName("head")[0].appendChild(s);
}
function callback(value) {
if (value == null) {
alert('error');
}
else {
if (value.value == "true") {
alert('working');
}
else {
alert('not working');
}
}
}
Help greatly appreciated.
Edit : problem solved. The problem was the following : I added an onclick event on an A tag, so that I could get some information about a user before he downloads an attached file. So I left it at return true;, so that he could download the file after filling in the form. Changing the onclick event to "dlPj(); return false;" solves the problem.
Try this, it works in chrome:
var email = prompt('Enter your email', 'email#company.com');
// If the script tag already exists, delete it
if (document.getElementById('script-pj') != null) {
var script_pj = document.getElementById('script-pj');
document.getElementsByTagName("head")[0].removeChild(script_pj);
}
// Create the script tag to call the PHP script
var s = document.createElement('SCRIPT');
s.id = 'script-pj';
s.src = 'http://www.something.com/bel/pj.php?' +
'email=' + encodeURIComponent(email) +
'&source=' + encodeURIComponent(document.location.href);
document.getElementsByTagName("head")[0].appendChild(s);
Alright, so that this follows correctly stackoverflow's workflow, there is the answer.
The problem was the following : I added an onclick event on an A tag, so that I could get some information about a user before he downloads an attached file. So I left it at return true;, so that he could download the file after filling in the form. Changing the onclick event to "dlPj(); return false;" solves the problem.

Posting not working via JS (Jquery) but is with form

I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.

Categories