JSON Parse error: Unrecognized token '<' In angular - javascript

This is my angular code. form submit code. When click on submit button. JSON Parse error: Unrecognized token '<' this error will showing. empty records will save on the DB. I added html code and PHP server side code also for this.
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost/youtubewebservice/checkOutt.php',
data : $scope.user,
dataType: 'json',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorinputFName = data.errors.inputFName;
$scope.errorinputLName = data.errors.inputLName;
}
});
};
Html code
<form name="userForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="inputFName" class="form-control" ng-model="user.inputFName">
<span ng-show="errorName">{{errorName}}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="inputLName" class="form-control" ng-model="user.inputLName">
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div id="sendmessageresponse"></div>
</form>
**PHP code **
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json;charset=UTF-8");
$data = json_decode(file_get_contents("php://input"));
$inputFName = mysql_real_escape_string($data->inputFName);
$inputLName = mysql_real_escape_string($data->inputLName);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('look4com_lk', $con);
$qry_em = 'select count(*) as cnt from checkout where chkID ="' . $chkID . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if ($res['cnt'] == 0) {
$qry = 'INSERT INTO checkout (inputFName,inputLName) values ("' . $inputFName . '","' . $inputLName . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}

This particular parse error indicates that the output is no valid JSON (duh). Since your output is formatted with json_encode, it should be. (Although I usually use print_r for arrays only ...) However ...
My experience tells me that your server produces an error / notice, which php usually outputs with some html, hence the <. Since you claim, that the response is clean JSON, I suggest you look at the actual responses your server sends. My assumption is, that you tested your php-script from command line (hence the php://input?) but a server possibly handles requests differently than you'd expect.
You can check the server's responses in the network tab of almost every decent browser, usually F12 -> network tab, then reload and/or resend the form. If you have problems solving your php-problem, add the php error message to your question or ask a new one.
As a final remark: Please avoid the mysql_* functions (deprecated mysql library) and either use the mysqli_* functions (mysqli library) or PDO. Also use prepared statements.

I found the error of this code. this code working properly. any one have any question ask. thanks
html code
<div ng-controller="ProductController">
<form name="userForm" ng-submit="submitForm()">
<div class="form-group">
<label>Name</label>
<input type="text" name="inputFName" class="form-control" ng-model="user.inputFName">
<span ng-show="errorName">{{errorName}}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="inputLName" class="form-control" ng-model="user.inputLName">
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<div id="sendmessageresponse"></div>
</form>
</div>
**PHP code **
$data = json_decode(file_get_contents("php://input"));
$inputFName = mysql_real_escape_string($data->inputFName);
$inputLName = mysql_real_escape_string($data->inputLName);
//localhost
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('look4com_lk', $con);
$qry_em = 'select count(*) as cnt from checkout where inputFName ="' . $inputFName . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if ($res['cnt'] == 0) {
$qry = 'INSERT INTO checkout (inputFName,inputLName) values ("' . $inputFName . '","' . $inputLName . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
**controller code **
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'http://localhost/youtubewebservice/checkOutt.php',
data : $scope.user, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorinputFName = data.errors.inputFName;
$scope.errorinputLName = data.errors.inputLName;
//$scope.errorMessage = data.errors.Message;
} else {
$scope.contactmessage = data.contactmessage;
//data: {Name: $scope.Name, Email: $scope.Email, Message: $scope.Message}
}
});
};

Related

updating data with JavaScript functions not working properly

