This is my ajax code:
$(document).ready (function() {
$("#send").click (function() {
var username = $(this).val();
alert (username);
$.ajax({
url : "sendpost.php",
type: 'POST',
async: false,
data: {username},
success: function(datat){}
})
});
});
This is my php code
include ('connection_socio.php');
if(isset($_POST['body']))
{
$body=mysqli_real_escape_string($db, $_POST['body']);
$date_added="123";
$added_by="123";
$username = mysqli_real_escape_string($db, $_POST['username']);
$check = "SELECT * FROM users";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$user_posted_to = $username;
echo $user_posted_to;
$query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";
mysqli_query($db, $query_post);
echo "POSTED SUUCESSFULLY";
}
This is my profile.php code:
if (isset($_GET['u']))
{
$username = mysqli_real_escape_string($db, $_GET['u']);
//checks and remove symbols like # , ' etc
if(ctype_alnum($username))
{
//check user existance
$check = "SELECT * FROM users WHERE username='$username'";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
if(mysqli_num_rows($result_profile) == 1)
{
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$username = $getusername['username'];
}
else
{
echo "User dont exist";
exit();
}
}
}
what I want is to fetch variable $username from profile.php page and assign it to $user_posted_to variable in senpost.php page and insert into database using javascript if any expert can help will really appreciate it i have tried this.attr() but thats not working also this.value is also not working I'm unable to fetch username from that page can anyone help me with this the username variable i want to fetch is the username of the user profile which I want to assign to $user_poste_to
I believe, the best way to access the value of $username is to store it to a cookie, once you are in senpost.php, all you need to do is to get the cookie you stored and assign it to $user_posted_to variable. the correct way to get the value of a textbox/form element in by using this $(input[type="text"]).val()
Update your AJax call.
data: {username:username},
here first username will be the index and 2nd username will be the variable which you got using $(this).val()
Related
I wanted to store the value "totalscore" from my JavaScript code to my database. I tried using ajax call but something is not working, I have not used ajax before.
In the following JavaScript code, I display the value of score which i have found to the html element.
JavaScript code:
if (matches==8){
var totalscore = calcScore();
document.getElementById("score").innerHTML=totalscore;
}
I want to save the value of totalscore in my users database when the submit button is clicked. So i tried something like :
$("#sendscore").on("click",function(){
gamescore= document.getElementById('score').innerHTML;
$.ajax({
type:'POST',
url: 'score-processor.php',
data:{
gamescore: gamescore,
}
})
});
the php code :
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
header('location: profile.php');
}
else {
array_push($errors, "Wrong username/password combination");
}
}
}
if(isset($_POST['gamescore'])){
$fetch = "SELECT id FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$gamescore= $_POST['gamescore'];
$updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
mysqli_query($db, $updatescore);
}
}
In my html :
<?php session_start();?>
<body>
<p>Your score: <span id=score></p>
<button id="sendscore" class="Go-on">Submit</button>
the database table has columns , id, username, email, password and score.
the value for columns id, username, email and password are collected during login/register.
The game runs smoothly and presents the score but when I click the submit button which on clicked should add the value to the table, but nothing happens, no errors in the log and the value is not added to the table.
Problem 1
gamescore= document.getElementById('score');
This is an HTML element, not the value of it.
You need to read the .innerHTML just like you wrote to it earlier
Problem 2
gamescore: gamescore
jQuery.ajax doesn't have a gamescore option. So this is meaningless.
You need to pass data.
data: {
gamescore: gamescore
}
Problem 3
contentType: false,
This stops jQuery overriding the content-type when you pass a FormData object to generate a multipart request (which is useful for uploading files).
You aren't doing that, so contentType: false will break the normal allocation of the correct Content-Type header.
Remove that
Problem 4
processData: false
You need the data to be processed. The object you pass to data needs encoding into the HTML request.
Remove that.
Problem 5
$updatescore= "UPDATE users SET(username='$username', score='$gamescore') WHERE (id='$id')";
You failed to define $username or $id.
Hye, I faced a problem where I need to create a log in that can only be access by specific id from my database table. how can I solve the problem where I just need to login by using admin_id = 1 for example, and there are no other user can login except this one id only because I put the admin and user login data inside of the same login tables. Help me solve this problem. Here my coding in php scripts. Thank you for helping.
<?php
if(ISSET ($_POST['login'])){
$faculty_department = $_POST['faculty_department'];
$password = $_POST['password'];
$query = $conn->query("SELECT * FROM `user` WHERE `faculty_department` = '$faculty_department' && `password` = '$password'") or die(mysqli_error());
$fetch = $query->fetch_array();
$row = $query->num_rows;
if($row > 0){
session_start();
$_SESSION['admin_id'] = $fetch['admin_id'];
header('location:home1.php');
}else{
echo "<center><labe style = 'color:red;'>Invalid faculty_department or password</label></center>";
}
}
?>
Just add a WHERE condition to allow only admin access, assuming admin_id is 1
SELECT * FROM `user`
WHERE `faculty_department` = '$faculty_department'
AND `password` = '$password'
AND `admin_id` = '1'
I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";
<?php
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
if ($_GET['type'] == "upload")
{
$title=$_GET['title'];
$creator=$_GET['creator'];
$ingredient=$_GET['ingredient'];
$serving=$_GET['serving'];
$note=$_GET['note'];
$prepare=$_GET['prepare'];
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUE ('$title','$creator','$ingredient','$serving','$note','$prepare')";
if(mysql_query($insertsql,$db))
{echo 1; }
else
{echo 0; }
}
?>
<script>
$.ajax({
type : "get",
url : "dataconn.php",
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredien t+"&serving="+serving+"¬e="+note,
success : function(data){
alert(data);
}
});
</script>
</head>
</html>
When I pass variable in to PHP from JavaScript it able to save in database but I need some value like the data have been successful save and will come out a alert 1 or 0.
But once I connect to database it cant alert any more. Like some error blocking in database but still can save just does not come out any alert. If I remove it then it running all
It does not sure alert as well.
Change this line:
if(mysql_query($insertsql,$db))
To this line; using mysqli_* extensions and correctly using $con for the query instead of $db which is a connection variable you don’t have set anywhere:
if(mysqli_query($con,$insertsql))
Also, you should set your MySQL calls to return errors like this:
$con=mysqli_connect("localhost","root","","recipe") or die(mysqli_connect_errno());
And change this as well:
$result = mysqli_query($con,$insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
Also you are using VALUE in the query when it should be VALUES:
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUES ('$title','$creator','$ingredient','$serving','$note','$prepare')";
Not to mention in your JavaScript AJAX code you have +ingredien t+ when it should be +ingredien t+:
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredient+"&serving="+serving+"¬e="+note,
At the top why are you setting variables for the MySQL connection but then putting values inline?
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
And finally, I did a cleanup of your main MySQL logic code. I have included mysqli_stmt_bind_param, mysqli_free_result & mysqli_close and set a foreach loop for $_GET values. This simply should work:
// Credentials.
$host="localhost";
$user="root";
$password="";
// Connecting, selecting database
$con = mysqli_connect($host, $user, $password, 'recipe') or die(mysqli_connect_errno());
if (isset($_GET['type']) && !empty($_GET['type']) && $_GET['type'] == "upload") {
// Set a '$_GET' array and roll through each value.
$get_array = array('title', 'creator', 'ingredient', 'serving', 'note', 'prepare');
foreach ($get_array as $get_key => $get_value) {
$$get_value = isset($_GET[$get_value]) && !empty($_GET[$get_value]) ? $_GET[$get_value] : null;
}
// Set the query.
$insertsql = "INSERT INTO `upload` (`title`, `creator`, `ingredient`, `serving`, `note`, `prepare`)"
. " VALUES (?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($insertsql, 'ssssss', $title, $creator, $ingredient, $serving, $note, $prepare);
// Run the query.
$result = mysqli_query($con, $insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
}