I am using an Ajax call to PHP to return a string of dates that a user is available, To make it dynamic.
I am returning the string back to my jQuery as :
['7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013']
However when I initialise the datePicker, That string of dates does not load.
I am not too sure as to why, I suspect its my success function after my Ajax call.
My jQuery code looks like this :
$('.vendor_id').change(function()
{
var vendor_id = $('option:selected', this).attr('title');
var url = "/admin/po/get_user_dates/" + vendor_id;
$.ajax({
type : "POST",
url : url,
success: function(unavaildates)
{
var disabledDays = unavaildates;
function disableAllTheseDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1) {
return [false];
}
}
return [true];
}
$('.booking-date').datepicker(
{
beforeShowDay: disableAllTheseDays,
numberOfMonths: 2,
dateFormat: 'DD, d MM, yy',
showButtonPanel: true
}
)
}
})
})
Hope someone call help me on this.
Quick Update.. On assigning disabledDays to ['7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'] the datePicker works...?
Thanks in advance.
Because you are retrieving a string and not an array from the server.
I would suggest to return the string without square brakets "'7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'" from the server and create the array like this :
var unavaildates = "'7-15-2013','7-16-2013','7-17-2013','7-18-2013','7-19-2013','7-20-2013','7-21-2013','7-22-2013'"
var disabledDays = unavaildates.split(',');
Related
I have 2 CGridView calling each other on beforeAjaxUpdate. How can I prevent the recursion? I only want it to call the other one once?
jobs-grid
'beforeAjaxUpdate' =>'function(id,options){
var x = getQueryParams(options.url);
var data = "sort="+x.Jobs_sort + "&ajax=detailsgeoscan-grid";
$.fn.yiiGridView.update("detailsgeoscan-grid",{data:"sort="+x.Jobs_sort});
}',
detailsgeoscan-grid
'beforeAjaxUpdate' =>'function(id,options){
var x = getQueryParams(options.url);
var data = "Jobs_sort="+x.Jobs_sort + "&ajax=jobs-grid";
$.fn.yiiGridView.update("jobs-grid",{data:"sort="+x.Jobs_sort});
}',
I think you can do this with an optional parameter isNotFirst:
jobs-grid
'beforeAjaxUpdate' =>'function(id,options,isNotFirst){
var x = getQueryParams(options.url);
var data = "sort="+x.Jobs_sort + "&ajax=detailsgeoscan-grid";
if(typeof isNotFirst === "undefined"){
$.fn.yiiGridView.update("detailsgeoscan-grid",{data:"sort="+x.Jobs_sort}, true);
}
}'
detailsgeoscan-grid
'beforeAjaxUpdate' =>'function(id,options,isNotFirst){
var x = getQueryParams(options.url);
var data = "Jobs_sort="+x.Jobs_sort + "&ajax=jobs-grid";
if(typeof isNotFirst === "undefined"){
$.fn.yiiGridView.update("jobs-grid",{data:"sort="+x.Jobs_sort},true);
}
}',
If isNotFirst is undefined, the function is called by yii, so you can call the function of the other grid with isNotFirst set to true.
I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};
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);
}
);
}
I need to update the disabled dates of a UI Jquery datepicker when a different city is chosen from a combo box, so what iv done is onchange of the combo box run the following function which does an ajax call to a php script which hits the DB via sql and returns the dates based on the city whcih i dump into the unavalibledates variable and rerun the .datepicker
This only works the first time its run, after which is does not update, but does not error. how do I make it update.
function update_datepicker()
{
$.ajax({
type: "POST",
url: "scripts/deals.php?val=05&city="+document.getElementById('city_combo').value,
success: function (temp2)
{
var unavailableDates = [eval(temp2)];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false,"","Unavailable"];
}
}
$('#datepicker').datepicker({ beforeShowDay: unavailable });
}
});
}
do not create every time a new datepicker, just update your current
var unavailableDates;
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false,"","Unavailable"];
}
}
var dp = $('#datepicker').datepicker({ beforeShowDay: unavailable });
function update_datepicker()
{
$.ajax({
type: "POST",url: "scripts/deals.php?val=05&city="+$('#city_combo').val(),
success: function (temp2)
{unavailableDates = [eval(temp2)];}
});
}
just add,
$('#datepicker').datepicker( "destroy" );
Before you recreate it, hope this helps otehrs
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