hye.. im trying to create a quiz game but now im stuck and already spend hours to try transferring local storage data into database but still the data can't be recorded in database.
this is my js code:
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var score = $(this).val();
localStorage.setItem(id, score);
});
location.href = "wheel2.html";
});
then, to show collected marks:
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect+=10;
}
}
score.append('You got ' + numCorrect + ' marks!! ');
return score;
}
im also already try to use this code:
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "marks" + score;
xhr.open("POST", "marks.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
this is my php code:
<?php
//provide your hostname, username and dbname
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test1";
$conn = new mysqli($host, $user, $password, $dbname);
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$sql = "INSERT INTO participant (marks)
VALUES ('".$_POST['marks']."')";
{
echo"<script>alert('successfully registered')</script>".' back ';
header('location:wheel.html?message=success');
}
?>
Related
I've tried to host my website to a provider but it looks like it doesn't want to login there.. On the localhost it works just fine, but uploaded at a provider it looks like it doesn't want to perform the login operation...I can successfully sign-up, change password, so basically I have database connection, but I just can't login to the website... Is it something I should modify? Here's my code:
If I'm entering for example https://example.com/login.php?enterID=123&password=123 in the website link,I can get a good response, but it looks like it doesn't allow me to login to the website..
Login.php:
<?php
include "mysql-connect.php";
//get Info from login.html
$ID = $_GET['enterID'];
$PW = $_GET['password'];
$stmt = $connect->prepare("SELECT PW, userType, nickName FROM users WHERE ID = ?");
$stmt->bind_param("s",$ID);
$valid = $stmt->execute();
if (!$valid){
die("Could not successfully run query.". $connect->connect_error);
}
$result = $stmt->get_result();
if ($result->num_rows==0){
//display message of no such student/teacher/admin
echo "Failed to find an account with the input ID.";
} else {
$row = $result->fetch_assoc();
if ($PW == $row['PW']) {
$type = $row['userType'];
$nick = $row['nickName'];
//save data, record cookie for 6hours
setcookie("type", $type, time() + 21600, '/');
setcookie("userID", $ID, time() + 21600, '/');
setcookie("nickName", $nick, time() + 21600, '/');
//login success - Request.responseText to checklogin.js
echo $type;
} else {
//display message of password error
echo "The input password does not match the account password.";
}
}
$connect->close();
?>
checklogin.js:
function login() {
var enterID = document.getElementById("enterID").value;
var password = document.getElementById("password").value;
if ((password != "") && (enterID != "")) {
var Request = new XMLHttpRequest();
var info = "?enterID=" + enterID + "&password=" + password;
Request.open("GET", "php/login.php" + info, true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "page/teacher-dashboard.php";
} else{
document.getElementById("errorMessage").innerText = respond;
}
}
} else {
document.getElementById("errorMessage").innerText = "Please fill in all the fields.";
}
}
function redirect() {
var Request = new XMLHttpRequest();
Request.open("GET", "php/redirect.php", true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond != "not logged.") {
if (respond == "admin") {
window.location.href = "page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "page/teacher-dashboard.php";
}
}
}
}
Redirect.php:
<?php
if (isset($_COOKIE["type"])){
setcookie("type", $_COOKIE["type"], time() + 21600, "/");
setcookie("userID", $_COOKIE["userID"], time() + 21600, "/");
setcookie("nickName", $_COOKIE["nickName"], time() + 21600, "/");
echo $_COOKIE["type"];
} else {
echo "not logged.";
}
?>
TImeoutAndRedirect function:
function TimeoutAndRedirect(Type) {
var Request = new XMLHttpRequest();
Request.open("GET", "../php/redirect.php", true);
Request.send();
Request.onload = function() {
var respond = Request.responseText;
if (respond == "not logged.") {
alert("Your login period has expired! Please login again!");
window.location.href = "../login.html";
} else if (respond != Type) {
alert("You cannot access this page using your account!");
if (respond == "admin") {
window.location.href = "../page/admin-system-management.php";
} else if (respond == "student"){
window.location.href = "../page/student-dashboard.php";
} else if (respond == "teacher"){
window.location.href = "../page/teacher-dashboard.php";
}
}
}
}
I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
Dears
I called a javascript function on onload body
<body onload="loadLeads()">
This function loads a leads information from database and display it in a table.
The problem is when the user press on delete button to delete a lead from the table. the function runs correctly and delete the lead from the database. BUT although the deletelead function relaoad the page which calls loadLeads() on load the page which should display the new leads without the deleted one. BUT the deleted one display again! although it deleted from the database!!
how can I run it correctly??
I should delete the cache of the browser each time to force the code runs correctly!!
how can I do it please?
this is the javascript code for delete
function deleteLead(id)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
location.reload();
}
}
xmlhttp.open("GET", "deletelead.php?id="+id, true);
xmlhttp.send();
}
This is the script calling in the HTML
<script src="https://example.net/js/loadLeads.js?version=' + Math.floor(Math.random() * 100) + '"\><\/script>'"></script>
This is the loadleads function javascript
function loadLeads()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
LeadsInfo = JSON.parse(this.responseText);
LeadsInfoCount = LeadsInfo.length;
DrawLeadsTable();
}
}
xmlhttp.open("GET", "LoadLeads.php", true);
xmlhttp.send();
}
This is the LoadLeads.php
<?php
require "conn.php";
$SelectSQL = "SELECT * FROM leads";
$result = $conn->query($SelectSQL);
$ECount = $result->num_rows;
if ($ECount != 0 )
{
$FinalArr = array();
$count =0;
while($row1 = $result->fetch_assoc())
{
$id = $row1["id"];
$name = $row1["name"];
$email = $row1["email"];
$mob = $row1["mob"];
$country = $row1["country"];
$comefrom = $row1["comefrom"];
$time = $row1["time"];
$qulified = $row1["qulified"];
$landingpage = $row1["landingpage"];
$myArr = array($id,$name,$email, $mob,$country,$comefrom,$time,$qulified,$landingpage);
$FinalArr[$count] = array();
$FinalArr[$count] = $myArr;
$count++;
$UserData = json_encode($FinalArr,JSON_UNESCAPED_UNICODE);
}
}
mysqli_close($conn);
echo $UserData;
?>
Add this before the xmlhttp.send();
xmlhttp.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
I'm creating a mobile web app where user will be able to upload its picture and use it as an avatar. Testing it in android studio emulator everything works fine and the successful function alerts that everything is done. However my $_POST and $_FILES are empty.
JS:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
var win = function (r) {
clearCache();
retries = 0;
alert('Done!');
}
var fail = function (error) {
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Ups. Something wrong happens!');
}
alert(error);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.username = curr_username;
alert('username: ' + params.username);
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("some-server/file_upload.php"), win, fail, options, true);
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 100,
destinationType: destinationType.FILE_URI
});
}
function onFail(message) {
alert('Failed because: ' + message);
}
PHP:
<?php
$con = mysqli_connect("localhost","db_user","db_user_pw","db_name") or die(mysqli_connect_error());
// ako u javasdcriptu nemaš pristup user_id-u, treba poslat username i ovdje fetchat iz baze odgovarajući user_id
$output = print_r($_POST, true);
file_put_contents('username.txt', $output);
$output = print_r($_FILES, true);
file_put_contents('file.txt', $output);
$username = $_POST['username'];
$tmp_file_name = $_FILES["file"]["tmp_name"];
$file_name = "images/" . $username . '.jpg';
// remove the file if exists
if(file_exists($file_name)) {
unlink($file_name);
}
// upload new file
move_uploaded_file($tmp_file_name, $file_name);
$file_name = "path_to_images_folder/".$file_name;
// update database
$q = mysqli_query($con,"UPDATE users SET avatar = '$file_name' WHERE id = (SELECT id WHERE username = '$username')");
if($q)
echo "success";
else
echo "error";
?>
Any ideas why this is happening since i'm loosing my mind
Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}