Hi I'm making a change to a text area and thanks to this plugin I can mention users from a db after entering # in a textarea you place the complete code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<link href="bootstrap-suggest.css" rel="stylesheet" type="text/css">
</head>
<body>
<textarea class="form-control" rows="8" id="example-1"></textarea>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="bootstrap-suggest.js"></script>
<script>
var users = [
{username: 'lodev09', fullname: 'Jovanni Lo'}
];
$('#example-1').suggest('#', {
data: users,
map: function(user) {
return {
value: user.username,
text: '<strong>'+user.username+'</strong> <small>'+user.fullname+'</small>'
}
}
})
</script>
</body>
</html>
in the user variable there are the search fields by default, I ask you for help, which instead of the defaul fields in the variable, the search is done in a php page, the data to search from my database sql, how can I change the code? how do I change defaul fields with dynamic fields taken from the database? Thanks I hope you help me
So I pretty much just followed the documentation on http://lodev09.github.io/bootstrap-suggest/#api
I wanted to include Axios as that's a more preferred way to fetch data in large scale applications.
and in their example return $.getJSON("users/data.json", { q: q }); using q by default will look up all the keys in the array. You can specify if you only want to search say for username with { username: q }
Here's my working db example you can use from {} myjson
Now the part that'd you change for getting this to work with your php backend is the api and api endpoint you've setup.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
<link href="bootstrap-suggest.css" rel="stylesheet" type="text/css" />
</head>
<body>
<textarea class="form-control" rows="8" id="example-1">type after -> #</textarea>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://lodev09.github.io/bootstrap-suggest/bower_components/bootstrap-suggest/bootstrap-suggest.js"></script>
<script>
$('#example-1').suggest('#', {
data: function(q) {
if (q) {
return $.getJSON('https://api.myjson.com/bins/18vsxq', {
q: q
}).then(function(Response) {
return Response.users
});
}
},
map: function(user) {
return {
value: user.username,
text: '<strong>' + user.username + '</strong> <small>' + user.fullname + '</small>'
}
}
})
</script>
</body>
</html>
anyways hopes this helps,
-Brendan
Related
I'm trying to get the data value on success from the php. However when I alert(data) in the success, it returns the page html.
HTML:
<input type="text" class="form-control" name="project_name" id="projectName" required>
Jquery AJAX:
$('#projectName').on('blur', function(){
var projectName = $(this).val();
$.ajax({
url: 'page.php',
type: 'POST',
dataType: 'text',
data: {
'projectChecked': 1,
'project_name': projectName,
},
success: function(data){
if (data == 'taken') {
$('#projectName').addClass('border-red');
}
}
});
});
PHP:
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
Alert Message:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="/favicon.png"/>
<title>Page Title</title>
<meta name="description" content="Meta Description">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlTw8HfCJo=" crossorigin="anonymous"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-157194354-1"></script>
You should use exit in php code to get return data use following code
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
can you check the html code when you do alert(data); and post here?
alternatively, you might want to check the developer tools of browser and validate network tab to monitor parameters and response of ajax request.
It is possible that you are getting http 400/500 response and you are actually seeing default error page (which is of course not a JSON response) in the data variable (this depends on the way server is configured)
been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});
I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>
This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.
I have the following code configured to reference an offsite XML file and autocomplete and return the value. It is not working no matter if I hardcode the data element like you see below or if I comment the data: element out. I've tried to change the Type: from Post to Get in both scenarios as well. I've also confirmed that the .xml is in the URL path specified as well as try to simply place it in the same directory as the .php file you see below. No errors are generated on the webserver either.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.3.js'></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/start/jquery-ui.css">
<style type='text/css'>
.red {color: red}
</style>
<script type='text/javascript'>
$(window).load(function(){
$.ajax({
url: "domain/file.xml",
type: "POST",
dataType: "xml",
data: {
xml: "<geonames><geoname><name>London</name><geonameId>2643743</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname><geoname><name>London</name><geonameId>6058560</geonameId><countryCode>CA</countryCode><countryName>Canada</countryName></geoname><geoname><name>The Tower of London</name><geonameId>6286786</geonameId><countryCode>GB</countryCode><countryName>United Kingdom</countryName></geoname></geonames>"
}, //should not need to define 'data' on your own xml call
success: function(xmlResponse) {
var data = $("geoname", xmlResponse).map(function() {
return {
value: $("name", this).text() + ", " + ($.trim($("countryName", this).text()) || "(unknown country)"),
id: $("geonameId", this).text()
};
}).get();
$("#test").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function(item) {
return matcher.test(item.value);
}));
},
minLength: 2,
select: function(event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.value + ", geonameId: " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
}
});
});//]]>
</script>
</head>
<body>
<p class="ui-widget">Try typing 'Lo' it will match on 'London'.</p>
<div class="ui-widget">
<label for="test">London matches: </label>
<input id="test" />
</div>
<p id="result" class="ui-widget red"></p>
</body>
</html>
If you can open the remote URL directly in the browser or a browser addon, but not using Ajax, the same-origin policy and missing CORS headers are the most likely reason.
The remote resource has to provide CORS headers. Otherwise the browser will not open it in the XHR object (jQuery.ajax() uses XHR internally).
Open the network tab of the developer tools in your browser an check the request/response headers.
I am trying receive the JSON data using PhoneGap application. I am using server xampp php server. On this server I have server code api.php for receiving data from database. My laptop's IP address is 192.168.1.4 so the URL of this local server is http ://192.168.1.4/Experiements/webservices/api.php".
I am able to receive the data using
alert(JSON.stringify(response));
but I want to add this _email_id_ information to
<div id="email">Email_id< /div >
which is defined in index.html.
From my Android phone I want to just log in and and receive the email_id of that user. Please see the image of my database and and data receive on my phone using
alert(JSON.stringify(response)).
My server code is api.php
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("demo");
if(isset($_GET['type']))
{
if($_GET['type']=="login"){
$username=$_GET['UserName'];
$Password=$_GET['Password'];
$query="Select * from registration where UserName='$username' and Password='$Password'";
$result=mysql_query($query);
$totalRows=mysql_num_rows($result);
if($totalRows>0){
$recipes=array();
while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){
$recipes[]=array('User'=>$recipe);
}
$output=json_encode(($recipes));
echo $output;
}
}
}
else{
echo "Invalid format";
}
My PhoneGap application code is in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title> Database Application</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$("#btnLogin").click(function(){
var userId = document.getElementById('id').value;
var userPassword = document.getElementById('password').value;
$.ajax({
url:"http://192.168.0.106/Experiements/webservices/api.php",
type:"GET",
dataType:"json",
data:{type:"login", UserName:userId,Password:userPassword},
ContentType:"application/json",
success: function(response){
alert(JSON.stringify(response));
console.log(JSON.stringify(response));
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
<script type="text/javascript">
document.addEventListener("deviceready",OnDeviceReady,false);
function OnDeviceReady(){
//alert("cordova is loaded");
}
</script>
</head>
<body>
User ID : <input type="text" id="id" name="user" />
User Password : <input type="text" id="password" name="password" />
<input type="button" id="btnLogin" name="btnLogin" value="Login"/>
<div id="email">Email_id</div>
</body>
</html>
DataBase: demo, user: root, password: 1234, table: registration
Screen shot of my phone:
So if I understood you correctly, what you want to do is to get the email_id from the response and put the content into the div called email.
What you need to do is to first get the user's email from the JSON object which is in your case Array with just one item. This first item of array again is Object which contains field called email which is exactly what we want. After that we need to locate the div from the DOM with jQuery element selector and insert the user's email in it. Example is found below.
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
I'm using the jQuery UI Autocomplete as helper in a form. When I try to use it to search from a list of available IPs it never filter the results, no matter the number of characters (numbers) I type it always returns the complete list.
How can I correct it?
I am using this code http://jqueryui.com/autocomplete/#remote-with-cache
The JSON generated from a PHP file is similiar to this (I have reduced the number of results):
["192.168.3.2","192.168.3.3","192.168.3.4","192.168.3.5","192.168.3.6","192.168.3.7","192.168.3.8","192.168.3.9","192.168.3.10"]
[Edit]
The form page code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Remote with caching</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
var cache = {};
$("#birds").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[ term ]);
return;
}
$.getJSON("tab-ip-autocomplete.php", request, function(data, status, xhr) {
cache[ term ] = data;
response(data);
});
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
The PHP to JSON code:
<?php
include_once 'conn.php';
INET_NTOA(ipv4) LIKE :ipv4";
$autocomplete = "SELECT * FROM vteste;";
$STH = $DBH->prepare($autocomplete);
$STH->bindParam(':ipv4', $ipv4, PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH->fetch();
/* gera json */
$arr = array();
while ($row = $STH->fetch()):
$arr[] = $row['ipv4'];
endwhile;
$json = json_encode($arr);
echo $json;
?>
When using a remote datasource, the jQueryUI AutoComplete doesn't filter your results - it is down to the script which provides the data to send over only matching results.
From the http://api.jqueryui.com/autocomplete/#option-source:
The Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.