controller
).controller('LoginController',
[
'$scope',
'dataService',
'$location',
'$window',
function ($scope, dataService, $location,$window){
$scope.check_login=function($event,userID,passwd)
{
dataService.login(userID,passwd).then
(
function (response){
$scope.loginCount = response.rowCount + 'account Record';
$scope.loginConfirm = response.data;
console.log(response.data);
},
function (err) {
$scope.status = 'unable to connect to data' + err;
});
// $scope.reloadRoute = function () {
// $location.path('/#');
// $window.location.reload()
// }//end of reload route fnction
}//end of function check_login
}
]
Services.js
this.login = function (userID, passwd) {
var defer = $q.defer(),
data = {
username: userID,
password: passwd
};
$http.post(urlBase, {
params: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
cache: true
})
. // notice the dot to start the chain to success()
success(function (response) {
defer.resolve({
data: response.login.Result, // create data property with value from response
rowCount: response.login.RowCount // create rowCount property with value from response
});
})
. // another dot to chain to error()
error(function (err) {
defer.reject(err);
});
// the call to getCourses returns this promise which is fulfilled
// by the .get method .success or .failure
return defer.promise;
};
index.php
if (isset($_POST['username']) && isset($_POST['password'])) {
$useremail = $_POST['username'];
$password = $_POST['password'];
$service = new FilmsService();
$result = $service->login($useremail, $password);
echo $result;
} else {
echo "Cant Find The Data";
}
Currently i got 3 file name controller,service.js and index.php , service.js is u to pass the data to the php side, but when i try to get the username and password in the php side, it will be error.Cant get the username and password.
How to solve it? is it my code error?
Try this in place of your $http.post:
$http({
method: 'POST',
url: urlBase,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
});
Related
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have the following php code, which works on its own. However, when using it AJAX it returns an empty response.
PHP login code:
<?php
session_start();
include_once 'resources/database.php';
if(isset($_POST['m_login_signin_submit'])) {
$email = trim($_POST['email']);
$user_password = trim($_POST['password']);
$password = MD5($user_password);
try {
$stmt = $db->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['password']==$password) {
echo '1';
$_SESSION['user_session'] = $row['id'];
} else {
echo 'You do not matter.';
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
AJAX Code:
$(document).ready(function () {
/* validation */
$("#login-form").validate({
submitHandler: submitForm
});
function submitForm() {
var email = $('#email').val();
var password = $('#password').val();
console.log(data);
$.ajax({
type: 'POST',
dataType: 'text',
url: 'partials/processLogin.php',
data: {
email:email,
password:password
},
success: function (response) {
console.log("Checking success.");
console.log(response);
},
error: function () {
console.log("error");
}
});
return false;
}
});
In console, all the values pass correctly and it returns success but the value is empty. Any help is greatly appreciated.
Thank you
You did not pass any m_login_signin_submit in your request, therefore you never go into your main if statement. I'm guessing that is the form's submit button but since this is ajax it will not get sent unless you do it explicitly.
data: {
email:email,
password:password,
m_login_signin_submit: 1
},
I'm to trying make a login using AJAX. AJAX function post data to PHP file but when I try to retrieve data from POST in PHP it's empty.
This is my AJAX posting code:
function validateUser() {
var userR = $("#fldUser").val();
var passwordR = $("#fldPassword").val();
if (userR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"> <b>A user is required.</b></p>");
} else if (passwordR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"><b>A password is required.</b></p>");
} else {
// alert(userR + passwordR)
$.ajax({
type: 'POST',
// url: '/_Controlador/_GSystemLogIn.php/',
url: '/_Controlador/_GSystemLogIn.php',
// data:'user=' + userR +'&password=' + passwordR,
data: {
'user': userR,
'password': passwordR
},
dataType: 'JSON',
beforeSend: function(xhr) {
alert("En before send: " + userR + passwordR);
},
success: function(data) {
alert(data);
if (data.message === "Success") {
// location.href = "main.php";
} else {
$("#divStatusText").html("<p class=\"text-danger\"><b>User or password is incorrect.</b></p>");
$("#fldUser").val("");
$("#fldPassword").val("");
}
},
error: function(data) {
alert("Error in AJAX call.");
}
});
}
}
PHP code retrieving data:
var_dump($_POST);
$user = $_POST['user'];
$password = $_POST['password'];
echo( "PHP user received: ". $user);
echo( "PHP pass received: ".$password);
Alert in AJAX beforeSend prints data correctly but var_dump($_POST) prints:
array(0) { }
I've also tried different ways to send data and URL. I'll really appreciate your help. Thank you!
You have to decode the data first.
Just do -
$_POST = json_decode(file_get_contents('php://input'), true);
Here's the full explanation - https://stackoverflow.com/a/39508364/5400741
In your ajax request,
type: 'POST' has to be method: 'POST'
Look at here
I am working on a project with CI and Ajax. Since, I'm working with ajax after a long time, I am having some issues in debugging. I have written this code. In which i am sending data to to controller function login. Please guide me regarding how to check whether the data is reaching controller, and model. And also on how to return data from model to controller and from controller to view.
My Ajax code is as follows:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert('Ajax Success');
}, error: function () {
alert('Ajax Error');
}
});
}
});
Controller home.php Code is as follows:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
return $data;
}
and Model Dis_model.php code is as follows:
function check_user($uname, $pwd) {
$this->db->select('*');
$this->db->where('uname', $uname);
$this->db->where('pwd', $pwd);
$query = $this->db->get('users');
return $query->result();
}
All positive suggestions are welcomed.
Thanks in advance.
Change In Controller:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo $uname;
exit;
}
Change in ajax:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
Same in modal
Change in Controller
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo json_encode($data['userinfo']);
die;
}
Change in ajax
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
I'm trying to use slim framework and when I do a POST to enter a record does absolutely nothing. I'm afraid I pass the parameter identified as null because if I allow it in the database, enter a null record.
this is mi Slim PHP.
$app-> post("/banda/", function() use($app){
$nombre=$app->request->post("nombre");
try{
$connection = getConnection();
$dbh = $connection->prepare("INSERT INTO banda VALUES(null, ?)");
$dbh->bindParam(1, $nombre);
$dbh->execute();
$banda = $connection->lastInsertId();
$connection= null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($banda));
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
});
And this is my JS
var API_URI = "http://localhost/banda/";
function limpiar() {
$("#form-band input:first-child").val("");
}
function nombreBandaEsVacia() {
return ($("#form-band input:first-child").val().length == 0);
}
function getBandaJSON() {
return JSON.stringify({
nombre: getBandaNombre()
});
}
function getBandaNombre() {
return $("#form-band input:first-child").val();
}
$("#form-band input:last-child").on("click", function createBanda() {
if (nombreBandaEsVacia()){
alert("Oops! Completa el formulario!");
}else{
// 1.2 JSON.Stringify
var banda = getBandaJSON();
};
$.ajax({
type:'POST',
crossDomain: true,
url:API_URI,
data:banda,
dataType:"json",
beforeSend: function() {
console.log(banda);
},
success:function(response, banda) {
limpiar();
},
error:function(jqXHR, data, textStatus, errorThrown) {
console.log(data);
console.log(errorThrown);
console.log(jqXHR);
console.log(textStatus);
}
});
});
My navigator say this:
http://s2.subirimagenes.com/imagen/previo/thump_91447311.png
By the look of it, you are sending a string to your php script instead of key-value pairs.
You can either use something like:
data: {'my_banda_json': banda},
and parse it at the server-side before you try to insert it.
Or you can just send what you need in a way that the back-end is now expecting it:
data: {'nombre': value_of_the_banda_name_field},