How I can send rowNumber variable to dataSource php file in this code ?
function getData(dataSource, divID,rowNumber)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
obj.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
PHP File (datasource):
<?php
//mysql connection
$result = mysql_query( 'CALL view_polls(`rowNumber`);' );
$row=mysql_fetch_array($result);
echo $row['title'];
?>
in JavaScript:
XMLHttpRequestObject.open("GET", dataSource + '?rowNumber=' + rowNumber);
in PHP:
$result = mysql_query( 'CALL view_polls(`' . $_GET['rowNumber'] . '`);' );
function getData(dataSource, divID,rowNumber)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource + "?rownumber=" + rowNumber);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
obj.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
PHP:
<?php
if (isset($_GET['rownumber']) && is_numeric($_GET['rownumber'])) {
$rowNumber = $_GET['rownumber'];
//mysql connection
$result = mysql_query( 'CALL view_polls(`' . $rowNumber . '`);' );
$row=mysql_fetch_array($result);
echo $row['title'];
}
else {
echo "Error";
}
?>
Related
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);
}
}
});
}
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 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
Hi i am having trouble making this ajax code work with JavaScript. The function is called studentReqHandler with a button onclick function and everything is in echo's. this is the code of the function studentReqHandler:
echo "<script type='text/javascript'>
function studentReqHandler(action,id,email,elem){
_(elem).innerHTML = 'processing ...';
var ajax = ajaxObj('POST', 'verifying.php');
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'accept_ok'){
_(elem).innerHTML = '<b>User Verified!</b><br />';
} else {
_(elem).innerHTML = ajax.responseText;
}
}
}
ajax.send('action='+action+'&id='+id+'&email='+email);
}
</script>
this is the onclick button :
<button onclick='studentReqHandler(\"accept\",\"".$id."\",\"".$email."\",\"user_info_".$id."\")'>accept</button> or
";
other ajax related functions:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
and last the php for this to work:
if (isset($_POST['action']) && isset($_POST['id'])&& isset($_POST['email'])){
$id = preg_replace('#[^0-9]#', '', $_POST['id']);
$email = $_POST['email'];
if($_POST['action'] == "accept"){
$sql = "UPDATE profile SET verified='1' WHERE id='$id' AND email='$email' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "accept_ok";
exit();
}
}
Can anyone figure out why this doesnt work?
I pasted this code and it works:
Minimum error, is you got some messy quotes in the <button> javascript string.
<?php
/* using this at the top to check what happens when it posts. */
if (isset($_POST['action']) && isset($_POST['id'])&& isset($_POST['email'])){
$id = preg_replace('#[^0-9]#', '', $_POST['id']);
$email = $_POST['email'];
if($_POST['action'] == "accept"){
/* I commented out the query, so you must make sure that works right */
$sql = "UPDATE profile SET verified='1' WHERE id='$id' AND email='$email' LIMIT 1";
//$query = mysqli_query($db_conx, $sql);
// mysqli_close($db_conx);
echo "accept_ok";
exit();
}
}
/* some default values. You need to make sure you get these from somewhere.*/
$id=3;
$email="oo#oooo.com";
/* ELEMENT changes when I click the button */
echo "Div Element <div id='element'>ELEMENT</div> area<br><br>";
?>
<script type='text/javascript'>
function studentReqHandler(action,id,email,elem) {
/* I used the basic document element locator */
document.getElementById('element').innerHTML = 'processing ...';
/* I posted to itself this time. */
var ajax = ajaxObj('POST', 'ajax.php');
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'accept_ok'){
document.getElementById('element').innerHTML = '<b>User Verified!</b><br />';
} else {
document.getElementById('element').innerHTML = ajax.responseText;
}
}
}
ajax.send('action='+action+'&id='+id+'&email='+email);
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
/* There were too many quotes and \'s in the original button. */
<br>The Button<br>
<?php
echo "<button onclick=\"studentReqHandler('accept','$id','$email','user_info_$id') \">accept</button>";
?>