I am developing a site that has a login form and a newsfeed. when i use ajax as my action to submit values to the controller my controller url disappears instead of having mypage/newsfeed
here is the script im using
$('#submitButton').on('click',function(){
var userid = $('#studentID').val();
var password = $('#password').val();
$('#errorHandler').empty();
var URL = '<?php echo base_url('newsfeed')?>';
if(userid.trim()!='' || password.trim()!=''){
$.ajax({
type:'POST',
url: URL,
data:{userid:userid,password:password},
success:function(data){
if(data)
$("body").load(data);
},error:function(errorw){
if( errorw.status == 400 ) { //Validation error or other reason for Bad Request 400
var json = $.parseJSON( errorw.responseText );
}
$('#errorHandler').append($('<label class="red-text text-darken-2">'+json+'</label>'));
}
});
}else{
$('#errorHandler').append($('<label class="red-text text-darken-2">ID/Password is Required</label>'));
}
});
UPDATE: controller code i am using custom routes $route['newsfeed'] = 'Login/Login';
public function Login(){
$userid = $this->input->post('userid');
$userpw = $this->input->post('password');
$validate = $this->loginmodel->validateAccount($userid,$userpw);
if($validate == NULL){
$this->output->set_status_header('400');
$details = $this->data['message'] = 'Incorrect Login/Password';
echo json_encode($details);
}
else{
$data['details'] = $this->loginmodel->getUserType($userid);
if(is_array($data) || is_object($data)){
foreach ($data as $key => $value) {
$type = $value->accounts_type;
}
}
$this->session->set_tempdata('accountID', $userid,18000);
$userid = $this->session->tempdata('accountID');
$data['init'] = $this->loginmodel->getGroups($userid);
$data['groupId'] = $userid;
if($type == "STUDENT"){
$data['details'] = $this->loginmodel->getDetails($userid);
$token = array(
'accountid' => $userid,
'groups' => $data['init'],
'details' => $data['details'],
);
$this->session->set_userdata($token);
$this->load->view('header');
$this->load->view('sidenav1', $data);
}
elseif($type == "PROFESSOR"){
$data['details'] = $this->loginmodel->getDetailsProf($userid);
$this->load->view('header');
$this->load->view('sidenav2', $data);
}
elseif($type == "ADMIN"){
$this->load->view('header');
$this->load->view('superadmin');
}
else{
$data['details'] = $this->loginmodel->getDetails($userid);
$this->load->view('header');
$this->load->view('Surveypage',$data);
}
}
}
Related
I need an AJAX Login Script for my school project.
But it actually won't work because when I try to login, I get kicked to the startpage (login-form) without any message.
That's my backend-script (login2.php):
if(empty($_POST['loginEmail']) || empty($_POST['loginPassword'])) {
$error[] = "Bitte füllen Sie alle Felder aus!";
}
if (!empty($_POST['loginEmail']) && !filter_var($_POST['loginEmail'], FILTER_VALIDATE_EMAIL)) {
$error[] = "Bitte geben Sie eine gültige E-Mail-Adresse an!";
}
if(count($error)>0) {
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':email' => $_POST['loginEmail']));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0) {
if(!password_verify($_POST['loginPassword'],$row[0]['uPassword'])) {
$error[] = "Falsches Passwort!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
session_start();
$_SESSION['Email'] = $row[0]['uEmail'];
$resp['redirect'] = "dashboard.php";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
else {
$error[] = "Falsche E-Mail-Adresse!";
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
And this is my JS part of the login form:
$(function() {
$('#login').click(function(e){
let self = $(this);
e.preventDefault();
self.prop('disabled',true);
var data = $('#login-form').serialize();
$.ajax({
url: '/login2.php',
type: "POST",
data: data,
}).done(function(res) {
res = JSON.parse(res);
if(res['status']) {
location.href = "dashboard.php";
} else {
var errorMessage = "";
console.log(res.msg);
$.each(res['msg'],function(index,message) {
errorMessage += '<p>' + message + '</p>';
});
$("#error-msg").html(errorMessage);
$("#error-msg").show();
self.prop('disabled',false);
}
}).fail(function() {
alert("error");
}).always(function(){
self.prop('disabled',false);
});
});
});
When I try to add action="/login2.php" in the form I get a HTTP 500 Error and the message, that it can not process this request at this time.
I'm not sure if this is your main problem, but it's a significant one. You're preparing two parameters:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email AND `uPassword` = :password";
But you're only binding one:
$stmt->execute(array(':email' => $_POST['loginEmail']));
You don't want to include the password in the select, since you're using password_verify() to validate it later. Change your SQL to this:
$sql = "SELECT * FROM `users` WHERE `uEmail` = :email";
So I've got my password being passed to a php page and returning json data
However if it returns nothing. nothing happings. My Failed login never fires. Can someone tell what I'm doing wrong.
<script>
$(document).ready(function(){
var password = "";
//PRESSING AN INPUT KEY
$('.sixPinInput').keyup(function (k) {
if (this.value.length == this.maxLength) {
password = password+this.value;
password = password.substring(0,6);
$(this).next('.sixPinInput').focus();
$(".pinIncorrectMessage").css("display", "block");
$(".pinIncorrectMessage").html(password);
}
//PRESSING DELETE
if (k.keyCode == 8) {
$(this).prev().val("").focus();
password = password.slice(0, -1);
$(".pinIncorrectMessage").html(password);
}
});
//PRESSING LAST INPUT KEY
$("#f").keyup(function() {
if($("#f").val().length > 0) {
$.post("http://heber/QC/includes/getUserInfo.php", {user: password}, function(data, status) {
//IF SUCCESSFUL LOGIN
password = "";
$(".sixPinInput").val("");
if(data) {
$(data).each(function(index, value) {
alert(value.firstName + value.lastName)
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
})
}
//IF FAILED LOGIN
if(!data) {
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
}
})
}
})
});
</script>
And this is my PHP
<?php include "db.php"; ?>
<?php
if (isset($_POST['user'])) {
$password = $_POST['user'];
$query = $connect->prepare("
SELECT firstName, lastName, color1, color2, authorizationLevel FROM employee WHERE password = ? LIMIT 1");
if(!$query) {
echo "Query Failed because " . mysqli_error($connect);
}
$query->bind_param("s", $password);
$query->execute();
$result = $query->get_result();
if ($result) {
while($row = mysqli_fetch_assoc($result)) {
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$color1 = $row['color1'];
$color2 = $row['color2'];
$authorizationLevel = $row['authorizationLevel'];
session_start();
$_SESSION['firstName'] = $firstName;
$_SESSION['lastName'] = $lastName;
$_SESSION['color1'] = $color1;
$_SESSION['color2'] = $color2;
$_SESSION['authorizationLevel'] = $authorizationLevel;
$array[] = array (
'firstName'=>$firstName,
'lastName'=>$lastName,
'color1'=>$color1,
'color2'=>$color2,
'authorizationLevel'=>$authorizationLevel
);
}
header('Content-type: application/json');
echo json_encode($array);
}
}
?>
I am trying to check the id's validity using ajax and codeigniter. when The status of the id if it is taken will appear "NPP tidak ada di database".
my contrroler:
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp( $id ); #send the post variable to the model
//value got from the get metho
$id= $id;
if( $result == '0' )
{
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
My modal:
public function checknpp($id)
{
$this->db->select('id');
$this->db->where('id', $id);
$this->db->from('id', 1);
$query = $this->db->get();
if( $query->num_rows() > 0 ){ return 0; }
else{ return 1; }
}
My js:
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('user/ajax_add')?>";
} else {
url = "<?php echo site_url('user/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
my view:
<input name="id" id="masukpun" placeholder="NPP" class="form-control" type="text" />
However, when I run it, it always says that error updating/adding data.
Just try this,
public function ajax_add() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp($id); #send the post variable to the model
//value got from the get metho
$id = $id;
if ($result == '0') {
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
} else {
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
$data = array("status" => TRUE);
}
echo json_encode($data);
}
For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.
This is the JavaScript code which checks for the validation of the mobile number data (with other data) and forwards it to validate_user.php which stores the mobile number.
But I want to store the data of only those users whose mobile number exists in another table or else I want to display an error message saying 'User not present in the database'.
I need help. What do I do?
Thanks in advance.
JavaScript
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
This is the server side PHP code:
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
}
else
{
return true;
}
?>
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function(json){
if(json.error){
alert(json.error)// or do whatever you want
}
else{
alert(json.success) // there your made a success call the do your staff
}
}
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
**The Server Side php**
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$json = array();
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
$json['error'] = "Unable to Connect server!".mysql_error();
}
if(empty($json)){
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
$json['success'] = "Successfully inserted";
}
else
{
$json['error'] = 'A Fake Number';
}
}
echo json_encode($json);
You can verify this using success response
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success:(function(result){
if(empty(result)){
return false;
}else{
return true;
}
}));
});