Not able to randomise questions rows in mysql - php

Im trying to get random questions from my sql table.The rand() function is not working. The rand() function for 'answers' is working but not for 'questions' row. Where am I going wrong? . Can anyone give a solution to this?
index.php
<?php
$msg = "";
if(isset($_GET['msg'])){
$msg = $_GET['msg'];
$msg = strip_tags($msg);
$msg = addslashes($msg);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quiz Tut</title>
<script>
function startQuiz(url){
window.location = url;
}
</script>
</head>
<body>
<?php echo $msg; ?>
<h3>Click below when you are ready to start the quiz</h3>
<button onClick="startQuiz('quiz.php?question=1')">Click Here To Begin</button>
</body>
</html>
questions.php
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysql_query("SELECT id FROM questions");
$numQuestions = mysql_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="text" name="email">
<input type="submit" value="Finish">
</form>';
exit();
}
$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' order by RAND() LIMIT 1");
while($row = mysql_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysql_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="checkbox" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
quiz.php
<?php
session_start();
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1;
if(!isset($_SESSION['qid_array']) && $question != 1){
$msg = "Sorry! No cheating.";
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['qid_array']) && in_array($question, $_SESSION['qid_array'])){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
if(isset($_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev){
$msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
unset($_SESSION['answer_array']);
unset($_SESSION['qid_array']);
session_destroy();
header("location: index.php?msg=$msg");
exit();
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Quiz Page</title>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "checkbox=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&checkbox="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Thanks, Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
</script>
</head>
<body onLoad="getQuestion()">
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<div id="status">
<div id="counter_status"></div>
<div id="question"></div>
<div id="answers"></div>
<h1>PONG</h1>
</div>
<script type="text/javascript">countDown(20,"counter_status");</script>
</body>
</html>

SELECT * FROM questions WHERE id='$question'
Seems that you're selecting exactly one question at a time, so there's nothing to sort randomly.
If you want to select a random question, query probably should look like this:
SELECT * FROM questions WHERE 1=1 order by RAND() LIMIT 1
... but that would require rewriting some of related code: for example, you won't need mandatory question get parameter every time.

Related

PHP | LDAP | Live search in AD

I am using the live search function for my MySQL database data.
But to go directly to the source I do not want a file or db in between and I went directly to the Active Directory itself.
The searching is working but after you searched for something like username, it gives the correct output, the data resets after 2/3 seconds. So the input type text is still filled in but it's showing all the results.
Does anyone can help me with this or can optimize the code?
INDEX.PHP
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search Active Directory</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
My fetch.php file with all the links to AD. Ofcourse crendentials and server are filled in and binding is working.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<div style="overflow-x:auto;">
</head>
</html>
<?php
$output = "";
$ldap_password = "<username>";
$ldap_username = "<password>";
$ldap_connection = ldap_connect("<ldapserver>");
if (FALSE === $ldap_connection){
echo "Unable to connect to the ldap server";
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password))
{
if (isset($_POST["query"]))
{
$search = $_POST["query"];
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*".$search.")(sAMAccountName=".$search."*)(l=*".$search."*)))";
}
else
{
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*)))";
}
$output .= '<table id="customers"><tr><th>Username</th><th>Last Name</th><th>First Name</th><th>Company</th><th>Office</th><th>Department</th><th>Mobile</th><th>Telephone</th><th>E-Mail Address</th></tr>';
$ldap_base_dn = "OU=NL,DC=global,DC=com";
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
//var_dump($entries);
//For each account returned by the search
for ($x=0; $x<$entries["count"]; $x++){
//Windows Username
$LDAP_samaccountname = "";
if (!empty($entries[$x]["samaccountname"][0])) {
$LDAP_samaccountname = $entries[$x]["samaccountname"][0];
if ($LDAP_samaccountname == "NULL"){
$LDAP_samaccountname= "";
}
} else {
//#There is no samaccountname s0 assume this is an AD contact record so generate a unique username
$LDAP_uSNCreated = $entries[$x]["usncreated"][0];
$LDAP_samaccountname= "CONTACT_" . $LDAP_uSNCreated;
}
//Last Name
$LDAP_LastName = "";
if (!empty($entries[$x]["sn"][0])) {
$LDAP_LastName = $entries[$x]["sn"][0];
if ($LDAP_LastName == "NULL"){
$LDAP_LastName = "";
}
}
//First Name
$LDAP_FirstName = "";
if (!empty($entries[$x]["givenname"][0])) {
$LDAP_FirstName = $entries[$x]["givenname"][0];
if ($LDAP_FirstName == "NULL"){
$LDAP_FirstName = "";
}
}
//Company
$LDAP_CompanyName = "";
if (!empty($entries[$x]["company"][0])) {
$LDAP_CompanyName = $entries[$x]["company"][0];
if ($LDAP_CompanyName == "NULL"){
$LDAP_CompanyName = "";
}
}
//Department
$LDAP_Department = "";
if (!empty($entries[$x]["department"][0])) {
$LDAP_Department = $entries[$x]["department"][0];
if ($LDAP_Department == "NULL"){
$LDAP_Department = "";
}
}
//Office
$LDAP_Office = "";
if (!empty($entries[$x]["l"][0])) {
$LDAP_Office = $entries[$x]["l"][0];
if ($LDAP_Office == "NULL"){
$LDAP_Office = "";
}
}
//Job Title
$LDAP_JobTitle = "";
if (!empty($entries[$x]["title"][0])) {
$LDAP_JobTitle = $entries[$x]["title"][0];
if ($LDAP_JobTitle == "NULL"){
$LDAP_JobTitle = "";
}
}
//Mobile Number
$LDAP_CellPhone = "";
if (!empty($entries[$x]["mobile"][0])) {
$LDAP_CellPhone = $entries[$x]["mobile"][0];
if ($LDAP_CellPhone == "NULL"){
$LDAP_CellPhone = "";
}
}
//Telephone Number
$LDAP_DDI = "";
if (!empty($entries[$x]["telephonenumber"][0])) {
$LDAP_DDI = $entries[$x]["telephonenumber"][0];
if ($LDAP_DDI == "NULL"){
$LDAP_DDI = "";
}
}
//Email address
$LDAP_InternetAddress = "";
if (!empty($entries[$x]["mail"][0])) {
$LDAP_InternetAddress = $entries[$x]["mail"][0];
if ($LDAP_InternetAddress == "NULL"){
$LDAP_InternetAddress = "";
}
}
$output .= '<tr><td><strong>' . $LDAP_samaccountname .'</strong></td><td>' .$LDAP_LastName.'</td><td>'.$LDAP_FirstName.'</td><td>'.$LDAP_CompanyName.'</td><td>'.$LDAP_Office.'</td><td>'.$LDAP_Department.'</td><td>'.$LDAP_CellPhone.'</td><td>'.$LDAP_DDI.'</td><td>'.$LDAP_InternetAddress.'</td></tr>';
} //END for loop
echo $output;
} //END FALSE !== $result
echo("</table>"); //close the table
}
?>
The loop is to display multiple results.
As you can see the result is good, but after 2/3 sec it resets and shows all data instead of the "sbx" value. (data is confidential so not shown, but it's corect)
Greets, Stef

How to redirect React submit button to php page

I have created a form with live validation in react, but I want to post this form to a PHP page so it gets inserted into the database. The code currently validates but doesn't allow me to access the PHP page, I have access to the SQL database which is on config page and it works well.
react js form
<!DOCTYPE html>
<?php
include ("includes/header.php");
?>
<html lang="en">
<title>Demostration of Forms in React</title>
<script src= "https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src= "https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src= "https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<body>
<h1> Register Page</h1>
<div id="root"></div>
<script type="text/babel">
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
//this.state = {value: 'Write your Name'};
this.handleChange = this.handleChange.bind(this);
this.password = this.password.bind(this);
this.manager = this.manager.bind(this);
this.phoneChange = this.phoneChange.bind(this);
this.emailChange = this.emailChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
//this.setState({value: event.target.value.toLowerCase()});
//perform validation length of the input values or others
//const textval = this.state.value;
var textval = this.state.value;
//if ((textval.length < 5) || (textval.length > 15))
//alert("Your Character must be 5 to 15 Character");
//user validation of the special characters
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < textval.length; i++) {
if (iChars.indexOf(textval.charAt(i)) != -1) {
alert ("Your username should not have !##$%^&*()+=-[]\\\';,./{}|\":<>? \nThese are not allowed.\n Please remove them and try again.");
//return false;
}
}
//if(isNaN(textval))
//alert(textval);
}
phoneChange(event){
this.setState({phone: event.target.value});
var textval2 = this.state.phone;
var iChars2 = "0123456789";
for(var j = 0; j< textval2.length; j++){
if(iChars2.indexOf(textval2.charAt(j)) == -1){
alert("Your phone number should be between 0 and 9");
}
}
}
password(event){
this.setState({password: event.target.value});
}
manager(event){
this.setState({manager: event.target.value});
}
emailChange(event){
this.setState({email: event.target.value});
var emailval = this.state.email;
var emailCheck= "#.";
for(var i =0; j<emailval.length; i++){
if(emailval.indexOf('#')>-1){
alert("Your email must contain an #");
}
}
}
//without .preventDefault() the submitted form would be refreshed
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" id="reg_name" value={this.state.value} onChange={this.handleChange} /><br/><br/>
Email:
<input type="text" id="reg_email" value={this.state.email} onChange={this.emailChange} /><br/><br/>
Phone:
<input type="text" id="reg_phone" value={this.state.phone} onChange={this.phoneChange} /><br/><br/>
Password:
<input type="password" name="reg_password" value={this.state.password} onChange={this.password} /><br/><br/>
Is this an manager account:<br/>
<input type="checkbox" name="reg_manager" value={this.state.manager} onChange={this.manager}/> <br/><br/>
</label>
<br/>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
</script>
</body>
</html>
PHP page to insert database.
<!DOCTYPE html>
<?php
include ("includes/header.php");
$firstname = $_POST['reg_fname'];
//$lastname = $_POST['reg_lname'];
$email = $_POST['reg_email'];
$phone = $_POST['reg_phone'];
$password = $_POST['reg_password'];
//$password2 = $_POST['reg_password2'];
$manager = $_POST['reg_manager'];
if ($manager='on') {
$dbadmin = 1;
}else{
$dbadmin = 0;
}
$query = "INSERT INTO users(firstname,,email,password,manager) VALUES(?,?,?,?,?)";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//prepare and bind
if ($stmt = $dbo->prepare($query)) {
$stmt->bind_param("sssss", $firstname,$email,$hashed_password,$dbadmin);
$stmt->execute();
$stmt->close();
}
?>
<html>
<head>
<title>Registered user</title>
</head>
<body>
<h2>Registered User<?php echo ($firstname) ; ?></h2>
</body>
</html>
you can use axios in react ensuite
after you use his post and get functions ...
via the link of your API or backend
here is an example
  axios.post (http://localhost: 8800/ data /, {username: username}). then (res => {
     console.log (rec); // for example print : i get username from backen
   });

