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();
});
Related
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)
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.
After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
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);
},
...
I am working on a form to database save/grab using ajax/jquery. I am having issues saving and grabbing though. My ajax keeps failing and I can't tell why. I know this should work. I movedmy ajaxCall to its own function to call it on load and on submit and that is when things seemed to go south. Can someone point me in the right direction on what is wrong. I have my jquery and php below.
JQUERY/AJAX CODE
$(document).ready(function() {
ajaxCall();
$('#submitBtn').on('click',function(event) {
var formData = $('form').serialize();
event.preventDefault();
ajaxCall(formData);
}); //END OF .ON
function ajaxCall(formData) {
$.ajax({
url: "php/save.php",
type: "POST",
dataType: "json",
//dataType: "string",
data: formData,
async: true,
success: successCall,
error: errorCall
});
} //END OF AJAX CALL FUNCTION
function errorCall() {
alert("There was an error with this request!")
}// END OF ERROR CALL FUNCTION
function successCall(data) {
//var records = $.parseJSON();
var record = "";
console.log(data);
/*$.each(data, function() {
ID = this['ID'];
NAME = this['NAME'];
PHONE = this['PHONE'];
ADDRESS = this['ADDRESS'];
var html = "<tr><td>" + ID + "</td><td>" + NAME + "</td><td>" + PHONE + "</td><td>" + ADDRESS + "</td></tr>";
$(html).appendTo("table");
});*/
//var jsonObject = $.parseJSON(data);
//alert("ajax call complete");
} //END OF SUCCESS CALL FUNCTION
}); //END OF .READY
PHP CODE
class dbClass {
private $host = "localhost";
private $username = "root";
private $password = "";
private $schema = "formtest";
public $dbCon;
function __construct() {
$this->dbCon = new mysqli($this->host,$this->username,$this->password,$this->schema);
if ($this->dbCon->connect_error) {
die("Issue Connecting: " . $dbCon->connect_errorno . "Error: " . $dbCon->connect_error);
}
//var_dump($dbCon);
}
function saveDBRecord($dbName, $dbPhone, $dbAddress) {
//HOW TO FIGURE THIS OUT
$query = $this->dbCon->prepare("INSERT INTO contact (contact_name,contact_phone,contact_address) VALUES (?,?,?)");
$query->bind_param("sss",$dbName,$dbPhone,$dbAddress);
//var_dump($query);
$query->Execute();
$recordData = $this->grabRecords();
return $recordData;
}
function grabRecords() {
$query = $this->dbCon->query("SELECT * FROM contact;");
//var_dump($query);
$data = array();
$counter = 0;
$i = 0;
while($row = $query->fetch_row())
{
$record = array(
"ID" => $row[0],
"NAME" => $row[1],
"PHONE" => $row[2],
"ADDRESS" => $row[3]
);
$data[] = $record;
//$data[$i++] = "ID: {$row[0]} NAME: {$row[1]} PHONE: {$row[2]} ADDRESS: $row[3]";
//$data .= "ID: {$row[0]} NAME: {$row[1]} PHONE: {$row[2]} ADDRESS: $row[3]";
//$counter .= $counter;//var_dump($data);
//$assoc = $query->fetch_all();
//var_dump($assoc);
//return $assoc;
}
//var_dump($data);
return $data;
}
function __destruct() {
$this->dbCon->close();
}
} //END OF dbClass
$dbClassConnection = new dbClass();
/*function displayRecords($recordData) {
//var_dump($recordData[0]);
}*/
//$name = $_POST['name'];
//$phone = $_POST['phone'];
//$address = $_POST['address'];
//$name = "AutoInput";
//$phone = "AutoInput";
//$address = "AutoInput";
//var_dump($dbClassConnection);
if ($_POST['name'] == "" || $_POST['phone'] == "" || $_POST['address'] == "") {
$recordData = $dbClassConnection->grabRecords()
echo json_encode($recordData);
//echo json_encode("HELLO");
//$recordData = $dbClassConnection->grabRecords();
//echo json_encode("FIRST IF");
//var_dump($recordData);
} else {
$name = $_POST['name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$recordData = $dbClassConnection->saveDBRecord($name,$phone,$address);
//$jsonData = displayRecords($recordData);
//var_dump(json_encode($recordData);
echo json_encode($recordData);
//var_dump($jsonData);
//echo json_encode("SECOND IF");
//var_dump($recordData);
}
//$name = $_POST['name'];
//ar_dump($name;
//echo json_encode($_POST);
//IF SUBMIT TRUE
//saveDBRecord and grabRecords
//ELSE
//JUST GrabRecords
?>
The issue was that the ajaxCall onLoad needed to serialize the formData as well and then the issue was with how I was handling the POST data for the IF statements.