I have this code. The problem is: It is not obeying 'ORDER BY NAME ASC' on query and I don't know why. It is happening in all 3 functions.
Here is the code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once("dbconfig.php");
class location extends dbconfig {
public static $data;
function __construct() {
if (in_array('__construct', get_class_methods(get_parent_class($this)))) {
parent::__construct();
}
}
public static function getCountries() {
try {
$query = "SELECT id, name FROM countries ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Country not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"Countries fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
public static function getStates($countryId) {
try {
$query = "SELECT id, name FROM states WHERE country_id=".$countryId." ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("State not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
public static function getCities($stateId) {
try {
$query = "SELECT id, name FROM cities WHERE state_id=".$stateId." ORDER BY name ASC";
$result = dbconfig::run($query);
if(!$result) {
throw new exception("City not found.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[$resultSet['id']] = $resultSet['name'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"Cities fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
}
Javascript
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
};
var errorRes = function(e) {
console.log(e);
alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
};
$.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
var rootUrl = "../PDOClasses/CountriesList/api.php";
var call = new ajaxCall();
this.getCities = function(id) {
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getCities&stateId=' + id;
var method = "post";
var data = {};
$('.cities').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.cities').find("option:eq(0)").html("Selecione a cidade");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.cities').append(option);
});
$(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getStates = function(id) {
$(".states option:gt(0)").remove();
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getStates&countryId=' + id;
var method = "post";
var data = {};
$('.states').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.states').find("option:eq(0)").html("Selecione o estado");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.states').append(option);
});
$(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
var url = rootUrl+'?type=getCountries';
var method = "post";
var data = {};
$('.countries').find("option:eq(0)").html("Carregando..");
call.send(data, url, method, function(data) {
$('.countries').find("option:eq(0)").html("Selecione o país");
console.log(data);
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.countries').append(option);
});
$(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
$(function() {
var loc = new locationInfo();
loc.getCountries();
$(".countries").on("change", function(ev) {
var countryId = $(this).val();
if(countryId != ''){
loc.getStates(countryId);
}
else{
$(".states option:gt(0)").remove();
}
});
$(".states").on("change", function(ev) {
var stateId = $(this).val();
if(stateId != ''){
loc.getCities(stateId);
}
else{
$(".cities option:gt(0)").remove();
}
});
});
and api
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start();
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
include_once("location.php");
$loc = new location();
try {
if(!isset($_GET['type']) || empty($_GET['type'])) {
throw new exception("Type is not set.");
}
$type = $_GET['type'];
if($type=='getCountries') {
$data = $loc->getCountries();
}
if($type=='getStates') {
if(!isset($_GET['countryId']) || empty($_GET['countryId'])) {
throw new exception("Country Id is not set.");
}
$countryId = $_GET['countryId'];
$data = $loc->getStates($countryId);
}
if($type=='getCities') {
if(!isset($_GET['stateId']) || empty($_GET['stateId'])) {
throw new exception("State Id is not set.");
}
$stateId = $_GET['stateId'];
$data = $loc->getCities($stateId);
}
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
echo json_encode($data);
}
ob_flush();
Can someone help me please? I'm about 3 hours trying asort and other functions but no success.
javascript > api > php
Related
It doesn't validate my fields correctly, always goes at last validation. What could be happening, I'm new to the topic, Thanks a lot.
This is the script code
<script type="text/javascript" charset="utf8">
(() => {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
// form.querySelector(".form-control:invalid").focus();
event.preventDefault()
event.stopPropagation()
} else {
event.preventDefault();
$.ajax({
method: "POST",
data: $(form).serialize(),
url: "procesos/usuario/registro/crear-usuario.php",
success: function(respuesta) {
respuesta = respuesta.trim();
if(respuesta == 1){
$(form)[0].reset();
Swal.fire(
'¡Felicidades!',
'Se creo con éxito',
'success'
);
}else if(respuesta == 2){
Swal.fire({
icon: 'error',
title: '¡Algo salió mal!',
text: 'Este usuario ya existe',
footer: 'Inténtalo nuevamente'
});
}else{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: '¡Algo salió mal!',
footer: 'Inténtalo nuevamente'
});
}
},
});
return false;
}
form.classList.add('was-validated')
}, false)
})
})()
function myFunction() {
var x = document.getElementById("password");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
This is php code, Something I forgot to say is that I am working with php 7.4.
<?php
require_once ("conexion.php");
class Usuario extends Conectar{
public function crearUsuario($datos){
$conexion = Conectar::conexion();
if(self::buscarUsuarioRepetido($datos['nomusuario'])){
return 2;
}else{
$sql ="INSERT INTO `db-mphz-transparencia`.`usuario` (`u_nombres`, `u_apellidos`, `u_nomusuario`, `u_password`) VALUES (?, ?, ?, ?)";
$query = $conexion->prepare($sql);
$query->bind_param('ssss', $datos['nombres'],
$datos['apellidos'],
$datos['nomusuario'],
$datos['password']);
$ejecutar = $query->execute();
$query->close();
return $ejecutar;
}
}
public function buscarUsuarioRepetido($nomusuario){
$conexion = Conectar::conexion();
$sql = "SELECT `u_nomusuario` FROM `db-mphz-transparencia`.usuario WHERE `u_nomusuario` = '$nomusuario'";
$result = mysqli_query($conexion, $sql);
$datos = mysqli_fetch_array($result);
if(($datos['nomusuario'] != "") || ($datos['nomusuario'] == $nomusuario)){
return 1;
}else{
return 0;
}
}
}
?>
(https://i.stack.imgur.com/kmDrw.png)(https://i.stack.imgur.com/xuw2C.png)
I new to PHP and this might not even be a problem. I have a JavaScript function that sends fetch request. When I send to the api.php, I get a null when I var_dump() the variable $studentnumber. I checked the fetch request and it's sending data in the request, so there is something wrong with PHP reading the form data... maybe?. Thanks in advance this was for a school assignment.
Fetch Request
function login() {
var studentnumber = document.getElementById("studentnumber");
var password = document.getElementById("password");
var logindetails = new FormData();
logindetails.append('studentnumber', studentnumber.value);
logindetails.append('password', password.value);
fetch('http://localhost/gaq/api/api.php?action=login', {
method: 'POST',
body: logindetails,
}
)
.then(function(response){
if (response.status == 202) {
var studentnumber = document.getElementById("studentnumber");
var logindetails = new FormData();
logindetails.append('studentnumber', studentnumber.value);
fetch('http://localhost/gaq/api/api.php?action=processlogin', {
method: 'POST',
body: logindetails,
});
console.log("Success");
} else {
console.log("Error");
}
})
}
API.PHP File
<?php
include 'database.php';
include 'session.php';
session_start();
//header('Content-Type: application/json');
$functions = new gaqfunctions();
if(!isset($_SESSION['user_session'])) {
$_SESSION['user_session'] = new gaqsession;
http_response_code(501);
die();
}
if(isset($_GET['action'])) {
switch($_GET['action']) {
case "login":
if($_SESSION['user_session']->userloginstatus()) {
$studentnumber = $_POST['studentnumber'];
$password = $_POST['password'];
$response = $_SESSION['user_session']->login($studentnumber, $password);
http_response_code(206);
if ($response == true) {
http_response_code(202);
} else {
http_response_code(404);
}
} else {
http_response_code(401);
}
break;
case "processlogin":
if($_SESSION['user_session']->userloginstatus()) {
$studentnumber = $_POST['studentnumber'];
var_dump($studentnumber);
//$studentnumber = isset($_POST['studentnumber']) ? $_POST['studentnumber'] : 0;
$_SESSION['user_session']->loginprocess($studentnumber);
http_response_code(206);
} else {
http_response_code(401);
}
break;
default:
http_response_code(400);
break;
}
}
?>
So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section.
The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
EDIT1:
It might be useful to understand my files:
I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.
chat_action.php
session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
$chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}
Chat.php
<?php
class Chat{
private $host = 'localhost';
private $user = 'root';
private $password = "";
private $database = "chat_demo";
private $chatTable = 'chat';
private $chatUsersTable = 'chat_users';
private $chatLoginDetailsTable = 'chat_login_details';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
public function insertChat($reciever_userid, $user_id, $chat_message) {
$sqlInsert = "
INSERT INTO ".$this->chatTable."
(reciever_userid, sender_userid, message, status)
VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
$result = mysqli_query($this->dbConnect, $sqlInsert);
if(!$result){
return ('Error in query: '. mysqli_error($this->dbConnect));
} else {
$conversation = $this->getUserChat($user_id, $reciever_userid);
$data = array(
"conversation" => $conversation
);
echo json_encode($data);
}
}
public function getUserChat($from_user_id, $to_user_id) {
$fromUserAvatar = $this->getUserAvatar($from_user_id);
$toUserAvatar = $this->getUserAvatar($to_user_id);
$sqlQuery = "
SELECT * FROM ".$this->chatTable."
WHERE (sender_userid = '".$from_user_id."'
AND reciever_userid = '".$to_user_id."')
OR (sender_userid = '".$to_user_id."'
AND reciever_userid = '".$from_user_id."')
ORDER BY timestamp ASC";
$userChat = $this->getData($sqlQuery);
$conversation = '<ul>';
foreach($userChat as $chat){
$user_name = '';
if($chat["sender_userid"] == $from_user_id) {
$conversation .= '<li class="replies">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
} else {
$conversation .= '<li class="sent">';
$conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
}
$conversation .= '<p>'.$chat["message"].'</p>';
$conversation .= '</li>';
}
$conversation .= '</ul>';
return $conversation;
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error($this->dbConnect));
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getUserAvatar($userid){
$sqlQuery = "
SELECT avatar
FROM ".$this->chatUsersTable."
WHERE userid = '$userid'";
$userResult = $this->getData($sqlQuery);
$userAvatar = '';
foreach ($userResult as $user) {
$userAvatar = $user['avatar'];
}
return $userAvatar;
}
}
EDIT2:
From the console:
chat.js:106
index.php:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
you try to parsing not valid json, in your js maybe try this:
function sendMessage(to_user_id) {
message = $(".message-input input").val();
$('.message-input input').val('');
if($.trim(message) == '') {
return false;
}
$.ajax({
url:"chat_action.php",
method:"POST",
data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
success:function(response) {
alert('no');
try {
var resp = JSON.parse(response);
$('#conversation').html(resp.conversation);
} catch(e) { alert(e) }
$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
alert('yes');
},
});
}
I keep receiving this JSON error,i think it has something to do with html tags or any other tags that conflicts with it.
Here is my PHP Code:
<?php
require_once("connection.php");
class AddAdminUPController extends Connection{
public function addAdminUP(){
include "function.php";
$username = cleanData($_POST['username']);
$password = cleanData($_POST['password']);
if (!empty($username)){
if(!empty($password)){
if(strlen($password) > 8){
$select_query = "select * from sample_user where user_name = ?";
$stmt = $this->db->prepare($select_query);
$stmt->bindParam(1,$username);
if($stmt->execute()){
if($stmt->rowCount() <= 0){
$password = password_hash($password,PASSWORD_BCRYPT,array('cost' => 12));
$create_query = "insert into sample_user(user_name,password)values(?,?)";
$stmt = $this->db->prepare($create_query);
$stmt->bindParam(1,$username);
$stmt->bindParam(2,$password);
if($stmt->execute()){
echo "<script>".
"Materialize.toast('Created SuccessFully!', 5000, 'green')"
."</script>";
echo "<script>".
"$('#add_admin_up_form').hide();".
"$('#add_admin_up').hide();";
?>
$(".enrollment_title").html("<i class='material-icons'>fingerprint</i> Enroll Fingerprint");
<?php
echo "</script>";
include 'flexcode_sdk/include/global.php';
include 'flexcode_sdk/include/function.php';
if(isset($_GET['action']) && $_GET['action'] == 'add'){
$lastID = $this->db->lastInsertId();
?>
<script type="text/javascript">
$('title').html('User');
function user_register(user_id, user_name) {
$('body').ajaxMask();
regStats = 0;
regCt = -1;
try
{
timer_register.stop();
}
catch(err)
{
console.log('Registration timer has been init');
}
var limit = 4;
var ct = 1;
var timeout = 5000;
timer_register = $.timer(timeout, function() {
console.log("'"+user_name+"' registration checking...");
user_checkregister(user_id,$("#user_finger_"+user_id).html());
if (ct>=limit || regStats==1)
{
timer_register.stop();
console.log("'"+user_name+"' registration checking end");
if (ct>=limit && regStats==0)
{
alert("'"+user_name+"' registration fail!");
$('body').ajaxMask({ stop: true });
}
if (regStats==1)
{
$("#user_finger_"+user_id).html(regCt);
alert("'"+user_name+"' registration success!");
$('body').ajaxMask({ stop: true });
load('view_admin.php?action=add');
}
}
ct++;
});
}
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"¤t="+current,
type : "GET",
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}
</script>
<?php
$last_id_query = "select * from sample_user where user_id = ?";
$stmt = $this->db->prepare($last_id_query);
$stmt->bindParam(1,$lastID);
if ($stmt->execute()){
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$url_register =
base64_encode($base_path."register.php?user_id=".$row->user_id);
echo "<br><a href='finspot:FingerspotReg;$url_register' onclick=\"user_register('".$row->user_id."','".$row->user_name."')\" class='fw_button general_button btn waves-effect waves-light'>Register Fingerprint</a>";
}
}
}
elseif (isset ($_GET['action']) && $_GET['action'] == 'checkreg') {
$sql1 = "SELECT count(finger_id) as ct FROM sample_finger WHERE user_id=".$_GET['user_id'];
$result1 = mysql_query($sql1);
$data1 = mysql_fetch_array($result1);
if (intval($data1['ct']) > intval($_GET['current'])) {
$res['result'] = true;
$res['current'] = intval($data1['ct']);
}
else
{
$res['result'] = false;
}
echo json_encode($res);
}
else { echo "Parameter invalid..";}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username already exists!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is too short!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is empty!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username is empty!', 5000, 'red')"
."</script>";
}
}
}
$add_admin_up_controller = new AddAdminUPController;
echo $add_admin_up_controller->addAdminUP();
?>
I need help in fixing this kind of error. It keeps displaying:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Function.jQuery.parseJSON (jquery.js:8520) at Object.success (eval at (jquery.js:339), :55:90) at fire (jquery.js:3148) at Object.fireWith [as resolveWith] (jquery.js:3260) at done (jquery.js:9314) at XMLHttpRequest.callback (jquery.js:9718)
You are returning plain text instead of JSON. In your ajax call put the response dataType: 'json' and the part of PHP:
header("Content-Type: application/json");
echo json_encode($res);
exit;
This error due to your responce is not in json format and your ajax request is expecting json responce .
You can change responce header by use dataType : 'text/html' in your ajax request.
Here in action .
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"¤t="+current,
type : "GET",
dataType: 'text/html',
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}
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...