Here is my function i wrote for getting usernames, location, and their pictures. Now the problem is if I use mustMatch option with it, every thing is working fine except for one bug. If lets say i type S it bring 'Sebastian' 'einstain'. If i select sebastian everything works like charm but if i select einstain it erases everything.
I tried to use change: event but its not firing in any case dont know why
$(document).ready(function(){
var wp_v = '3';
$("#searchbox").autocomplete("search.php?wp="+wp_v, {
matchContains: true,
//mustMatch: true,
width: 258,
scroll: true,
scrollHeight: 350,
dataType: 'json',
change: function (event, ui) {
alert('change');
if (!ui.item) {
$(this).val('');
}
},
parse: function(data) {
var array = new Array();
for (var i = 0; i < data.length; i++) {
array[array.length] = {
data: data[i],
value: data[i].name,
result: data[i].name
};
}
return array;
},
formatItem: function(row) {
var output = "<img class=img src='avatars/" + row.img + "'/> ";
output += "<span class=name>"+row.name+"</span><br/>";
output += "<span class=small>"+row.country+"</span><br/>";
return output;
}
}).result(function(event,item) {
if (item == undefined) {
$('#receiver').val('');
} else {
$('#receiver').val(item.uid);
}
});
});
This is the source
[
{"uid":"2","name":"Sebastian Aparicio","img":"1339875067-Koala.jpeg","country":"Leder"},
{"uid":"12","name":"Mester Jakob","img":"default.jpeg","country":"Salg"},
{"uid":"19","name":"Mester Jakob","img":"1339875047-Penguins.jpeg","country":"Leder"}
]
Actually autocomplete plugin version was different. That's why it was not working.
Related
This is what I have tried so far and it works fine without a custom template. However I need to show some more data, such as images etc., within the search result. How can I call a custom template along with AJAX?
<input type="text" class="site-search" name="search">
var path = "{{ route('site-search') }}";
$('input.site-search').typeahead({
hint: true,
highlight: true,
display: 'value',
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
See the docs. Just make your template function and use |raw modifier to show clean, non-escaped html.
display: "series",
template: function (query, item) {
var template = '<span data-series="{{series|raw}}">' +
'{{series}}, {{seasons}} seasons -' +
'<var data-rating="{{rating|raw}}">{{rating}}/10</var></span>'
if (item.rating >= 9) {
template += '<span class="ribbon">Top Rated</span>';
}
return template;
},
source: {
data: [
{
series: "Breaking Bad",
seasons: 5,
rating: 9.6
}
...
]
}
I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}
The charts I am using are written in JavaScript, so I need to transfer mysql query arrays to JavaScript, creating the charts. The mysql queries are generated by drop down menus. On the web page is a button that, when clicked, should display the chart. All should be displayed on the same page.
I have two drop down menus with names of runners in each. through onChange, each drop down menu calls the same JavaScript function -
home.php
<form id='awayPick'>
<select name='awayRunner' id='awayRunner' onchange='Javascript: getitdone(this);/>
...multiple options
</form>
<form id='homePick'>
<select name='homeRunner' id='homeRunner' onchange='Javascript: getitdone(this);/>
...multiple options
</form>
Js.js
function getitdone(str)
{
if (str=="")
{
document.getElementById("midSpa").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp11=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp11=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp11.onreadystatechange=function()
{
if (xmlhttp11.readyState==4 && xmlhttp11.status==200)
{
document.getElementById("midSpa").innerHTML=xmlhttp11.responseText;
}
}
var awayRunner = document.getElementById('awayRunner').value;
var homeRunner = document.getElementById('homeRunner').value;
var queryString = "?awayRunner=" + awayRunner + "&homeRunner=" + homeRunner;
xmlhttp11.open("GET","getRunners.php" + queryString,true);
xmlhttp11.send(null);
}
getRunners.php
$home=$_GET['homeRunner'];
$away=$_GET['awayRunner'];
$db = db;
$homeRunner=array();
$awayRunner = array();
$leagueRunner = array();
$getHome="select ... from $db where ... = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['...'];
}
$getAway="select ... from $db where ... ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['...'];
}
$week = 0;
while($week<20){
$week++;
$getLeague = "select ... from $db where ... = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$leagueRunner[]=$row3['...'];
}
}
home.php
<script type="text/javascript">
function chartOne(){
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
zoomType:'xy' },
title: {
text:
'title'
},
xAxis: {
categories: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
},
yAxis: [{ // Primary yAxis
labels: {
formatter: function() {
return this.value + 'pts'
},
style: {
color: '#89A54E'
}
},
title: {
text: 'text',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text:null,
},
}],
tooltip: {
formatter: function() {
return '' +
this.y +
(this.series.name == ' ' ? ' mm' : 'pts');
}
},
legend: {
layout: 'horizontal',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 69,
y: 20,
floating: true,
shadow: true,
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name:'adfg',
data: [ <?php echo join($awayRunner, ',');?>],
type: 'column',
pointStart: 0
//pointInterval
},
{
name:'fghtrht',
data: [<?php echo join($homeRunner, ',');?>],
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [ <?php echo join($leagueRunner, ',');?>],
type:'spline',
pointStart: 0
//pointInterval
},
]
});
});
}
</script>
<input type='submit' value='chart One' onclick='chartOne()'></input>
<div id='container' style='width: 50%; height: 200px; float: left;'></div>
How do I get the php arrays back to the home page into the javascript? Should I place the JavaScript somewhere else?
The thing is, I have gotten all of this to run on separate pages when I didnt try to pass the runners names through. If I explicitly stated the runners names on the getRunners.php page, everything works great. I can not get the the php variables to insert into the JavaScript to generate the charts.
I've tried to assign the js code to a php variable in the getRunners.php page then echo the variable on the home.php page which didnt work.
It seems, once the home page is loaded, the JS remains the same. How do I pass through the PHP variables after the drop down options have been selected, allowing the chart to be displayed only after the button is clicked?
Thank you. I hope this is more clear than my previous question.
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);
I am using the following code to get a list of members and their information using ajax, jquery, php, json.
The only problem is when i use .html , it only displays the first record, it doesn't display all of the records. Totally confused.
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function(){
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url:'http://www.l.example.com/app/scrip/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
$.each(data, function(key, val) {
var friend = val['friend'];
var phone = val['phone'];
var status = val['status'];
var email = val['email'];
var updated = val['updated'];
$('#member_friends').append("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
});
}
});
}, 1500);
});
</script>
I tried this, and it didn't work:
<script type="text/javascript">
$( document ).delegate("#member_home", "pagecreate", function() {
var refreshId = setInterval(function() {
var friends= new Array();
$.ajaxSetup({cache: false})
$.ajax({
url: 'http://www.l.example.com/pp/scripts/friends_lookup.php',
data: "",
dataType: 'json',
success: function(data){
var output = [];
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
$('#member_friends').html("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
}
}
});
}, 1500);
});
</script>
You are over-writing the values each iteration of your $.each loop. Before the loop, create an array to store the data, then add to the array each iteration:
$.ajax({
success : function (data) {
var output = [];
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
}
//you now have an array of objects that each contain a set of information
}
});
The for loop I used is quite fast, here's a JSPerf to show the performance increase over using $.each(): http://jsperf.com/jquery-each-vs-for-loops/2
Also you may have noticed that I used output[output.length] = ... instead of output.push(...). The former performs faster in old browsers (the latter performs faster in modern browsers), I tend to try to help the old browsers out since they really need the help.
I guess your problem is that when you use .html() within a loop, for every iteration, it will replace all content added with the .html() during the previous iteration. Logically that would however leave you with only the last record, not the first.
You have to call .html() after the loop, currently it will replace the contents of #member_friends
in every loop iteration, so you will always see the last item.
This should be the workaround:
var output = [];
var html = []
for (var i = 0, len = data.length; i < len; i++) {
output[output.length] = {
friend : data[i].friend,
phone : data[i].phone,
status : data[i].status,
email : data[i].email,
updated : data[i].updated
};
html.push("<div class='member-box'>"+friend+"<span class='status-pic1'><img src='images/"+status+".png' width='40' height='40'/></span><span class='phone_box'><a href='tel:"+phone+"'><img src='images/icons/phone.png' width='40' height='40' /></a></span><span class='email-box'><a href='mailto:"+email+"'><img src='images/mail.png' width='40' height='40' /></a></span><div class='clear'></div><span class='update-status'><i>last update: "+updated+"</i></span>");
}//end of for
$('#member_friends').html(html.join(''));
I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false¢er=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function