jQuery display object value - php

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')));

Related

Give autonumber Id MySQL back with an AJAX call? [duplicate]

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!

Ajax request dataType json

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

ajax/php autocomplete issue

i'm new to pdo and json. I want to make an autocomplete searching by username and also displaying pic next to name. The issue i have is that my script is not displaying pic next to name but it makes it part of autocomplete, i mean it displays if it matches the letters from the search box. Sorry if my english is bad.Here is my sql script:
include("configPDO.php");
// Query to get the usable suggestions
$likeString = '%' . $_GET['term'] . '%';
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT username,avatar,id FROM `users` WHERE username LIKE :likeString");
// bind parameters, Named parameters always start with colon(:)
$STM->bindParam(':likeString', $likeString);
// For Executing prepared statement we will use below function
$STM->execute();
// we will fetch records like this and use foreach loop to show multiple Results
$STMrecords = $STM->fetchAll();
$Category_array = array();
foreach($STMrecords as $row)
{
$result = $row[0].$row[1];
array_push($Category_array, $result);
}
$json = json_encode($Category_array);
echo $json;
this is my ajax code using jquery.ui.autocomplete.js
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: 'Get_Auto1.php',
dataType: 'json',
success: function(data){
$('#searchg').autocomplete(
{
source: data,
minLength: 1
});
}
});
});
</script>
Thnx in advance.
I managed to make it displaying the avatar next to each result but id doesnt show the image itself just the url ex:"http://twingoo.ro/images/twingoo_logo.png", i also tryed with img src. I modified this line of code: $result = $row[0].$row[1];
here is the link of the demo: demo link

Retrieve data from MySQL database after jQuery autocomplete

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

Returning a JSON object from PHP in AJAX call?

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!

Categories