The PHP don't add the value to an external file

I write this little script of PHP but when I press the button "Add" it don't add the value to the json.json file, can you tell me what is wrong? The objective is take the values introduced by user on the box add.name and add-link and save it to the json.json file. Have I to call the php script on a html line?
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
<?php
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($json, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $jsonString);
?>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" name="addname" id="add-name" placeholder="Name"></input>
<input type="text" name="addlink" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Box/Table Configuration (Sites/edit/delete)
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
var el1 = document.getElementById('edit-name1');
el.value = Checker[item].name;
el1.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
var url1 = el1.value;
if (url) {
Checker[item].url = url1.trim();
Checker[item].name = url.trim();
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
//Close button (Edit bar)
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
I think you are not using your variables in the right way. json_decode should use $jsonContents and file_put_contents should use $json
Since you are using post variables, you might want to check if it is a post first.
Try it like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($jsonContents, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $json);
}

I need to pass multiple check boxes from jquery to php and GET is as an array in php

i need to pass a get variable via jquery, one of the form fields is a multiple check box. so i want to be able to pass it so that from php i can use GET and collect it then use IMPLODE to get such a value but its not working
JQUERY CODE HERE
$(document).ready(function(){
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
var FilterByOrder = $("#FilterByOrder").val();
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
var Highlights = $("#Highlights").val();
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, Highlights: Highlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
THE PHP VERSON
<?php
if(isset($_GET['FilterByOrder'])){
echo 'filter '. $FilterByOrder=$_GET['FilterByOrder'].'<br>';
echo 'location '.$location=$_GET['location'].'<br>';
echo 'sort '.$sortFilter=$_GET['sortFilter'].'<br>';
echo 'highlits '.$Highlights=$_GET['Highlights'].'<br>';
echo 'here is the one!';
}else
{
echo'lets run it';
}
?>
THE HTML FORM FIELD
<input type="checkbox" name="Highlights[]" value="<?php echo $DisplayedHighlightID; ?>" id="Highlights">
$(document).ready(function(){
var searchValue = $("#searchValue").val();
$.get('actionfilter.php', {searchValue: searchValue}function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
if($("#FilterByOrder").prop("checked") == true){
var FilterByOrder = 'on';
}
else
{
var FilterByOrder = 'of';
}
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
/* declare an checkbox array */
var HighlightsArrays = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".Highlights:checked").each(function() {
HighlightsArrays.push($(this).val());
});
/* we join the array separated by the comma */
var selectedHighlights;
selectedHighlights = HighlightsArrays.join(',') + ",";
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, selectedHighlights: selectedHighlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
<script language="JavaScript">
function toggle() {
if($("#check-buton").prop("checked") == true){
$('.chkall').prop('checked', true);
}else{
$('.chkall').prop('checked', false);
}
}
$('#industry').click(function(){
if($('#s').val().trim())
{
window.location.href= '<?php echo base_url();?>search?industry_id='+$('#industry_id').val().trim()
}else{
$('#alert_error').text('Please Select Industry').show();
return false;
}
});
</script>
<div class="loginAccount">
<form method="post" name="search" action="<?php echo base_url();?>search">
<h3>Search by Industry :</h3>
Select All: <input type="checkbox" name="industry_id[]" id="check-buton" value="" onclick="toggle()">
<ul class="searchbyindustry">
<?php
if($Industries)
{?>
<?php
foreach($Industries as $Industry)
{
?>
<li> <input type="checkbox" name="industry_id[]" class="chkall" value="<?php echo $Industry['id'];?>"> <?php echo $Industry['industry_name'];?>
</li> <?php
} }
?>
<br/>
<br/>
<!-- <button type="button" id="industry">Search</button>-->
<input type="submit" name="submit" value="Search">
</ul>
</form>
<?php
if(_inputPost('industry_id'))
{
$ind=implode(',', _inputPost('industry_id'));
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}else if(_inputGet('industry_id'))
{
$ind= _inputGet('industry_id');
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}
else if(trim(_inputGet('s')))
{
$s = trim(_inputGet('s'));
$flag = true;
$condition = ' and (name LIKE '.$this->db->escape('%'.$s.'%').' or mobile_office LIKE '.$this->db->escape('%'.$s.'%').' or mobile2 LIKE '.$this->db->escape('%'.$s.'%').' or email2 LIKE '.$this->db->escape('%'.$s.'%').")";
$extraparams = '?s='.$s;
}

Ajax call not replacing the content

What I want to do is replace the content of a div after a log in with a welcome message. I've read AJAX tutorials but I might've got it wrong.
Isn't the logIn function supposed to change the content of the element with the given id, with the content echoed by the php file?
Because right now, the log in is done but the content echoed by the php file is displayed in login.php instead of replacing the content of my "user_panel" div.
My html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My awesome blog!</title>
<script>
function logIn(u,p) {
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div class="nav">
<div class="container">
<div id="user_panel">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
</div>
</div>
<form class="login" action="login.php" method="post">
<label class="login_label" for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label class="login_label" for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="Login" onclick="logIn(document.getElementById('username'),document.getElementById('password'))">
</form>
</body>
</html>
my php
<?php
$server = "localhost";
$username = "root";
$password = "123456";
$dbname = "BlogDb";
// Create connection
$con = mysqli_connect($server, $username, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully2";
$u = $_POST['username'];
$p = $_POST['password'];
setcookie("User_in", $u, time() + (86400 * 30), "/");
// Set session variables
$_SESSION["user_on"] = $u;
$sql= "SELECT username,is_admin FROM User WHERE username ='".$u."' and password='".$p."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<ul>";
echo "<li>";
echo "Welcome " . $row['username'] . "! How are you today?";
echo "</li><li>";
echo "<a href=logout.php>Log out</a>";
echo "</li></ul>";
}
mysqli_close($con);
?>
What am I doing wrong here?
the input type='sumbit' when clicked where submit this form so you must prevent this default event you can change this type='button'!
document.getElementById('username') where return node n't input value get input value can use
document.getElementById('username').value
below is my change code:
html:
<input type="submit" value="Login" onclick="logIn()">
js:
function logIn(e) {
e = e || window.event;
e.preventDefault();
var u = document.getElementById('username').value,
p = document.getElementById('password').value;
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
*** This is a comment as I don't have access to the comment section I am adding as answer******
Hi Matt,
If Ajax is used there is no need to use html-->input-->submit. Use a <button> tag
and then invoke the js function.

Categories