Couldn't get response from database with jQuery using PHP post request - php

I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>

<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>

You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});

Related

Handling currencies and account deliveries with php

My site works like this:
User has a balance stored in a database under column named currency. He earns currency then after earning enough he goes to another page to get accounts in exchange of these currencies. I set up everything but something is bugging me since an hour. If user has enough currencies and he retrieve an account, he can refresh and retrieve another account and even though he doesn't have enough currencies my system is still giving him his account on firefox but not on chrome (There are the browser I have tested until now) I'm handling this with session, ajax, and php to handle the delivery and here is the codes:
1. In the file below: I check how much the user has currencies and assign an ability session which will then be checked when retrieving the accounts. User can either get an account with currency amount of 250 or 1000 or 2500 and I am checking how much currency he can have on account:
<?php session_start();
unset($_SESSION["ability"]);
$unames = $_SESSION['username'];
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database-name", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyamount = $row['currency'];
}
if ($currencyamount<250){
$_SESSION["ability"]= 'zero';
echo $_SESSION["ability"];
}
elseif ($currencyamount<1000) {
$_SESSION["ability"]= 'one';
echo $_SESSION["ability"];
}
elseif ($currencyamount<2500) {
$_SESSION["ability"]= 'two';
echo $_SESSION["ability"];
}
else {
$_SESSION["ability"]= 'three';
echo $_SESSION["ability"];
}
?>
I then have the jquery file listening to this php file, for its echos, which will if the user has an ability of 1 allow him to get an account with 250 currencies, if he has an ability of 2: 1000 currencies, if he has an ability of 3: 2500 currencies. If he has ability 0, he won't get any account if he tries, it alerts him to refresh and if he tries to get two accounts or more without refreshing (Did this because I wanted to unset the session when the page loads again then set them because the abilities may change) The script also deletes each account the user got from the database.
$(document).ready(function () {
var ability = 'zero';
var click = 0;
$.ajax({url: "ability.php"}).done(function( html ) {
ability = html
});
$('#currency2500').click(function(){
if (click==0){
if (ability != 'zero') {
function show_account() {
$.ajax({
type: "POST",
url: "select1.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency250').click(function(){
if(click==0){
if (ability != 'zero') {
var id=$(this).data("id3");
$.ajax({
url:"delete1.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
function show_account() {
$.ajax({
type: "POST",
url: "select2.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
var id=$(this).data("id3");
$.ajax({
url:"delete2.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
function show_account() {
$.ajax({
type: "POST",
url: "select3.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
var id=$(this).data("id3");
$.ajax({
url:"delete3.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
}
});
});
Here is the php file that will deliver the account with 250 currencies to the user, there is also the ones which are the same for 1000, 2500 and with just the value 250 changed. if its called by jquery:
<?php
session_start();
$link = mysqli_connect( 'localhost', 'database-username', 'database-password', 'database' );
$action=$_POST["action"];
if($action=="showroom") {
$query="SELECT * FROM tablename LIMIT 1";
$show = mysqli_query($link, $query) or die("Error");
echo "<p id='paragraph' style='font-size:22px;font-weight: bold;'>Here is your 250 currencies account:</p>";
echo "<table style='position:relative;bottom:30px;' border='2px'><tr><td>Email</td><td>id</td></tr>";
while ($row = mysqli_fetch_array($show)) {
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['id'] . "</td></tr>";
}
echo "</table>";
$unames = $_SESSION['username'];
$query2 = "UPDATE users SET currency=currency-250 WHERE username='$unames'";
$update = mysqli_query($link, $query2);
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyvalue = $row['currency'];
}
unset($_SESSION['currencynumber']);
$_SESSION["currencynumber"]=strval($currencyvalue);
}
?>
Then the page which users gets in: ( Only a part from it )
<?PHP
session_start();
if( !isset($_SESSION['username']) ) {
header ("Location: login.html");
}
<div id="accountinfo"></div>
<input type="button" id="currency2500" value="Get 2500 currencies" />
<input type="button" id="currency1000" value="Get 1000 currencies" />
<input type="button" id="currency250" value="Get 250 currencies" />
So: If using firefox: I can refresh 2-4 times until i can't get accounts anymore and my balance will be negative after getting those accounts. Maybe there is a way that if the balance gets negative to cancel the operation and not show anything to the user? Or how can it be solved? I am using sessions to track.

AJAX catch returned data if statement

I've been pulling my hair out to get this to work but no luck.
I have the below AJAX call;
$("#orderverify-form").submit(function(e) {
$('#loader').show();
e.preventDefault();
initiateCall();
});
function initiateCall() {
// Client side validation
if ($("#phone_number").val() == "") {
$('#loader').hide();
detError();
} else {
$.post("php/corder-verify.php", {
phone_number : $("#phone_number").val()
}, function(data) {
if (data.verification_code == 0) {
console.log(data.verification_code);
numberError();
} else {
console.log(data.verification_code);
showCodeForm(data.verification_code);
checkStatus();
}
}, "json");
}
}
My responses received from PHP are below;
Query successfull
// return verification code as JSON
$json = array();
$json["verification_code"] = $code;
header('Content-type: application/json');
echo(json_encode($json));
exit;
Query not successful
else {
// return verification code as JSON
$json = array();
$json["verification_code"] = 0;
header('Content-type: application/json');
echo(json_encode($json));
exit;
}
Code is just a rand number I'm generating. For failure I just set it to 0.
I never seem to be able to catch the error.
Only the else part of my AJAX if..else statement work :(
Help please.

Stop Execution Php

I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>

Put DIV ID into a PHP Variable

I am wanted to get the id's of all the divs on my page with the class archive and put them in a MySQL query to check and see if the ids are archived in the database.
So basically I am wondering how I can do this: $div = $(this).attr('id');
Then I would throw it into the loop to check:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '$div'");
while ($post = mysql_fetch_assoc($matches))
{
if (mysql_num_rows($matches) > 0)
{
//DO THIS
}
}
UPDATE
I have this code for the AJAX now:
$('div.heriyah').each(function() {
var curID = $(this).attr('id');
$.post("admin/btnCheck.php", { div : curID }, function(data) {
if (data == "yes") {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Add Element</div></div></div><div class=\"clear\"></div></div>');
} else {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Set As Editable Region</div></div></div><div class=\"clear\"></div></div>');
}
});
});
And my PHP:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['div']."'");
if (mysql_num_rows($matches) > 0)
{
echo "yes";
} else {
echo "no";
}
What am I doing wrong?
You cannot throw a javascript variable to PHP script like that. You have to send an ajax request to the page
$div = $(this).attr('id');
$.post("yourquerypage.php", { divid : $div }, function(data) {
// Something to do when the php runs successfully
});
Next, configure your query to get the variable from $_POST()
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['divid']."'");
And of course, you have to take measures for injection.
It's simple syntax error. Remove the condition after the else and you should be fine.
else (data == "yes") { // remove (data == "yes")
// snip
}

check if username exists with bvalidator (jquery validation plugin)

I'm using bvalidator (jquery validation plugin) to check if a username exists in the database. They have an example on their documentation. However, I have no idea how it works. You can read more on that example here:
http://karmela.fsb.hr/~bmauser/bvalidator/documentation.html#serversidevalidation
I tried creating my own. However, It always tells me that the username is already taken no matter what... I'm a complete newbie when it comes to AJAX. I barely know it. So anyway, here's what I created so far...
index.php (the main page)
<script type="text/javascript">
$(document).ready(function () {
$('#register').bValidator(optionsRed);
});
function checkUsername(username) {
$.post("checkusername.php", { username: username }, function(data) {
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;
});
}
</script>
<input type="text" name="username_register" id="textstyleid" data-bvalidator="checkUsername,required,rangelength[5:20]" data-bvalidator-msg="This username is not valid or already taken."/>
checkusername.php (checks if username exists)
<?php
require '../connect.inc.php';
if (isset($_POST['username'])) {
$username = mysql_real_escape_string($_POST['username']);
if (!empty($username)) {
$username_query = mysql_query("SELECT COUNT(uid) FROM users WHERE username='$username'");
$username_result = mysql_result($username_query, 0);
if ($username_result == 0) {
return 0;
} else if ($username_result == 1) {
return 1;
}
}
}
?>
Edit
I noticed a 404 error. I fixed that. The PHP and AJAX is working. It gives me a 0 or 1 depending on the text entered in the preview. However, the problem still exists. I think its because of this line of code. I don't really understand what it means. What is data?:
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;
After looking at it further the problem is your php, you need to use mysql_num_rows around your result to compare with 0 recs returned, the result object itself will only give u a resource id if echo'ed out
Try this one
if (data == 0) {
echo json_encode(TRUE);
} else {
echo json_encode(FALSE);
}

Categories