Passing data in ajax JQUERY - javascript

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}

Related

PHP GET variable not being set

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>';
}
}

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

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.

Categories

Resources