I want to send an Ajax request when clicking a button but it seems my request is never executed.
Here is my HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src = "./actions.js"></script>
</head>
<body>
<div id="badFrm" class="container">
<h2><br>User Registration</h2>
<form id="Form" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email">
</div>
<button id="submitBtn" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
i feel there is something wrong with my javascript code but i cant figure whats wrong ! i changed a lot of it based on the comments i got earlier . what i want is when i click on the update button it changes to " submit again " and i want to replace "list items" ( name and email ) with input fields and put whatever written in them to be saved in the database instead . and eventually return to the first page which is the register form. i need help in this part !! i know this part is buggy . i need to know how to reach each list item individually ( what attribute should i add/use )
and here is my javascript code :
$(document).ready(function() {
var i ;
$("#submitBtn").click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("http://localhost/MiniProject/connect.php",
{
name: name,
email: email
}, function () {
var element = document.getElementById("badFrm");
element.remove();
showTbl();
});
function showTbl() {
$.post("http://localhost/MiniProject/Select.php",
{
name: name,
email: email
}, function (res) {
// console.log(res);
res = JSON.parse(res);
var html = '<ul id="List">';
for (i = 0; i < res.length; i++) {
var j = i +1 ;
html += '<li class = "name" >' + res[i].name + '</li><li class = "email">' + res[i].email + '</li>'+ '<div>' + '<button onclick="removeUser(this)" class="btn btn-primary">Remove</button>' + '<button onclick="updateUser(this)" class="btn btn-primary">Update</button>' + '</div>';
}
html += '</ul>';
document.body.innerHTML = html;
});
}
});
});
function removeUser(element){
var ID = element.id;
var element2 = document.getElementById("List");
element2.remove();
$.post("http://localhost/MiniProject/Remove.php",{
id : ID
}, function (res) {
console.log(res);
document.write(res);
});
//alert(element.id);
}
function updateUser(element){
// code ...
$.post("http://localhost/MiniProject/Update.php",{
id : ID2,
}, function (res) {
console.log(res);
// document.write(res);
});
}
here is connect.php :
<?php
require 'Users.php';
$name = $_POST['name'];
$email = $_POST['email'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$user->Insert(['name' => $name, 'email' => $email]);
echo "name is : ".$name." and email is : ".$email;
}
this is Users.php :
<?php
require 'newDB.php';
class Users extends DatabaseClass{
public $table = 'Users';
}
and this is where i handle the database commands :
<?php
class DatabaseClass{
public $connection = null;
public $table = null;
// this function is called everytime this class is instantiated
public function __construct( $dbhost = "localhost", $dbname = "myDatabaseName", $username = "root", $password = ""){
try{
// $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Insert a row/s in a Database Table
public function Insert($parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = '`' . implode('`,`', $fields) . '`';
$values_string = ':' . implode(',:', $fields);
$sql = "INSERT INTO `{$this->table}`({$fields_string}) VALUES ( {$values_string} )";
$this->executeStatement( $sql , $parameters );
return $this->connection->lastInsertId();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Select a row/s in a Database Table
public function Select( $parameters = [] ){
try{
$fields = array_values($parameters);
$fields_string=implode(' , ',$fields);
$sql = "SELECT {$fields_string} FROM {$this->table}";
$stmt = $this->executeStatement( $sql , $parameters );
return $stmt->fetchAll();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Update a row/s in a Database Table
public function Update( $parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = 'id = '.implode($fields);
$sql = "UPDATE {$this->table} SET {$fields_string} WHERE {$fields_string} ";
echo $sql; exit ;
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Remove a row/s in a Database Table
public function Remove( $parameters ){
try{
$fields_string = 'id = '.implode($parameters);
$sql = "DELETE FROM {$this->table} WHERE {$fields_string}";
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// execute statement
public function executeStatement( $statement = "" , $parameters = [] ){
try{
$stmt = $this->connection->prepare($statement);
$stmt->execute($parameters);
return $stmt;
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
}
and this is Update.php :
<?php
require 'Users.php';
$id = $_POST['id'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$result = $user->Update(['id'=>$id]);
// echo json_encode($result);
}
?>
i dont want the question to have a lot of code so hope this makes it better to understand.
I mentioned posting something without jQuery - here is a demo which does what I understand your requirement to be. There are comments below to explain what is going on.
<?php
error_reporting( E_ALL );
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
/*
This emulates ALL of the PHP endpoints used in the original code
-this is for demo purposes ONLY. The data returned is DEMO data
and should be ignored. All AJAX functions should be pointed at
their original endpoints... unless you adopt a similar approach
in which case include your various PHP classes here.
The ficticious sql in the below is for example only!
Obviously you would use `prepared statements`...
*/
switch( $_POST['action'] ){
case 'insert':
// do stuff...
// send response...
$data=sprintf('name is: %s and email is: %s',$_POST['name'],$_POST['email']);
break;
case 'remove':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('delete from `TABLE` where `email`="%s"', $_POST['email'] )
));
break;
case 'update':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('update `TABLE` set `col`=? where `email`="%s"', $_POST['email'] )
));
break;
}
exit( $data );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
.hidden{display:none}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/*
I can see no benefit to having multiple endpoints to process
the different AJAX requests. You can structure a single script
to process each request rather like the above PHP code but
that is just an opinion. The following points ALL requests to
the same page for this demo.
The user's `email` address should be unique(?) so could be used
as the key in whatever sql query???
*/
const endpoints={
'insert':location.href, // 'MiniProject/connect.php'
'select':location.href, // 'MiniProject/Select.php'
'remove':location.href, // 'MiniProject/Remove.php'
'update':location.href // 'MiniProject/Update.php'
};
// Elements in the initial page/form
let cont=document.querySelector('div.container');
let form=document.forms.register;
let bttn=form.querySelector('button');
// the main callback - for the `Submit` button
const bttnclickhandler=function(e){
e.preventDefault();
let valid=true;
// check the form fields are not empty before continuing
let col=form.elements;
Array.from( col ).some( n => {
if( n.tagName=='INPUT' && n.value=='' ){
alert( '"' + n.name + '" cannot be empty' );
valid=false;
return true;
}
})
if( !valid )return false;
// Prepare the Payload to be sent, via AJAX POST, to the backend script/endpoint.
let fd=new FormData( form );
fd.append('action',this.dataset.action);
// Send the AJAX request
fetch( endpoints.insert, { method:'post', body:fd } )
.then( r=>r.text() )
.then( text=>{
// Hide the original form - do not remove it though... you want to reinstate this later
form.classList.add('hidden');
/*
create a clone of the template and then find the elements within
assign new values and bind event listeners.
*/
let oTmpl=document.querySelector('template#list-item').content.firstElementChild.cloneNode( true );
oTmpl.querySelector('[data-id="name"]').textContent=fd.get('name');
oTmpl.querySelector('[data-id="email"]').textContent=fd.get('email');
oTmpl.querySelectorAll('button[data-action]').forEach( n=>{
n.addEventListener('click',function(e){
let action=this.dataset.action;
let url=endpoints[ action ];
let fd=new FormData();
fd.append('action',action);
fd.append('name',e.target.parentNode.parentNode.querySelector('span[data-id="name"]').textContent);
fd.append('email',e.target.parentNode.parentNode.querySelector('span[data-id="email"]').textContent);
// send a new AJAX request
fetch( url, { method:'post', body:fd })
.then( r=>r.json() )
.then( json=>{
// the response...
console.log( json );
// show the original form and remove the clone
form.classList.remove('hidden');
cont.querySelector('ul#list').removeChild( oTmpl );
})
});
});
// Add the cloned template to the container
cont.querySelector('ul#list').appendChild( oTmpl )
})
};
// bind the event handler to the button.
bttn.addEventListener( 'click', bttnclickhandler );
});
</script>
</head>
<body>
<!--
All buttons below have dataset attributes
data-action='value' - this is used to decide
which piece of PHP code to process.
-->
<div class='container'>
<h2>User Registration</h2>
<form name='register' method='post'>
<div class='form-group'>
<label>
Name:
<input type='text' name='name' class='form-control' placeholder='Enter Name' />
</label>
</div>
<div class='form-group'>
<label>
Email:
<input type='email' name='email' class='form-control' placeholder='Enter Email' />
</label>
</div>
<button data-action='insert' class='btn btn-primary'>Submit</button>
</form>
<ul id='list'></ul>
</div>
<!--
The template will be called and populated
by ajax callback when the above `Submit`
button is clicked.
This will NOT appear in the DOM until
requested with Javascript.
The inner contents of this template
are cloned and inserted into the DOM.
-->
<template id='list-item'>
<li>
<span data-id='name'></span>
<span data-id='email'></span>
<div>
<button data-action='remove' class="btn btn-primary">Remove</button>
<button data-action='update' class="btn btn-primary">Update</button>
</div>
</li>
</template>
</body>
</html>
You say that you want to make an AJAX request (submit), but I don't see where are you doing it.
Also, it seems that you're submitting twice your form.
You should have something like this:
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "http://localhost/MiniProject/connect.php",
success: function(data) {
//if it's successful, put all your code here to change names etc.
}
$(this).serialize() will work only if you change your button to a submit input:
<input type="submit" id="submitBtn" class="btn btn-primary">Submit</input>
you can also use a "button" but then you'll have to specify what data you're submitting, it's easier to use a submit input, if you ask me.
Also, if you already have an ID for name and email, it's a lot easier to change them using it's respective ID's, instead of trying to re-write the whole div element.
Anyway, I hope it helps

Cannot login using php through jquery

I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?

updating MYSQL table gives success msg, but does'nt update the table

the AJAX msg gives successful, but the data doesn't update in DB, can you help plz!
html code:
<div class="row">
<input type="text" ng-model="updateId" class="form-control" placeholder="user Id To Update Phone">
<input type="text" ng-model="updatePhone" class="form-control" placeholder="user New Phone">
</div>
<div class="col-xs-3">
</div>
<div class="col-xs-2">
<button ng-click="updateuser()" type="button" class="btn btn-primary">Update </button>
</div>
</div>
javascript code:
$scope.updateuser = function () {
var data = {
updateId: $scope.updateId,
updatePhone: $scope.updatePhone
};
$.ajax({
data: data,
type: "post",
url: "update.php",
success: function(data){
alert("Data Updated");
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
});
};
update.php code:
<?php
header('Content-Type: application/json');
include 'connect.php';
$db = new database();
$db->setDb_name('training');
$db->connect();
if(isset($_POST)){
$id = $_POST['updateId'];
$phone = $_POST['updatePhone'];
$data = $db->update('user',array('phone'=>$phone),array('id',$id));
echo json_encode($data);
}
mysql_close();
?>
the update() function:
public function update($table,$rows,$where)
{
for($i = 0; $i < count($where); $i++)
{
if($i%2 != 0)
{
if(is_string($where[$i]))
{
if(($i+1) != null)
$where[$i] = '"'.$where[$i].'" AND ';
else
$where[$i] = '"'.$where[$i].'"';
}
}
}
$where = implode('=',$where);
$update = 'UPDATE '.$table.' SET ';
$keys = array_keys($rows);
for($i = 0; $i < count($rows); $i++)
{
if(is_string($rows[$keys[$i]]))
{
$update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
}
else
{
$update .= $keys[$i].'='.$rows[$keys[$i]];
}
// Parse to add commas
if($i != count($rows)-1)
{
$update .= ',';
}
}
$update .= ' WHERE '.$where;
$query = #mysql_query($update);
}
}
I am using angularJS, and when trying to run updating in update.php it works correctly, but using AJAX it gives "Data Updated" msg but actually doesnt update table.. why?
First of all, the ajax success callback from (I'm assuming) jQuery just means the HTTP request succeeded. This means it got a 200 response code. With most minor and some major errors in PHP the request will still be successful. If you want to know what went wrong, enable error reporting in PHP and be sure the errors are displayed:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Now, you should be able to see any errors. Use something like Chrome's developer console to see what error happened in your PHP code. Another option would be to log the error in PHP and check the error log after the request.

Session not sending correctly through AJAX

I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.

Many spaces before javascript result

I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.

Categories

Resources