PHP GET variable not being set - javascript

I have a registraion php class that displays a form and when the registration button is clicked, calls a function in a login javascript file. This file uses ajax to post data to a index.php file. My index.php file cannot access this data, despite the post being a success (ajax success is true as the alert is being called).
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
urlPath = "../index.php?action=register";
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
})
}
index.php
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
if(isset($_GET['action'])) {
if($_GET['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
?>

You used POST method of ajax. So send data also in POST manner like below:-
// Send the login/registration data to database
$(document).ready(function() {
var username = $("#usernameField").val();
var email = $("#emailField").val();
var password = $("#passwordField").val();
$.ajax({
type: "POST",
url: "../index.php",
data: {"username":username,"email":email,"password":password,"action":"register"},
success: function (result) {
alert(result);//check the change
}
});
});
And then change GET to POST at php end:-
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
//single condition can do the job and use POST instead of GET
if(isset($_POST['action']) && $_POST['action'] == "register" ) {
echo "hello"; //check the change
}
?>
Note:- Please take care of comments too.(added in the code)

loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
});
Try adding the action also in post data and receive it as $_POST
if($_POST['action']) {
if($_POST['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}

Related

Magento insert data into database through ajax

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",

Ajax PHP Follow Script - Nothing stored in the database

I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!
try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way

JqueryAjax and php logic

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.

Ajax Validate username and password

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.

Passing data in ajax JQUERY

I'm creating a Login page with ajax and JQuery.
Here is my code for ajax:
<script>
$(document).ready(function() {
$('#login').click(function(){
var username=$("#username").val();
var password=$("#password").val();
var url = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: url,
cache: false,
success: function(responceText){
document.write(responceText);
if(responceText==1){
document.write('____Welcome____');
}
else if(responceText==0){
document.write('____Login Failed____');
}
else if(responceText == -1){
document.write('____Some Thing went wrong____');
}
}
});
}
return false;
});
});
</script>
And here is the ajaxLogin class:
<?php
include("db.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password'])){
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=md5(mysqli_real_escape_string($db,$_POST['password']));
$result=mysqli_query($db,"SELECT user_id FROM users WHERE user_name='$username' and user_pass='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($count==1) echo 1;
else echo 0;
}
else{
echo -1;
}
?>
I've debugged the code and i thing the url which i'm passing to the ajax login is not working fine. The values for username and password are null when i load ajaxLogin.php. What is the problem with my url?
var url = 'username='+username+'&password='+password;
is responceText integer ? are you sure about it ? you can try like
success: function(responceText){
responceText = parseInt(responceText);
document.write(responceText);
also... you can pass values in better way by construct it as an object...
var url = {
'username': username,
'password': password
}
Your url contains data for GET method. For POST you need to pass data like this:
data: {username: username, password: password}

Categories

Resources