Get all values from mysql then make variables - php

Hi i want to get values from PHP files and make them usuable like array.
I'm using jquery.
How should i format retriever and php file to retrieve them all.
PHP file: i used switch to retrieve 1 at time but this method sucks
<?php
ob_start();
session_start();
include('mysql_config.php');
$konto = $_SESSION['login'];
$temp=mysql_fetch_array(mysql_query("SELECT `curchar` FROM `users` WHERE `login`='$konto'"));
$id = $temp['curchar'];
$gracz=mysql_fetch_array(mysql_query("SELECT * FROM `chars` WHERE `id`='$id'"));
$gracz['max_pz']=94+($gracz['str']+$gracz['stm']*5);
$gracz['max_pe']=7.1-($gracz['str']*0.1)+$gracz['stm']+$gracz['int']*2;
$gracz['max_exp']=($gracz['lvl']*10)*25;
if ($gracz['max_exp'] <= $gracz['exp'])
{
$gracz['lvl']++;
$zostalo = $gracz['exp']-$gracz['max_exp'];
mysql_query("UPDATE `chars` SET lvl=lvl+1, stats=stats+3, exp='$zostalo' WHERE `id`='$id'");
$gracz['exp']=$zostalo;
$gracz['max_exp']=($gracz['lvl']*10)*25;
}
$lol=$_POST['name'];
switch ($lol) {
case 'pz':
echo $gracz['pz'];
break;
case 'max_pz':
echo $gracz['max_pz'];
break;
case 'pe':
echo $gracz['pe'];
break;
case 'max_pe':
echo $gracz['max_pe'];
break;
case 'max_exp':
echo $gracz['max_exp'];
break;
case 'str':
echo $gracz['str'];
break;
case 'dex':
echo $gracz['dex'];
break;
case 'int':
echo $gracz['int'];
break;
case 'stm':
echo $gracz['stm'];
break;
case 'stats':
echo $gracz['stats'];
break;
case 'exp':
echo $gracz['exp'];
break;
case 'lvl':
echo $gracz['lvl'];
break;
case 'mapa':
echo $gracz['mapa'];
break;
case 'x':
echo $gracz['x'];
break;
case 'y':
echo $gracz['y'];
break;
default:
echo "post jest pusty";
break;
}
ob_end_flush();
?>
JS file(retriever): Here's retriever to get 1 variable but it is using sync that cause browser lags i don't want it
function get_char_val(merk)
{
var returnValue = null;
$.ajax({
type: "POST",
async: false,
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data)
{
returnValue = data;
}
});
return returnValue;
}

Use JSON. In your PHP file, just output:
echo json_encode($gracz);
And change your ajax handler to accept json data:
$.ajax({
type: "POST",
async: false,
url: "char_info2.php",
data: { name: merk },
dataType: "json",
success: function(data) {
// Use data.max_pz or whatever here
}
});

Related

Ajax post not passing data to php?

So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}

jquery.ajax json wrong?

hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));

DataType JSON doesn't work with php

Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];

Auto Complete with json and bootstrap

this is my code:
class_search.php
case 'users':
if(!empty($_REQUEST['user'])){
if(strlen($_REQUEST['user']) >= 3){
$_REQUEST['user'] = $this->sanitize($_REQUEST['user'], 'string');
$stmt = $this->sql->prepare('SELECT
id,
nome,
url
FROM
animes
WHERE
nome LIKE ?
LIMIT 10');
$stmt->execute(array('%'.$_REQUEST['user'].'%'));
$this->queries++;
$c = 0;
if($admin){
$result['users'] = array();
}
if($stmt->rowCount() > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').$row['nome'], 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').$row['nome'];
}
}
}
}
}
break;
general.js
$('#top_search').typeahead({
source: function(typeahead, query) {
$.ajax({
url: baseurl + "/ajax_calls.php",
dataType: "json",
type: "POST",
data: {
call: 'top_search',
user: query
},
success: function(data) {
typeahead.process(data);
}
});
},
onselect: function(obj) {
location.href= baseurl + '/animes/'+obj;
}
})
ajax_calls.php
case 'top_search':
$status = $site->process_autosearch('users');
break
;
I am having problem with onselect, I need to select the row url in my MySQL and encode to json, because when I click in one result I am redirect to mysite.com/animes/name of anime/ (yes, with space) and I need to fix this.
Table animes in phpMyAdmin:
http://s18.postimage.org/3ulrcmss9/Animes_Table.jpg
Quickly video: http://www.screenr.com/plZ7
You would need to use urlencode().
In your class_search.php file, update this part:
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').urlencode($row['nome']), 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').urlencode($row['nome']);
}
And to make the names looks good in the searche auto-complete as well, you need to modify your jQuery as well, wrapping the decodeURIComponent() function around the obj like so:
onselect: function(obj) {
location.href= baseurl + '/animes/' + decodeURIComponent(obj);
}

acessing PHP variables in javascript

