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);
}
}
});
}
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'm having trouble implementing if statement in ajax success function.
<?php
include('../Config/config.php');
$myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
$execute = mysqli_query($mysqli, $myquery);
if (mysqli_num_rows($execute) >= 1)
{
echo "Precinct is full.\n Recheck precinct number.";
}
?>
function checkerprecinct() {
var precinct = $("#precinct").val();
$.ajax({
type: "POST",
url: "precinctchecker.php",
data: "precinct=" + precinct,
success: function(data) {
console.log(data);
if (data === "") {
alert("Data is empty!");
} else {
alert(data);
}
}
});
}
I would like to use this as a validation.
I want to alert the user if the sent data contains similar data from the database.
try this code
change with your code
PHP Code:
$data = array();
if (mysqli_num_rows($execute) >= 1)
{
$data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
//echo "Precinct is full.\n Recheck precinct number.";
}else{
$data= array('code'=>101,'message'=>"Data is empty!");
}
echo json_encode($data);
exit;
ajax code:
var data = JSON.parse(data);
if (data['code'] == 100) {
alert(data['message']);
}
I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
echo '<ul>';
foreach($all_pics_of_item as $key=>$val)
{
if ($val['pics_main']=='yes')
{
$set_checked = "checked";
$action = true;
}
else
{
$set_checked = "";
$action = false;
}
echo '<li style="float: left;margin:10px;border: 1px solid #000;padding:10px;">';
echo '<img style="width:120px;height:120px;" src="../../gallery_images/thumbs/'.$val['pics_source'].'">';
echo '<br>'.$val['pics_name'];
echo '<br><div class="delet"><b>x</b></div>';
echo '<br><form method="post" action="update_main_pic.php" enctype="text/plain" >
Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
</form>';
echo '</li>';
}
echo '<ul>';
}
Here is the AJAX and script:
$(document).ready(function(){
$(':checkbox').click(function() {
$(':checkbox').not(this).removeAttr('checked');
var picid = $(this).attr('data-picid');
var itemid = $(this).attr('data-itemid');
var action = $(this).is(':checked');
//if((this).attr('checked',true))
//{
// var action = true;
//}
//else
// {
// var action = false;
// }
$.ajax({
url: "ajax_update_main_pic.php",
type: "POST",
data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
timeout:5000,
dataType: "html",
beforeSend:function(){
},
error: function(){
alert('Problem !');
},
success: function(msg){
if(msg == 'no')
{
}
else
{
}
},
complete: function(){
}
})
});
}); //END READY
Here is the update function:
<?php
require_once "../../db.php";
require_once "../../functions.php";
if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
die();
}
if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )
{
global $db;
try
{
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
$stmt->execute();
return true;
}
catch(Exception $e)
{
return false;
}
}
$result = update_main_pic($item_id, $pic_id, $pic_show );
if($result == false)
{
die('Problem updating pics');
}
else
{
header('location: upload_image.php?iid='.$item_id);
die();
}
?>
I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics
The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);
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
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});