Populating span/div with database record - php

I apologise if this comes across as really stupid. I have searched but can't seem to find an answer. I hope I can explain what it is I am trying to do.
I want to be able to query a database and if there is a record in it to show the record in the span/div or show a not found error message if there isn't.
I have a jquery check up and running to check if a username is in the database, what I want to know is how easy it would be to ammend this to pull all the data and show it in the span/div on the original page.
This is the jquery I have:
$(document).ready(function () {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if (username == "" || username.length < 2) {
$('#username').css('border', '1px #D5D5D5');
$('#cross').hide();
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function (response) {
if (response == 1) {
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
Can I do all this on the one page and query the db from the same page, instead of posting it to another page as I don't know how to get the results back to the calling page?
I hope I have explained what I want to do. Apologies if I haven't
Here is the PHP code:
$username = trim(strtolower($_POST['username'])); $username = mysql_escape_string($username); $query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1"; $result = mysql_query($query); $num = mysql_num_rows($result); echo $num; mysql_close()

You will normally send ajax requests to pages hosted on your server. So you can't directly access your database without going through your server. You'll need to write a function on your server that queries the database, and then call that function from javascript using ajax.

You can output a string in PHP and then set that text value to an element with jQuery ( $('#element').val(responseFromServer);
or $('#element').html(responseFromServer);

Instead of sending back "1" send back a json response something like:
/* record exists */
{status:1, html:'server generated message about record'}
/* doesn't exist */
{status:0}
This will allow you to still change css based on response data status value
Can use $.post ajax shorthand method:
$.post('check.php',{username: username}, function(response){
var upDateElement=$('#spanID');
if(response.status && response.status== 1){
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
upDateElement.html( response.html)
}else{
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
upDateElement.html('Message html for no record found')
}
},'json')

check.php
$data = array();
$data['exists'] = false;
if(!isset($_POST['username'])) {
echo json_encode($data);
exit();
}
$username = mysql_escape_string($_POST['username']);
$query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(count($row) == 1) {
$data = $row;
$data['exists'] = true;
}
return json_encode($data);
from your jQuery:
success: function(response) {
/**
* For instance, for a table with id, username, password and email you have
* data.exists = true/false;
* data.id = 1;
* data.username = 'foo';
* data.password = 'sample data password';
* data.email = 'foo#bar.com';
*/
if(response.exists === true) {
$('#username').val(response.username);
$('#email').val(response.email);
}
}

Related

if statement in success ajax

I'm having trouble implementing if statement in ajax success function.
<?php
include('../Config/config.php');
$myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
$execute = mysqli_query($mysqli, $myquery);
if (mysqli_num_rows($execute) >= 1)
{
echo "Precinct is full.\n Recheck precinct number.";
}
?>
function checkerprecinct() {
var precinct = $("#precinct").val();
$.ajax({
type: "POST",
url: "precinctchecker.php",
data: "precinct=" + precinct,
success: function(data) {
console.log(data);
if (data === "") {
alert("Data is empty!");
} else {
alert(data);
}
}
});
}
I would like to use this as a validation.
I want to alert the user if the sent data contains similar data from the database.
try this code
change with your code
PHP Code:
$data = array();
if (mysqli_num_rows($execute) >= 1)
{
$data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
//echo "Precinct is full.\n Recheck precinct number.";
}else{
$data= array('code'=>101,'message'=>"Data is empty!");
}
echo json_encode($data);
exit;
ajax code:
var data = JSON.parse(data);
if (data['code'] == 100) {
alert(data['message']);
}

Javascript, Php, Ajax

I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.

Return a boolean from a PHP file to the AJAX one - Follow button

I'm creating a follow button, more or less like the twitter one.
You click the button, and you follow the user.
You click again, and you unfollow the user.
I have done this code
HTML
<div data-following="false" class='heart canal'><i class='fa fa-heart awesome'></i></div>
AJAX
$(document).ready(function() {
$(".heart.canal").click(function() {
if($(".heart").attr("data-following") == '0'){
$(".heart").attr('data-following', '1');
} else if($(".heart").attr("data-following") == '1'){
$(".heart").attr('data-following', '0');
}
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");
var seguir = $(".heart").attr("data-following");
$.ajax({
type: "POST",
url: "./include/php/follow.php",
data: { user: usuario, follower: seguidor, follow: seguir },
success: function(response) {
if(response == '0'){
$(".heart").addClass("like");
} else if(response == '1'){
$(".heart").removeClass("like");
}
}
});
return false;
});
});
PHP
<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$sql = "";
$user = $_POST["user"];
$seguidor = $_POST["follower"];
$follow = $_POST["follow"];
if($follow == '0'){
$sql = "INSERT INTO seguidores(id_canal, id_seguidor) VALUES('$user', '$seguidor')";
} else if($follow == '1'){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
}
if($conexion){ $resultado = $conexion->query($sql); }
return $follow;
?>
The problem is, everytime I click the button, I only insert data in the database. I mean, I only create follows.
When I click twice, it doesnt remove the follow.
Is there anyway to insert data when data-following = true and remove it when data-following = false ?
UPDATED
I have changed the boolean false and true for 2 strings, 0 and 1. But it doesn't work anyway.
There are numerous problems here. For one, like #Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.
Try the following:
JS:
$(document).ready(function () {
$(".heart.canal").click(function () {
var $heart = $(this);
if ($heart.data("following")) {
$heart.data("following", false)
} else {
$heart.data("following", true);
}
var usuario = $(".left").find("h4").data("id");
var seguidor = $("#user_account_info").find(".profile_ball").data("id");
$.ajax({
type: "POST",
url: "follow.php",
data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
success: function (result) {
if (result) {
console.log("true");
} else {
console.log("false");
}
}
});
return false;
});
});
PHP:
$user = (int)$_POST["user"];
$seguidor = (int)$_POST["follower"];
$follow = ($_POST["follow"] === 'true') ? true : false;
if ($follow) {
// insert
} else {
// delete
}
print $follow;

Developing the login page in Phonegap using Ajax and on server MySQL

I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request

AJAX username Availability

I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.

Categories