OK, so I'm not a programmer so please don't beat me up too much... I have a situation where I have some javascript (for jqgrid) that I would like some of the values to be populated from a PHP variable. What I did to get around this is to use PHP and put all the javascript code within a 'here document'. All looks to work well but I thought I'd reach out to all of you to see if there is a way to streamline my programming. The code is below for reference.
global $database;
$switchesStr = "";
$sql = "SELECT id,name FROM switch ORDER BY name asc";
$result = $database->query($sql);
while($row = mysql_fetch_array($result,MYSQL_NUM)) {
$switchesStr .= $row[0].":".$row[1].";";
}
$switchesStr = substr_replace($switchesStr,"",-1);
$vlansStr = "";
$vlansStr = "0:System Default;";
$sql = "SELECT id,vlan_description FROM vlan ORDER BY default_name asc";
$result = $database->query($sql);
while($row = mysql_fetch_array($result,MYSQL_NUM)) {
$vlansStr .= $row[0].":".$row[1].";";
}
$vlansStr = substr_replace($vlansStr,"",-1);
echo <<<DOC
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#htmlTablePorts").jqGrid({
url:'crud_ports.php',
editurl:'crud_ports.php',
datatype: 'json',
mtype: 'POST',
colNames:['id','switch','Switch IP','Switch Name','Port Name','up','Comment','restart_now','Auth Profile','VLAN','Shutdown','Last Seen'],
colModel :[{
name:'id'
,width:55
},{
name:'switch'
,index:'switch'
,editable:true
},{
name:'ip'
,index:'ip'
,width:70
},{
name:'sname'
,index:'sname'
,width:120
,edittype:'select'
,editoptions:{value:"$switchesStr"}
},{
name:'pname'
,index:'pname'
,width:65
},{
name:'up'
,index:'up'
,width:80
},{
name:'comment'
,index:'comment'
,width:125
,editable:true
},{
name:'restart_now'
,index:'restart_now'
,width:110
},{
name:'auth_profile'
,index:'auth_profile'
,width:110
,editable:true
,edittype:'select'
,editoptions:{value:"0: ;1:Static;2:Dynamic"}
},{
name:'vlan_description'
,index:'vlan_description'
,width:110
,editable:true
,edittype:'select'
,editoptions:{value:"$vlansStr"}
},{
name:'shutdown'
,index:'shutdown'
,width:110
,editable:true
,edittype:'checkbox'
,editoptions:{value:"Yes:No"}
},{
name:'last_monitored'
,index:'last_monitored'
,width:110
}],
pager: jQuery('#htmlPagerPorts'),
rowNum:20,
rowList:[10,20,30,50,100],
sortname: 'switch',
sortorder: "asc",
viewrecords: true,
height: "auto",
imgpath: 'themes/steel/images',
caption: 'Port Management',
multiselect: false,
afterInsertRow: function(rowid, aData){
switch (aData.shutdown) {
case '0': jQuery("#htmlTablePorts").setCell(rowid,'shutdown','No',{}); break;
case '1': jQuery("#htmlTablePorts").setCell(rowid,'shutdown','Yes',{}); break;
}
switch (aData.auth_profile) {
case '0': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile',' ',{}); break;
case '1': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','Static',{}); break;
case '2': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','Dynamic',{}); break;
}
switch (aData.up) {
case '2': jQuery("#htmlTablePorts").setCell(rowid,'sname','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'pname','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'shutdown','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'ip','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'comment','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'vlan_description','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'last_monitored','',{background:'red',color:'white'});
break;
}
switch (aData.shutdown) {
case '2': jQuery("#htmlTablePorts").setCell(rowid,'sname','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'pname','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'shutdown','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'ip','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'comment','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'vlan_description','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'last_monitored','',{color:'red'});
break;
}
}
}).navGrid('#htmlPagerPorts',
{add:false}, //options
{height:130,reloadAfterSubmit:true}, // edit options
{height:130,reloadAfterSubmit:true}, // add options
{reloadAfterSubmit:true}, // del options
{} // search options
).hideCol(["id","switch","auth_profile","up","restart_now","shutdown"]);
});/* end of on ready event */
</script>
DOC;
I believe the best way to do this would be to inside your javascript echo out what you need. For example with json_encode:
<?php $name = 'Ben'; ?>
<script type="text/javascript">
var name = <?php echo json_encode($name); ?>;
alert(name);
</script>
Or if you know the type of the value and it is not complex (like a string):
<script type="text/javascript">
var name = "<?php echo $name; ?>";
alert(name);
</script>
You could have PHP write in the information at runtime...
<script type="text/javascript" language="<strong class="highlight">javascript</strong>">
<!--
<?php
echo("firstVar = $var1;");
echo("2ndVar = $var2;");
?>
// -->
</script>
Well, if you are confortable with this way, continue. Style is always personal...
The methods by BenMills and Urda are ok too. And, when the vars in javascript are strings, don't forget to quote it too.

Categories