I am newbie to php and mysql. Using Cordova plugin for visual studio 2015 i have created a simple mobile application in which a user selects a serial number and on selecting it data is showed on the chart. Also there is a toggle switch button through which i can change the state of the switch from on-off or off-on. While changing the state the data is inserted into DB.
Now, i want is to do is that whenever i select a serial number the last state of the toggle should be shown on the switch. Means if the user has previously change the state from on to off for a particular serial number than this change should be shown if the same serial number is selected again.
For this i have done the following
My PHP CODE
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = isset($_REQUEST['Command_Name'])?$_REQUEST['Command_Name']:"";
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
//print_r($result);
echo json_encode( (array) $result->fetch_object());
mysqli_close($con);
echo $cmd_Name;
My html(ajax) code
$.ajax({
method: "GET",
url: "http://localhost:Port/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = $.parseJSON(JSON.stringify(data));
console.log(dt);
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
} else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function () {
toastr.success('Data not fetched', '', { timeOut: 2000 })
}
});
Now whenever i run the app this part of code executes and it always goes to the else part. i.e if my serial number's last state is On it shows me off as shown in the below image
In above image you can clearly see that the command_Name = on but still it goes to else part.
I must be doing something wrong, and that i don't know.
Any help would be highly appreciated.
Related
I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work
I am having nearly 80,000 records in a single table in MYSQL, I wanna make it display in the Autocomplete control.
The table structure is given below
Table_name
-ID
-Code
-codeType
In client side, I have made that autocomplete script like given below
var Cds = "";
$.ajax({
type: "POST",
url:"cdList.php",
async: false,
data:{
value1 : '9'
},
success:function(result){
Cds = JSON.parse(result);
}
});
$("#prin").autocomplete({
minlength : 3,
source: Cds,
autoFocus:true,
width:500
});
cdList.php
<?php
$con = mysql_connect("localhost","***","***");
if(!$con){
die("Error : ".mysql_error());
}
mysql_select_db("ananth",$con);
$value1 = $_POST['value1'];
$cd9 = array();
$result = mysql_query("select * from Table_name where codeType = '9' AND Code LIKE '$value1%'");
while($row = mysql_fetch_array($result)){
$cd9[] = $row['Code'];
}
echo json_encode($cd9);
?>
Even i set minLength in autocomplete control, still i am feeling damn slowness on getting the data. It took around 30 seconds. So what will be the work around to make it fast?
Look at this post abot like operator.
For your case i reccomend using query_caching flag and select only one column instead *
select Code from Table_name where codeType = '9' AND Code LIKE '$value1%'
LIKE queries have a potential for taking a long time...
for autocomplete purposes you could use MySQL's LIMIT and return only a chunk of the relevant entries.
check out this link:
http://www.w3schools.com/php/php_mysql_select_limit.asp
also you should probably index codeType column for a faster search.
hope this helps
I've built an admin page for my site, that contains numerous forms that save, update, delete data into different tables in my database.
Currently i have one PHP file for each function that does the mysql query according to my ajax post command. which is getting a bit out of control.
for example i have a file for saving a new category
$cataddname = $_POST['name'];
$area = $_POST['area'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "INSERT INTO clet_faq_category (id, name, nickname, area) VALUES ('', '$cataddname', '$shortname', '$area')";
mysqli_query($db_connect, $update_category);
my save new category command posts to this file:
then i have a file that saves a category edit:
$cataddname = $_POST['name'];
$area = $_POST['area'];
$id = $_POST['cid'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "UPDATE clet_faq_category SET name='$cataddname', nickname='$shortname', area='$area' WHERE id = '$id'";
mysqli_query($db_connect, $update_category);
And another one to delete a category:
$c_id = $_POST['delete_id'];
$sql_del = "DELETE FROM clet_faq_category WHERE id = '$c_id'";
$del_question = mysqli_query( $db_connect, $sql_del );
then i have an jQuery ajax call that calls the page:
function newcat(){
var id = "answer";
tinymce.execCommand('mceRemoveEditor', true, id);
var category = document.getElementById('newcategory').value;
var area = document.getElementById('area').value;
var dataString = 'name=' + category + '&area=' + area;
$.ajax({
type: "post",
url: "newcat.php?area_id=" + areaid,
data : {
'name': category,
'area': area,
'query' : query
},
cache: false,
success: function(html){
$('#category_table').html(html);
$('#cat-form').text("Category Saved");
}
});
return false;
}
And When you look at them it's pretty much the same thing it's just a mysql query running.
What i'm trying to do is streamline this a little bit, i thought about passing the entire query via ajax to my php file, but that's not an option as anyone that can see my js file will be able to figure out all my queries and table names, and all they need to do is post a query to my php page and damage my entire DB.
so my question is, is there a way to do this in a smarter way maybe creating php functions inside the same file, that has category_delete(), category_add(), category_edit() on the same file and using ajax target each one of those categories, at least all my functions and queries will be on the same spot not in multiple separate files if you know what i mean.
You can do like this create a separate class which perform options for insert delete and update. and on your ajax page call these function like this
$func = new CUD();
switch($_POST['action'])
{
case 'delete':
$func->delete($values..)
case 'update':
$func->update($values..)
case 'delete':
$func->insert($values..)
}
You can have to send extra parameter in ajax as action, this parameter specifies the action
in php
switch($_POST['action'])
{
case 'delete':
.....
}
I've checked for duplicates and none of them are strictly related to this problem.
I have the following javascript code
var value = $.ajax({
type: "POST",
url: "bank.php",
data: {sum:money},
cache: false,
async: true
}).done(function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
and php in bank.php
if(isset($_POST['sum']))
{
$money = mysql_real_escape_string($_POST['sum']);
$query = "UPDATE banks SET currency = 1 WHERE amount = '.$money.'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
I receive in the browser console "success" for the ajax operation but nothing happens in the database. Take note that "currency" is a tinyint(1) and amount is an int(10) [I'm using sql tables as you might have guessed]. What am I doing wrong? (bank.php also includes the header to link to my database, so that's not the problem because I tested others queries there).
I believe the code isn't going through the if(isset($_POST['sum'])) validation but don't understand why. Any suggestions?
Try this :
$query = "UPDATE banks SET currency = 1 WHERE amount = ".$money.";
Hope this help u.
I have implemented on my site the jQuery autocomplete function which works well. However, I would like to use the result from the autocomplete to retrieve the selected person's telephone number from the database.
The database structure is this;
id | name | type | tel | mobile | email | level
===============================================
1 | John Smith | judge | 01234 567890 | 07812 345678 | jsmith#example.com | BS Two Star
Here is my updated code so far
Autocomplete function
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
change: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: 'id='+ id,
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
lookups/shows-sj-findtel.php
<?php
include("config.php");
mysql_connect ($DbHost, $DbUser, $DbPass);
mysql_select_db ("equilive_manager");
$id = $POST["id"];
$result = mysql_query("SELECT tel, mob FROM officials WHERE id='{$id}'");
$judgerow = mysql_fetch_array($result, MYSQL_ASSOC);
$contactdetails[] = array(
'tel' => $row['tel'],
'mob' => $row['mob'],
);
echo json_encode($data);
flush();
?>
lookups/shows-sj-searchforjudge.php
<?php
// if the 'term' variable is not sent with the request, exit
if ( !isset($_REQUEST['term']) ) exit;
// connect to the database server and select the appropriate database for use
include("../config.php");
mysql_connect ($DbHost, $DbUser, $DbPass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("equilive_manager");
// query the database table for name that match 'term'
$term = mysql_real_escape_string($_REQUEST['term']);
$rs = mysql_query("SELECT id, name, level FROM officials WHERE name LIKE '%{$term}%' ORDER BY name LIMIT 0,10");
// loop through each name returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['name'] .', '. $row['level'],
'value' => $row['name'],
'id' => $row['id'],
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Thanks in advance,
Craig
You have one issue at least in the code, which is that in getChiefJudgeContactDetails() you're mixing javascript with php. Mixing the two works fine if it's the first time you output a page and the code is on a PHP page. But if you're expecting the javascript to run PHP code every time a change event is triggered from the auto-complete, then that won't work.
Use the select event as others have stated, inside that, make a ajax request to a similar end point as your autocomplete but send it the value of your option (e.g. the ID value 2). Then use SQL in a PHP script to fetch the row for that id and return it as a json object. Parse the result and update UI in the jquery ajax call result handler.
update:
Change your autocomplete to look like this
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
select: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: {id:id},
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
Instead of using the change option of the autocomplete, use select (as stated by other answers to your question). Also, instead of using a string ("id="+id) as your data, use a js object ({id:id}). jquery will handle serializing it correctly before sending to the server, the result being that it actually shows up as a post variable in your php script.
Also, as more of a side note, I would suggest looking into using the PDO driver (http://www.php.net/manual/en/pdo.prepare.php) to access your database instead of using the mysql_* commands. It's object oriented and also automatically provides safety features that are not available in the old commands, such as prevention of SQL injection attacks.
You can do it in select option of autoComplete.
All you need to do is send new ajax request to get selected person number.
select: function (event, ui)
{
//make $.ajax request and send selected value.
//you can send selected value using => ui.item.value
}
You should use the "select" event of the autocomplete:
http://api.jqueryui.com/autocomplete/#event-select