I'm trying to use jQuery to check if the username that the user entered in a form is already taken. Below are the relevant codesnippets in Java, and existence.php.
*javascript*
var username = document.register.username.value;
usernameTaken = checkUserExistence(username, 'username');
function checkUserExistence(str, type){
var dataString = '?str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existence.php",
data: dataString,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
$("#submit").val('Succes!');
return 1;
}else{
$("#submit").val('Failure!');
return 0;
}
}
});
}
return false;
}
*/JavaScript*
<?php
include("inc/connect.php");
$data = $_POST["str"];
$type = $_POST["type"];
switch($type){
case "username":
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
break;
}
?>
What am I doing wrong?
My website is supposed to show live hints to the users, like 'your username is too short' etc. All hints are working, but the ones where it should say 'your username is already taken' won't show. The form gets processed to my PHP-register function, where usernames that are already taken get rejected, so somehow the checkUserExistence-function and the existence.php page are not working.
Edit:
For a live demonstration of my code, go to:
http://beta.somentus.nl/index.php
The usernames 'Admin', 'Somentus' and 'Rik' are already taken, try them out :)
$data = $_POST["data"];
should be:
$data = $_POST["str"];
Related
I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",
Hey guys im with a problem getting a value from php. I know we have a lot of problems with this kind of issues, but i need help.
This is my javascript
$( document ).ready(function() {
$(".loading_bg").hide();
});
$( document ).ajaxStart(function() {
$(".loading_bg").fadeIn("slow");
});
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
and this is my php
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_POST['function'])) {
$user = $_POST['username'];
$password = $_POST['password'];
echo login::validate_user($user, $password);
}
class login {
static function validate_user($username, $password) {
//Call a new default connection
$db = db::connect();
//Prepare our sql
$stmt = $db->prepare("SELECT * FROM Accounts WHERE username = :username AND password = :password");
//Bind our values to the SQL statement
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
//Get number of affected rows
$results = $stmt->rowCount();
//If to check if we can find any row with username and password
if($results === 1) {
//return json_encode("valid account");
} else {
return json_encode($username);
}
}
}
?>
When i do the request im getting a undifned error from my var, i dont know how to fix it, can someone help me, if possible.
I think its something with my $_POST.. because if run the php with login::validate_user("teste","teste); i can get the json result..
Everything else is fine, you are not passing data correctly to ajax call. You are making query string but you have to pass JSON object if you want to capture it in $_POST in php and can append to url if you want to capture in $_GET array. I have corrected your function in both ways below:
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = { 'function': 'validate_user', 'username': username, 'password': password }
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
When you want to capture data in $_GET at server side
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php?' + datastring,
data: {},
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
Here is PHP Code
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_GET['function'])) {
$user = $_GET['username'];
$password = $_GET['password'];
echo login::validate_user($user, $password);
}
.... // Remaining Class will come here
Im sorry to bother all of you, the real problem its my form input feilds.. i forgot to set a class... Thank you all, and once again, im sorry to make you lose time with such a silly problem.
I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.
So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})
I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.
I need help! I have this code that work very good to validate username in mysql database using Ajax, php and Javascript but when I try to add for validate the password too not work and I have been test all possible ways in my mind!
-- Code in html page to validate username
function admin_search(){
$("#checkuser").click(function(){
var user_name = $('#admin_user').val();
if(user_name == ""){
$("#disp").html("");
}
else{
$.ajax({
type: "POST",
url: "checklogin_admin.php",
data: "user_name="+ user_name ,
success: function(html){
$("#disp").html(html);
}
})
return false;
}
})
}
-- Code in checklogin_admin.php
if(isset($_POST['user_name'])) {
$user_admin = mysql_real_escape_string($_POST['user_name']);
$query = mysql_query("SELECT * FROM $tbl_name WHERE user='$user_admin'");
$row = mysql_num_rows($query);
if($row == 0) {
echo "<span style='color:red;'>NOT EXIST</span>";
} else
{
echo "<span style='color:green;' id='exist'>EXIST</span>";
}
Im tying to add for validate the password too with this:
function admin_search(){
$("#checkuser").click(function(){
var user_name = $('#admin_user').val();
var user_pass = $('#admin_pass').val();
if((user_name == "") & (user_pass == "")){
$("#disp").html("");
}
else{
$.ajax({
type: "POST",
url: "checklogin_admin.php",
data: "user_name="+ user_name
"user_pass="+ user_pass,
success: function(html){
$("#disp").html(html);
}
})
return false;
}
})
}
But, nothing works!
Data should send a single structure ...
data: { "user_name": user_name,
"user_pass": user_pass },
... you could also do something like this ...
data: "user_name=" + user_name + "&" + "user_pass=" + user_pass,
I personally would recommend the first method ...
In both, be careful of sending the username and password in the clear as part of the URL.
You'll have to adjust the backend PHP to account for the data being sent.