JSON.parse() seems not to work with my code, I'm not sure what's causing it.
JS Code:
var obj = JSON.parse(this.responseText);
console.log(obj.status + " " + obj.type);
if (obj.status == "success") {
document.cookie = "accounttype=" + obj.type;
document.cookie = "name=" + obj.name;
var accounttype = getCookie(accounttype);
if (accounttype == "Seller") {
window.location.href = "../html/sell.html";
}
}
PHP Code:
$count = mysqli_num_rows($result);
if($count == 1){
echo '{"status": "success", "type":"$account", "name":"$name"}';
}else{
echo '{"status": "failed"}';
}
Hope you guys can help me, thanks!
EDIT UPDATED CODE
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var str = JSON.stringify(this.responseText);
var obj = JSON.parse(str);
console.log(obj.status + " " + obj.type);
if (obj.status == "success") {
document.cookie = "accounttype=" + obj.type;
document.cookie = "name=" + obj.name;
var accounttype = getCookie(accounttype);
if (accounttype == "Seller") {
window.location.href = "../html/sell.html";
}
} else {
sweetAlert("Oops...", "Invalid username or password!", "error");
document.getElementById("password").value = "";
}
}
}
xmlhttp.open("POST", "../php/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
And here's the updated PHP code:
<?php
include("checkdbconnection.php");
session_start();
$username = mysqli_escape_string($conn, $_POST['username']);
$password = mysqli_escape_string($conn, $_POST['password']);
$password = md5($password);
$getLogin = "SELECT * FROM user WHERE username = '$username' and password = '$password'";
$result = mysqli_query($conn, $getLogin);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$name = $row["firstname"];
$account = $row["account_type"];
if(!$result){
echo "Query Error: ". mysqli_error($conn);
die();
}
$jsonsuccess = ["status": "success", "type": $account, "name": $name];
$jsonfail = ["status": "failed"];
$jsonsuccstring = json_encode($jsonsuccess);
$jsonfailstring = json_encode($jsonfail)
$count = mysqli_num_rows($result);
if($count == 1){
echo $jsonsuccstring;
}else{
echo $jsonfailstring;
}
?>
Console returns undefined for both JSON returned values.
Use json_encode()
Your server side response should be
$json = ["status": "success", "type": $account, "name": $name];
$jsonstring = json_encode($json);
echo $jsonstring;
die();
Your JS code should be like
$.ajax({
type: "GET",
url: "URL.php",
data: data,
success: function(data){
// Here is the tip
var data = $.parseJSON(data);
//Here is success
alert(data.status);
}
});
EDIT
You should verify your json string. If it is ok try this:
var jsonStr="your json string";
var json=JSON.stringify(jsonStr);
json=JSON.parse(json)
Related
i want to validate login form using ajax success response is working but if all goods it should be redirect to index page but it's not working , i don't understand what's wrong please help. thanks in advance..
$(document).ready(function(){
var response;
$('#submit').click(function(e){
e.preventDefault();
$('.alert-box').html('<div id="loading" style="margin: 0 auto;" >
</div>');
var action = 'ajax_validation';
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url:"do_login.php",
method:"POST",
data:{action:action, username:username, password:password},
success:function(data){
response = data;
if(response === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
});
});
});
above these ajax request
this is action page code
include('includes/db.php');
if(isset($_POST["action"])){
$check_username = $_POST['username'];
$check_password = $_POST['password'];
if(empty($check_username) && empty($check_password)){
echo "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
die("QUERY FAILED".mysqli_error($select_query));
}
if(mysqli_num_rows($select_query)==0){
echo "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
echo $row['email'];
}
}
}
}
In your resposne you are echoing
echo $row['email'];
This should be:
echo 1;
Your problem is that you are checking if value is 1 in ajax:
success:function(data){
response = data;
if(response === 1){ //<- there you are checking if your echo is 1 but you are trying to echo $row['email'];
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
change your echo from $row['email'] to 1
I think that the problem is response checking condition in ajax success.
You're checking if a string (email or error message) is equal and the same type of 1.
...
dataType: 'json',
success:function(data){
response = data;
if(response === 1){
...
You can use a json response with status/error code:
...
success:function(data){
response = JSON.parse(data);
if(response.status === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response.data);
}
}
...
$check_username = $_POST['username'];
$check_password = $_POST['password'];
$res = array('status'=> 0, 'data' => '');
if(empty($check_username) && empty($check_password)){
$res['status'] = 0;
$res['data'] = "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
$res['status'] = 0;
$res['data'] = "QUERY FAILED".mysqli_error($select_query);
echo json_encode($res);
return;
}
if(mysqli_num_rows($select_query)==0){
$res['status'] = 0;
$res['data'] = "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
$res['status'] = 1;
$res['data'] = "".$row['email'];
}
}
}
echo json_encode($res);
In addition i suggest to put only the username in query where condition and check if the password match with php.
I have a form. When I submit and try to insert a duplicate record in the database, the page reloads and the error message is logged in the console. However, after* the page reloads, a question mark is already appended to the end of the URL. Why is that so?
Like from this:
http://localhost/project/home
to this (after database error occurred due to duplicate record):
http://localhost/project/home?
Controller:
public function loadBoardManagement()
{
$role = $this->session->userdata('role');
$user_id = $this->session->userdata('user_id');
$board_id = $this->uri->segment(3);
$role = 'Admin';
$user_id = 1;
if ($this->uri->segment(3) == null)
{
$board_id = 178;
}
if ($this->session->userdata('first_board_id') !== null && $board_id == 0)
{
$board_id = $this->session->userdata('first_board_id');
}
$data['boards'] = $this->Board_model->getBoards($role, $user_id);
$data['board_assignees'] = $this->Team_model->getBoardAssignees($board_id);
$data['all_teams'] = $this->Team_model->getAllTeams();
$data['team_quantity'] = $this->Team_model->getBoardTeamsQuantity($board_id);
$data['board_name'] = $this->Board_model->getBoardName($board_id);
$data['board_id'] = $board_id;
$this->load->view('board_management', $data);
}
public function fast_signup()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$role = $this->input->post('role');
$fast_signup = $this->User_model->fastSignup($username, $password, $first_name, $last_name, $email, $role);
if ($fast_signup)
{
echo 'success';
}
else
{
echo $fast_signup;
}
}
javascript:
function addMember()
{
var username = $('#username').val();
var password = $('#password').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var role = $('#role option:selected').val();
console.log('Role: ' + role);
console.log(username + password + first_name + last_name + email);
$.ajax({
type: 'POST',
url: base_url + 'user/fast_signup', //controller for inserting new members, but the current page is localhost/project/board/loadBoardManagement
data: {
'username': username,
'password': password,
'first_name':first_name,
'last_name': last_name,
'email': email,
'role' : role
},
success: function(msg)
{
if (msg == 'success')
{
console.log('Member created');
window.location.href = window.location.href;
}
else
{
console.log('Failed to create member!' + msg);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('Response: ' + jqXHR.responseText);
console.log('Status code: ' + textStatus);
console.log('Error thrown: ' + errorThrown);
}
});
}
$('#create_user_member').click(function() {
addMember();
});
I am trying to input data from a input form to database, but it always gives a fail alert even the data is success to input. so this is the part of my code
jquery
$("#daftar").click(function(){
nim = $("#kdAlumni").val();
tahun = $("#kdTahun").val();
nama = $("#Nama").val();
nohp = $("#Nohp").val();
foto = $("#Foto").val();
email = $("#Email").val();
jurusan = $("#kdJurusan").val();
judul = $("#judul").val();
fakultas = $("#kdFakultas").val();
tgl = $("#Lahir").val();
$.ajax({
type: "POST",
url: "insertupdate.php",
data: "nim=" + nim + "&nama=" + nama + "&nohp=" + nohp + "&email=" + email + "&jurusan=" + jurusan + "&foto=" + foto + "&judul=" + judul + "&fakultas=" + fakultas + "&tahun=" + tahun + "&tgl=" + tgl,
success: function(dat)
{
if(dat == 'true')
{
alert("input success");
$("#kdAlumni").val("");
$("#kdTahun").val("");
$("#Nama").val("");
$("#Nohp").val("");
$("#Foto").val("");
$("#Email").val("");
$("#kdJurusan").val("");
$("#judul").val("");
$("#kdFakultas").val("");
$("#Lahir").val("");
}
else if(dat == 'false')
{
alert("input fail");
$("#kdAlumni").val("");
$("#kdTahun").val("");
$("#Nama").val("");
$("#Nohp").val("");
$("#Foto").val("");
$("#Email").val("");
$("#kdJurusan").val("");
$("#judul").val("");
$("#kdFakultas").val("");
$("#Lahir").val("");
}
}
});
return false;
});
php
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$name = "buku_tahunan";
$koneksi = mysqli_connect($host,$user,$pass,$name);
if(mysqli_connect_errno())
{
die("koneksi DB Gagal".mysqli_connect_error());
}
$nim = $_POST["nim"];
$nama = $_POST["nama"];
$nohp = $_POST["nohp"];
$email = $_POST["email"];
$jurusan = $_POST["jurusan"];
$fotoN = $_FILES['foto']['name'];
$fotoT = $_FILES['foto']['tmp_name'];
$tujuan = "foto/" .$fotoN;
$judul = $_POST['judul'];
$fakultas = $_POST["fakultas"];
$tahun = $_POST["tahun"];
$tgl = $_POST["tgl"];
$sql="INSERT INTO `data_alumni`(`kdAlumni`, `nama`, `noHP`, `email`, `foto`, `judulSkripsi`, `kdFakultas`, `kdTahun`, `kdJurusan`, `tgl_lahir`) VALUES ('$nim','$nama','$nohp','$email','$tujuan','$judul','$fakultas','$tahun','$jurusan','$tgl')";
$insert = mysqli_query($koneksi,$sql);
move_uploaded_file($sumber, $tujuan);
if($insert)
{
echo 'true';
}
else
{
echo 'false';
}
?>
that's all of my code to input data to database, so what's the real problem from my code? thank you
It's not uncommon to have extra whitespace in the response. Try trimming any whitespace:
success: function(dat){
dat = dat.trim();
if(dat == 'true'){.....
Also check what dat is in the response to be sure it is what is expected and to narrow down where the actual issue lies.
Generally easier to use json for all responses
finally I realize the reason of this error, when I try to debug the script I see the problem that caused by $_FILES. The way that I input value from in javascript is the real problems
I'm using a framework called Ispinia to do a simple system for my Company, and when I try to submit anyting give this error:
Web page message [object object].
I'm using IE11.
Thanks in advance!
CODE: Controller.js
function vila_do_conde_ctrl($scope, $http, SweetAlert){
$scope.dataInicio = new Date();
$scope.dataFim = new Date();
$scope.teste = function(){
alert($scope.myDate);
}
$scope.preencheEmbarques = function(){
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_embarques.php?oi="+$scope.oi)
.then(function (response) {$scope.embarques=response.data.records;$scope.emb = ""; $scope.dataChegada = ""; $scope.dataSaida = ""; $scope.dataDesova = ""; $scope.tipoCarga = ""; if($scope.ctn) $scope.ctn = ""; $scope.fornecedor = ""; $scope.servicoAdd = ""; $scope.qte = ""; $scope.unidade = ""; $scope.dataInicio = ""; $scope.dataFim = ""; $scope.obs = ""; $scope.servicos = ""; }, function (response){alert(response);});
};
$scope.buscaServicos = function(){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_servicos.php?emb="+embarque)
.then(function (response) {
$scope.servicos=response.data.records;
for(var i=0; i<$scope.servicos.length; i++){
var dataAux = $scope.servicos[i].DataInicio.split("-");
$scope.servicos[i].DataInicio = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
dataAux = $scope.servicos[i].DataFim.split("-");
$scope.servicos[i].DataFim = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
}
}, function (response){alert(response);});
};
$scope.preencheDados = function(){
if($scope.emb){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_dados.php?emb="+embarque)
.then(function (response) {
$scope.dados=response.data.records[0];
if($scope.dados.DtChegada){
$scope.dataAux=$scope.dados.DtChegada.split("-");
$scope.dataChegada=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtSaida){
$scope.dataAux=$scope.dados.DtSaida.split("-");
$scope.dataSaida=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtDesova){
$scope.dataAux=$scope.dados.DtDesova.split("-");
$scope.dataDesova=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
$scope.tipoCarga=$scope.dados.TipoCarga;
$scope.ctn=$scope.dados.Container;
$scope.buscaServicos();
}, function(response){alert(response);});
}
};
$scope.adicionarServico = function(){
if($scope.oi && $scope.emb && $scope.fornecedor && $scope.servicoAdd && $scope.qte && $scope.unidade && $scope.dataInicio && $scope.dataFim){
var embarque = encodeURIComponent($scope.emb.trim());
var fornecedor = encodeURIComponent($scope.fornecedor.trim());
var servico = encodeURIComponent($scope.servicoAdd.trim());
var quantidade = encodeURIComponent($scope.qte);
var unidade = encodeURIComponent($scope.unidade.trim());
var data_inicio = encodeURIComponent($scope.dataInicio.getFullYear()+"-"+ ($scope.dataInicio.getMonth() + 1) +"-"+$scope.dataInicio.getDate());
var data_fim = encodeURIComponent($scope.dataFim.getFullYear()+"-"+ ($scope.dataFim.getMonth() + 1) +"-"+$scope.dataFim.getDate());
var obs = "";
if($scope.obs)
obs = encodeURIComponent($scope.obs);
var container = ""
if($scope.tipoCarga){
if($scope.ctn)
container = encodeURIComponent($scope.ctn);
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_tipo_carga.php?oi="+$scope.oi+"&emb="+embarque+"&ctn="+container)
.then(function (response) {}, function (response){alert(response);});
}
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_servico.php?oi="+$scope.oi+"&emb="+embarque+"&forn="+fornecedor+"&servico="+servico+"&qte="+quantidade+"&unidade="+unidade+"&dtInicio="+data_inicio+"&dtFim="+data_fim+"&obs="+obs)
.then(function (response) {
SweetAlert.swal({
title: "Serviço adicionado!",
//text: "You clicked the button!",
type: "success"
});
$scope.buscaServicos();}, function (response){alert(response);});
}
else
alert("Preencha todos os campos!");
};
MODEL:
<?php
$oi = $_GET['oi'];
$emb = $_GET['emb'];
$fornecedor = $_GET['forn'];
$servico = $_GET['servico'];
$quantidade = $_GET['qte'];
$unidade = $_GET['unidade'];
$data_inicio = $_GET['dtInicio'];
$data_fim = $_GET['dtFim'];
$obs = $_GET['obs'];
// Create connection
$conn = new mysqli($host, $usuario, $senha, $base_de_Dados);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($obs != "")
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM, OBSERVACOES) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."','".$obs."')";
else
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
[object Object] is the way JavaScript outputs an object. Not sure what the purpose of your script is, but you can show the sub-object by using objectname.key.
e.g. if 'person' is an object containing name and mail address, you can access the sub-objects (probably strings in this example) by calling person.name and person.mailaddress.
I think you should now go through your code again and have a look at all alert messages.
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...