Ajax with map, getting data - javascript

I'm trying to use the $.map in ajax and I don't success with getting the data from json array. I'll show you the json file, the ajax code and the json output i get. Hope you can help me, thank you very much :) and sorry for my english! Here is the ajax:
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table, function( item ) { //dont get this line!
return {
label: item.trid,
value: item.trid
}
}));
}
});
And here is the json file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = ("select * from table;");
$json = array();
$result = mysql_query($data);
while($row = mysql_fetch_array ($result))
{
$array = array(
'trid' => $row['name'],
);
array_push($json, $array);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
?>
Here is the json output:
[{"name":"Emma"},{"name":"Eric"},{"name":"Peter"},{"name":"Sam"},{"name":"Roger"},{"name":"Sven"},{"name":"Julia"}]

You are referring to the wrong key, try it like this
$.map(data, function( item ) { //dont get this line!
return {
label: item.name,
value: item.name
}
})

Related

JQuery Ajax goes in error

My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)

Using pivottable.js with PHP query on Sql Server

I want to use pivottable.js on my data which I pulled from SQL Server using php.
Examples(http://nicolas.kruchten.com/pivottable/examples/) are for files JSON and CSV.
My data connection to html page is like below. How can I directly use this data on pivottable.js?
$server = "SQLSERVER";
$connectionInfo=array("Database"=>"SQLDATABASE","CharacterSet" => "UTF-8");
$conn= sqlsrv_connect($server,$connectionInfo);
$sql ="SELECT Column1,Column2,Column3,Column4 from TABLE";
$stmt = sqlsrv_prepare( $conn, $sql, array(), array('Scrollable' =>'buffered'));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute($stmt);
while($row = sqlsrv_fetch_array($stmt))
{
echo "<li>" . $row["Column1"] . $row["Column2"] . "</li>";
}
echo "<table border=1><tr><th>HEAD1</th><th>HEAD2</th><th>HEAD3</th><th>HEAD4</th></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
echo "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td> <td>".number_format($row[3], 0, ',', '.')."</td></tr>";
}
echo "</table>";
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
You could generate JSON array. It should look like
[
["HEAD1", "HEAD2", "HEAD3", "HEAD4"],
["va1", "val2", "val3", 123.45],
...
]
On page you may query PHP via $.ajax and then use pivottable.js with the result. $ajax is conviniet to show 'waiting' gif and hide it in 'success' finction.
$.ajax({
type: 'post',
url: 'https://path_to_your_php_script',
data: {
param1: "value1",
param2: "value2",
...
},
success: function (response) {
$("#output").pivotUI(eval(response), {
rows: ["HEAD1", "HEAD2"],
cols: ["HEAD3"],
vals: ["HEAD4"]
});
}
});
Other way
$.getJSON("https://path_to_your_php_script", function(mps) {
$("#output").pivotUI(mps, {
rows: ["HEAD1", "HEAD2"],
cols: ["HEAD3"],
vals: ["HEAD4"]
});
});

jQuery autocomplete retrieve data from database

I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.
Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});
Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});

Hide value in Bootstrap Typeahead

I'm using Bootstrap Typeahead with PHP to display a list from a database using source.php:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = $row['title'] . ',' . $row['id'];
}
// Return the json array
echo json_encode($array);
}
?>
You can see that I add both 'title' and 'id' to the array. All I want it to display in the typeahead is the title but I need the id for the links. Here is the JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
return item;
}
});
In the line beginning document.location I replace the comma between the two values with a forward slash and it works e.g. /england/123/. But it's the typeahead display that shows it as England,123 rather than just England.
Any help would be greatly appreciated.
OK managed to get a result with the following:
PHP:
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = array('label' => $row['title'], 'id' =>$row['id']);
}
// Return the json array
echo json_encode($array);
}
JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "http://www.stubowker.com/amex/cms/source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id +
"/";
return item;
}
});

conflict with typeahead, php and jquery 1.10.2

I have the following code in JavaScript:
$('input#search_user').typeahead({
source: function(query, process) {
$.ajax({
url: 'modulos/search_user.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(data);
}
});
}
});
And the following code in my PHP file:
if (isset($_POST['query'])) {
$query = $_POST['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
}
$data = array();
while ($row = mysql_fetch_object($sql))
{
$data[] = $row['nombre'];
}
echo json_encode( $data );
mysql_close($link);
But with jQuery 1.10.2 it throws the following error:
Uncaught Error: one of local, prefetch, or remote is required
What should I do about this?
now works with the next code
javascript
$(document).ready(function ()
{
$("input[name='search_user']").typeahead({
name: 'nombre',
remote: 'modulos/search_user.php?query=%QUERY'
});
}); // $(document).ready(function ()
php file
$query = $_GET['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
$data = array();
while ($row = mysql_fetch_assoc($sql))
{
$data[] = $row['nombre'];
}
mysql_close($link);
echo json_encode( $data );
my problem was the each method, for get column work with mysql_fetch_assoc but no with mysql_fetch_object

Categories