I retrireve data from my MySQL database into a simple table. Above this table I should have a text-input. On entering a keyword into this input, I want to cancel all showing data in the table and display data, found by %LIKE% operator, matching the keyword entered.Something similar does jQueryUi Autcomplete, FooTable and a couple of Yii extensions, but I wanna do it all from scratch. Any ideas on how to do it? Links?
My knowledge:
$.ajax({
url: 'ajax/test.html',
success: function(){
alert('Load was performed.');
}
});
What I am going to give you is not the complete code.
You want to do it yourself so here is only the logic.
In you index.php file
<input type="text" name="autocoplete" id="autocomplete"/>
<div id="result"></div>
<script type="text/javascript">
$(document).on('keyup', '#autocompelte', function(){
var text = $('#autocomplete').val();
$.post('process.php', {text:text}, function(resultData){
//Treat your resultData and convert into HTML for example
$('#result').html(myHTMLResult);
}, 'json'); //I want my result as JSON
});
</script>
process.php
if(true === isset($_GET['text']) && false === empty($_GET['text']))
{
//Do your query where you field is like %$_GET['text']% : example : SELECT * FROM mytable WHERE myfield like %$_GET['text']%
//Store all your result in an array
//Format this array into json to be easy to treat with json
//Send this json back to your index.php file.
echo json_encode($listResult);
}
#ThinkTank thank you very much for the help. It works just fine. Here is my final code:
$(document).ready(function() {
$('#input').keyup(function(eventObject){
//cancel all displaying data in the table if keyword exists
if($(this).val()) {
//$("td").hide();
$("td").remove();
//data hid, now send data to server
var orgValue = $(this).val();
$.ajax({
url: '/products/RetrieveData',
data: 'term='+orgValue,
success: function(data) {
var jsondata=$.parseJSON(data);
$.each(jsondata, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
}
});
} else {
$("td").show();
}
});
} );
Just some ideas:
1. Once I find (filter out) what I need, I clear the input with backspace. How do I set the table to the initial state with the data?
Related
I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery
I have a page with a lot of input fields. I am using Jquery to get all of the values of the form at once using data: $("#profile").serialize().
Since my MySQL columns have the same name as my input fields. Is there an easy to select * from my db and load the results into the appropriate fields using jquery / ajax? Perhaps an example or a link?
Thanks,
Scott
Edit: Ok thanks for the help, but I am still a bit lost and not getting it to work, here is what I have so far:
<script type="text/javascript">
$(window).load(function(){
$.ajax({
url: "/profile_functions/profile_about_retrieve.php",
type: 'POST',
data: allFormFields,
success: function(){
//console.log('done');
}
});
jQuery(#profile).find(":input").each(function(key, val) {
fieldName = jQuery(this).attr("name");
if(fieldName != "" && fieldName != undefined) {
allFormFields[fieldName] = jQuery(this).val();
}
});
});
</script>
And a little test data from my db being echo'ed via json_encode
[{"key":"test","value":"9"}]
And html
<form id="profile" method="post">
<input type="text" name="test"
</form>
jQuery(formId).find(":input").each(function(key, val) {
fieldName = jQuery(this).attr("name");
if(fieldName != "" && fieldName != undefined) {
allFormFields[fieldName] = jQuery(this).val();
}
});
Use the allFormFields array to send to the PHP endpoint
$.ajax({
url: url,
type: 'POST',
data: allFormFields,
success: function(){
console.log('done');
}
});
I've only every used json to fetch data to use on pages or set as variables. But now I would like to search json for a matching name then fetch its views from the json
[{"id":1,"name":"Pale","description":"This is a description","url":"http://domain.com//1/pale","views":2212,"createdBy":{"name":"Bill Lumbergh","url":"http://domain.com"},"createdOn":"2013-10-24T22:54:34.183"},
Above is a little example and using the below code only console.logs the entire json which has about 20 id's
$.getJSON( "content.php", { name: 'Pale' } ,function(data){
console.log(data);
});
$.ajax({
url: 'content.php',
dataType: "json",
success: function (data) {
$.each(data, function(k,v){
if (v.name == theme){
console.log(v.views);
}
});
}
});
The Object you put in the code is the one you are passing to the Server, not receiving. {name:'Pale'} is being sent to the server. If you want the name from the JSON file, it's like:
$.getJSON('content.php', function(data){
console.log(data.name);
});
However, if my guess is correct try the following:
$.getJSON('content.php', function(data){
var ary = data.arrayThatHoldsYourObjects, store;
$.each(ary, function(i, v){
if(v.name === 'Pale'){
store = v.views;
}
});
});
store now holds v.views.
I can incorporate jquery ui autocomplete with source from database. How, I am trying to get the source from a prepared json file, the content is like this:-
{"data":[{"id":"1","country_name_en":"USA","country_name_hk":"\u7f8e\u570b"},{"id":"2","country_name_en":"China","country_name_hk":"\u4e2d\u570b"},{"id":"3","country_name_en":"British","country_name_hk":"\u82f1\u570b"}]}
I tried to modify the jquery codes as follow:-
<script>
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
alert(data);
})
}
});
</script>
but I think I do not written the format correctly. How shall I improve the way to extract the data from the json file?
The autocomplete won't show anything until you tell it to do so by calling the response function passed to your source method with the allowed autocomplete values. So you should do something like this:
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
var choices = [];
for(var i=0;i<data.data.length;i++) {
choices.push(data.data[i].country_name_en);
}
response(choices);
})
}
});
Also just a tip, you're going to confuse yourself by naming everything "data".
Ajax can be used for this refer this article which list countries from geonames.org(contains huge list country,state,regions). This will help you in some way.
To get data from json try this..
$("#country").autocomplete({
source: function(request, response) {
$.getJSON('../../database/country.json', { id: data.id }, function(data) {
$.each(data, function(key, value) {
alert(value.country_name_en); // json data
});
});
}
});
The problem is, you need to call the autocomplete callback from the ajax success handler.
$(function() {
$("#country").autocomplete({
source : function(request, response) {
$.getJSON('country.json', {
id : 1
}, function(data) {
var list = $.map(data.data, function(item, index) {
return {
id : item.id,
label : item.country_name_en
};
});
response(list);
})
}
});
})
Demo: Plunker
i need some code for the next step..this my first step:
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
});
</script>
after matches..i want the result can connect to data base then show data from table inside <div id="value">...how to do that?
you can start here. $.ajax();
You should have some server side scripting knowledge also.
You will need to do it using an ajax call (matches will be a parameter for the call). The php script called through ajax will have to fetch the data and give it back to the calling page.
There you will need to parse the ajax response and display what you want.
A helpfull tutorial can be found here.
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
$.ajax({
type:"post",
url:"process.php",
data:params,
cache :false,
async :false,
success : function() {
alert("Data have been input");
$("#value").html(matches);
return this;
},
error : function() {
alert("Data failed to input.");
}
});
return false;
});
</script>
and i change my process.php become:
select itemdata as version from settingdata where version = "tunerrange";