I am loading boolean data from mySql. the db is 0 or 1. However JSON wants true or false for a form to load properly. I have 30 fields in the actual table. And yes I can convert the 0 1 to true false in the select using a case statement. But there must be an easier way to do this?
I have lots of boolean fields in the actual production. Maybe JSON doesn't handle this and only handles plain type="text"?
Otherwise I can load it all with PHP and set the values on load
Here is the original JSON
[{"drscomplete":"0"}]
and this is what I need for the checkbox to work properly on a form
[{"drscomplete":"true"}]
Here is the load php
$SQL ="SELECT * from dealfinalize d where d.ID=" . $id;
$resultArray = array();
$result = mysqli_query($con,$SQL);
if($result->num_rows >0 )
$resultArray = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($resultArray);
and here is the ajax
jQuery.ajax({
url: "dealfinalizeload.php",
data:'id='+id,
type: "POST",
success:function(data){
var data2 = $.parseJSON(data);
$('div#white_content_dealfinalize').loadJSON(data2);
alert(data);
},
error:function (){
alert("Error loading tasks");
}
});
You can use case
select t1.column1,
case when t2.column == 1
then 'true'
else 'false'
end OrderedAll
from yourtable t1
Related
Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!
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 trying to access some info in my database and displaying the result of my query in some textboxes.. my code works but it says object object..
here's my jQuery code:
jQuery('body').on('click', '.update_button', function() {
var manufacturer_part = jQuery(this).val();
jQuery.ajax({
url: '/codes/clearhouse_processor.php',
type: 'POST',
data: {update_key: manufacturer_part},
dataType: 'json',
success: function(result) {
jQuery('#update-manufacturer-part').val(result.part_number);
jQuery('#update-manufacturer').val(result.manufacturer);
jQuery('.update-form').stop();
jQuery('.update-form').slideToggle('slow');
jQuery('html,body').animate({
scrollTop: jQuery('.update-form').offset().top-60
}, 750);
}
});
});
and here's my php code...
if(isset($_POST['update_key'])){
$manufacturer_part = $_POST['update_key'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('part_number')));
$query->from($db->quoteName('clearing_house'));
$query->where($db->quoteName('part_number') . '='.preg_replace("/[^0-9,.]/", "", #$manufacturer_part) );
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo json_encode($results);
}
and btw, I am using joomla here...
thanks in advance,
jQuery('#update-manufacturer-part').val(result[0].part_number);
it is receiving an array from the server
by the result you gave
and if you want to see all the results that you receive
jQuery('#update-manufacturer-part').val(result[0].part_number);
_.map(result,function(){return part_number; }).join(",")
on the query itself update the fields that you need to get
$query->select($db->quoteName(array('part_number', 'manufacturer', 'field3', 'fieild4')));
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.
Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!