When I run my ajax action the return text has a return character as the first char. However the echo text used to send is fixed with no spaces or returns. and if i alert the return text there is no carraige return.
I'm running the code from my Godaddy host, running MSQL with PHP5
innerHTML that crates the button - _("comment_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
js code -
function deleteComment(commentid,commentbox){
var conf = confirm("Press OK to confirm deletion of this status and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/comments_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var deleteOk = ajax.responseText; //This is retuning a return carraige
if(deleteOk = "1"){
_(commentbox).style.display = 'none';
_("replytext_"+commentid).style.display = 'none';
_("replyBtn_"+commentid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_comment&commentid="+commentid);
}
This is the PHP code
if (isset($_POST['action']) && $_POST['action'] == "delete_comment"){
if(!isset($_POST['commentid']) || $_POST['commentid'] == ""){
mysqli_close($db_conx);
echo "comment id is missing";
exit();
}
$commentid = preg_replace('#[^0-9]#', '', $_POST['commentid']);
// Check to make sure this logged in user actually owns that comment
$sql = "SELECT author_name FROM comments WHERE parent_id=$commentid LIMIT 1";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$author_name = $row[author_name];
}
if ($author_name == $log_username) {
mysqli_query($db_conx, "DELETE FROM comments WHERE parent_id=$commentid");
mysqli_close($db_conx);
echo "1";
exit();
}else{
echo "$sql - $author_name";
}
}
So I have had to edit my code at the moment to use the int values as it would seem the IF statements still match the return value, but if i use a text return then it does not match. I have an almost identical bit of code to create the comment but this work as expected.
Related
My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.
this is probably very simple but im really new to php and js
i made a comment system for my site but i have an issue that i cant figure out
//comment section
$commentsArray = array();
$commentQuery_run = mysqli_query($con, "SELECT * FROM comments WHERE PostID='$userPostId'");
if (mysqli_num_rows($commentQuery_run) > 0) {
echo "<b id='commcount'>Comments:".mysqli_num_rows($commentQuery_run).
"</b>";
while ($commentRow = mysqli_fetch_assoc($commentQuery_run)) {
$commentID = $commentRow['id'];
$commentUsername = $commentRow['username'];
$commentUserPfpPath = $commentRow['path'];
$commentContent = $commentRow['text'];
$commentDate = $commentRow['date'];
$commentsArray[] = $commentContent;
echo "html for displaying the comments";
}
} else {
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
if ($isLoggedIn === true) {
echo "<form id='commForm' method='POST' action=''> <
input id = 'commTextInp'
type = 'text'
placeholder = 'Your comment...'
name = 'commentText' > < br >
<
input id = 'commSubmInp'
type = 'submit'
name = 'commentSubmit'
value = 'Post Comment' >
<
/form>";
} else {
echo "<b id='commcount'>Please Login In to comment!</b>";
}
//comment section
//coment process
if (isset($_POST['commentSubmit'])) {
if (isset($_POST['commentText']) && !empty($_POST['commentText'])) {
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if (!in_array($postCommentContents, $commentsArray)) {
$postCommentQuery_run = mysqli_query($con, "INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if ($postCommentQuery_run === true) {
echo "<script> window.location.reload() </script>";
} else {
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
} else {
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
}
} else {
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
}
}
echo "</center>";
//comment process
every time i submit the form i get the "please dont repeat yourself/other users" error. why? does the window.location.reload() function also re-submit the form? or im I doing something completely wrong? and is there any better method for reloading the site? as it might be obvious i need to reload the page so that the new comment shows up. again, im really new to php/js/html so please explain why my code isnt working the way its supposed to. my guess is that the reload() method resubmits the form (excuse my bad english)
You better should place your POST-processing code in header of file, and you will be able to use header() redirect. To show error, you can use some flag; see:
// here we store all our comments
$commentsArray = [];
$commentQuery_run = mysqli_query($con,"SELECT * FROM comments WHERE PostID='$userPostId'");
while($commentRow = mysqli_fetch_assoc($commentQuery_run)){
$commentsArray[] = $commentRow;
}
//coment process
if(isset($_POST['commentSubmit'])){
if(isset($_POST['commentText']) && !empty($_POST['commentText'])){
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if(! array_search($postCommentContents, array_column($commentsArray, 'text')) ){
$postCommentQuery_run = mysqli_query($con,"INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if($postCommentQuery_run === true){
header("Location: " . $_SERVER['PHP_SELF']);
}
else {
$is_error = 'ERROR';
}
}
else{
$is_error = 'DUPLICATE';
}
}
else{
$is_error = 'NO_DATA';
}
}
and next, in the old place (in the middle of page) you can show error:
if(isset($is_error)) {
switch($is_error) {
case 'DUPLICATE':
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
break;
case 'NO_DATA':
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
break;
default:
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
}
// ...........
// PRINT ALL COMMENTS HERE
if(count($commentsArray)>0){
echo "<b id='commcount'>Comments:" . count($commentsArray) . "</b>";
foreach($commentsArray as $comment){
// $comment contains all your db-fields
echo "html for displaying the comments";
}
}
else{
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
every time i submit the form i get the "please dont repeat yourself/other users" error. why?
if(! in_array($postCommentContents, $commentsArray))
for first comment is true because:
if(mysqli_num_rows($commentQuery_run) > 0)
for first comment is false and commentsArray is empty.
I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.
I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.
HTML
<body onload="AjaxFindPerson()">
.....
</body>
JS
var xmlHttp = createXmlHttpRequestObject();
function AjaxFindPerson() {
if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else {
document.getElementById('Label-Result').innerHTML = "";
document.getElementById('UserNameSearchResult').innerHTML = "";
$('#add-person-btn').attr("disabled", "disabled");
setTimeout('AjaxFindPerson()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
result = xmlDocumentElement.firstChild.data;
if (result[0] != false) {
document.getElementById('Label-Result').innerHTML = result[1];
document.getElementById('UserNameSearchResult').innerHTML = result[0];
$('#add-person-btn').removeAttr("disabled", "disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result[1];
}
setTimeout('AjaxFindPerson()', 1000);
}
else {
alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
}
}
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
session_start();
define("DB_HOST", 'mysql6.000webhost.com');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
echo '<response>';
$email = $_GET['email'];
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$sq = mysql_query("SELECT UserEmail FROM Users");
$UserInfo = array();
while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
$UserInfo[] = $row['UserEmail'];
}
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
$returnRes = array($row[0], "We found results"); //row[0] holds the UserN
echo $returnRes;
}
else {
$returnRes = array(false, "We couldn't find results");
echo $returnRes;
}
echo '</response>';
?>
If we check the php-xml file alone will see the image bellow :
Do I need to pass the values to xml-php with another way?
UPDATE 1 in PHP
I manage to found a way to return the data correctly. Here are the update 'touch'
header('Content-Type: application/json');
and
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}
The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:
result = xmlDocumentElement.firstChild.data;
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
**UPDATE 2 WORKING JS **
I figure out how to retrieve the data from PHP.
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var result = JSON.parse(xmlDocumentElement.firstChild.data);
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!
+1 to all of you!
Four things :
Usage of send(null) doesn't seems to be right, just don't pass null in it.
Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.
If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach
<?php
session_start();
define('DB_HOST', 'mysql6.000webhost.com');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', '');
$dom=new DOMDocument('1.0','utf-8');
$root=$dom->createElement('response');
$dom->appendChild( $root );
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){
/* Basic filtering IF mysql_* functions are used! */
$email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );
$conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');
/* By the looks of the original there should be no need for two queries and then an array lookup */
$result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");
/* If there are results, add nodes to the dom object */
if( mysql_num_rows( $result ) > 0 ){
while( $rs=mysql_fetch_object( $result ) ){
$root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
}
} else {
/* Otherwise add error message */
$root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
}
}
/* Send the xml back to the js client */
header('Content-Type: text/xml');
$xml=$dom->saveXML();
$dom=null;
exit( $xml );
?>
I am using ajax to login user but this script is not working. When i call login function to execute nothing happens..
function login() {
var login = new XMLHttpRequest;
var e = document.getElementById("email").value;
var p = document.getElementById("password").value;
var vars = "email=" + e + "&password=" + p;
login.open("POST", "http://example.com/app/login.php", true);
login.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
login.onreadystatechange = function(){
if (login.readyState == 4 && login.status == "200") {
var response = login.responseText;
//document.getElementById("status").innerHTML = response;
}
document.getElementById("status").innerHTML = "Loggin in....";
login.send(vars);
if (response == "Sucess") {
window.location.replace("/logged.html");
}
else {
document.getElementById("status").innerHTML == "Login Failed";
}
}
}
login.php contains following codes
require_once('../db_/connection.php');//Holds connection to database
$email = mysqli_real_escape_string($con, $_POST['email']);//Sanitizing email
$pass = md5($_POST['password']);//Hashing password
$sql = "SELECT id FROM users WHERE email='$email' AND password='$pass' LIMIT 1";
$query = mysqli_query($con, $sql);
$check = mysqli_num_rows($query);
if($check < 1){
echo "fail";
//mysqli_close($con);
exit();
}
else{
echo "Sucess";
//mysqli_close($con);
exit();
}
Calling login function does not execute the code.
Line 2: The parentheses are missing after new XMLHttpRequest
Line 15: Your if (response == "Sucess") { ... } is misspelled and it gets executed before the ajax request is returned, because it's asynchronous
I made a working version at JSFiddle for you: http://jsfiddle.net/eRv83/
You might find the MDN referrence helpfull: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest