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.
Related
I am stumbling into the following issue.. I am trying to retrieve some information from my DB using Ajax, however, my query is failing for some reason, when trying to debug it by analyzing the information within the mysqli_object, all the properties are null:
I printed the contents of the object of the console:
affected_rows:null
client_info:null
client_version:null
connect_errno:null
connect_error:null
errno:null
error:null
error_list:null
field_count:null
host_info:null
info:null
insert_id:null
protocol_version:null
server_info:null
server_version:null
sqlstate:null
stat:null
thread_id:null
warning_count:null
Why can this happen?
Here's my Ajax call:
$('#npClientName').keyup(function(){
var txt = $(this).val();
if (txt == "") {
$('#npClientList').fadeOut();
return false;
}
$.ajax({
method: 'POST',
url: '/fitcoControl/Resources/PHP/Clientes/fetchPopupClientList.php',
data:{txt: txt},
success: function(result){
rsp = JSON.parse(result);
console.log(rsp);
if (rsp.code != "1") {
$('#npClientList').html("<p>Hubo un error al cargar la lista de clientes...</p>");
console.warn("Error en el query: " + rsp.response);
} else {
$('#npClientList').html(rsp.response);
}
$('#npClientList').fadeIn();
clientSelector();
},
error: function(exception){
console.error(exception);
}
});
});
And here's my PHP code:
$root = $_SERVER['DOCUMENT_ROOT'];
$data = array(
'code'=>"",
'response'=>""
);
$txt = "'%" . $_POST['txt'] . "%'";
require $root . "/fitcoControl/Resources/PHP/DataBases/Conexion.php";
$query = "SELECT * FROM ct_cliente";
$stmt = $conn->prepare($query);
//$stmt->bind_param('s', $txt);
$stmt->execute();
$resultados = $stmt->get_result();
$num_rows = $stmt->num_rows;
if (false) {
$data['code'] = 2;
//$data['response'] = $num_rows;
} else {
$data['code'] = 1;
$data['system'] = $conn;
while ($a = mysqli_fetch_assoc($resultados)) {
$idCliente = $a['pk_cliente'];
$nc = $a['nombreCliente'];
$data['response'] .= "<p client-id='$idCliente'>$nc</p>";
}
}
$json = json_encode($data);
echo $json;
Ideas?
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 have created a code that allows you to search videos from the database. But everytime I write the video I want to search, in console, error appears... I really dont know why it doesnt print the result...
Could you help me?
I need help real fast
AJAX
$(document).ready(function($) {
var Search = function(title){ return $.post( "./include/php/busqueda_videos.php", { "title" : title }); }
$("#input_search").on('keyup', function(event) {
var output = "";
$(".videos_container").html("");
event.preventDefault();
var input = $("#input_search").val();
Search(input).done(function(response) {
if(response.success) {
$.each(response.videos, function(key, value) { var output = "<div class='video_main_container'><div class='video_container'><div class='video_thumb'><a data-id='"+value['id']+"'><img src='"+value['image']+"' alt='' /></a></div><div class='video_info'><p class='title'>"+value['title']+"</p><p class='usuario'>"+value['user']+"</p></div></div></div>"; });
$(".videos_container").html(output);
} else {
console.log("Error");
}
}).fail(function(jqXHR, textStatus, errorThrown) { console.log("Hubo un error"); });
});
});
PHP
<?php
if(isset($_POST['title'])) {
get_infvideo($_POST['title']);
} else {
$message = sprintf("No valid");
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $message, true, 403);
}
function get_infvideo($title) {
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseña = "";
$conexion = new PDO($dsn, $usuario, $contraseña);
$resultado = null;
$jsondata = array();
$videos = array();
$text ="";
if($title!="") {
$title= explode(" ", $title);
for($i=0; $i<count($title);$i++) {
if($text!="") {
$text .= " AND (title LIKE '%".$title[$i]."%' or user LIKE '%".$title[$i]."%')";
} else {
$text .= " (titulo LIKE '%".$titulo[$i]."%' or user LIKE '%".$title[$i]."%')";
}
}
}
if($conexion){
$sql = "SELECT * FROM video WHERE ".$text;
if($resultado = $conexion->query($sql)) {
while($fila = $resultado->fetch()) {
$fila['id'] = $fila['id'];
$fila['user'] = $fila['user'];
$fila['image'] = $fila['image'];
$jsondata['success'] = true;
array_push($videos, $fila);
$jsondata['videos'] = $videos;
}
} else {
$jsondata['success'] = false;
$jsondata['message'] = $sql;
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
}
exit();
?>
The idea is to print the video (with his id, image, user, title) that you have searched...
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.