How can i load markers using an ajax call - codeigniter

i saw an example on how to load markers dynamically on this page
https://developers.google.com/maps/articles/phpsqlsearch_v3
and i saw another code igniter Google-maps api from BIOSTALL.
but this(http://biostall.com/codeigniter-google-maps-v3-api-library) library doesn't load the markers dynamically how can i achieve that using the library it self.
should i try to fetch the markers on map init or does the library provide a way to load these markers using ajax

Firstly, thanks for using my library. It's worth noting that the library is merely a way to simplify the generation of the Google Maps code. It constructs the JavaScript and HTML on your behalf making it quick and easy to add maps to your page.
There are a million and one ways that a developer might want to interact with the Google Maps API and it's impossible for the library to cater for every single instance. As a result, there are times where, in a bespoke situation like this, you may need to add your own code so it performs as you require.
As a result, might I suggest you simply add in the custom JS you require after you do echo $map['js']. There is a function available that comes with the library called createMarker() which, if you view the source code, you will see.
In pseudocode this will look like so:
<?php echo $map['js']; ?>
<script type="text/javascript">
// Get marker(s) with ajax
// Call createMarker() function to add marker(s) to map
</script>
I hope that helps somewhat.

Trying the pseudocode suggested by Biostall, this is what i have implemented:
$.ajax({
url: '*URL*',
type: "POST",
data: ({value : *value*}),
dataType: "json", //retrieved Markers Lat/lng in Json, thus using this dataType
success: function(data){
//Removing already Added Markers//////////
for(var i=0; i < markers.length; i++){
markers[i].setMap(null);
}
markers = new Array();
//////////////////////////////////////////
// Adding New Markers////////////////////
for (var i = 0, len = data.length; i < len; ++i) { // Iterating the Json Array
var d = data[i];
var lat = parseFloat(d.lattitude);
var lng = parseFloat(d.longitude);
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = {
map:map,
position:myLatlng // These are the minimal Options, you can add others too
};
createMarker(marker);
}
}
}
);
Note: If an array of Markers is being sent to this ajax call, it must be json encoded with the php function json_encode(). And thus you can use the dataType: "json" as mentioned in the ajax call parameters.
This worked for me, hope this might help.

Related

How to 'POST' a image through xhttp?

I´m trying to do this:
var http = new XMLHttpRequest();
var url = "guardarImg.php";
var params = $('#form').serialize();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "multipart/form-data");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
But is not working, it shows me in my php that 'Image' is not defined, but when I do it through a average Submit it works fine.
All the similar samples I saw work with string data but I need to achieve it with images to make it work later in Intel XDK
What I´m doing wrong?
Can you show me a sample?
Sorry if my question is too basic, I´m a noob with xmlhttp and ajax stuff.
You have the right idea with regard to $("#form").serialize() but for the mess that is (still) AJAX uploads. Yuck (and shame on me for not noting that detail the first time :-( ).
The problem with file uploads via AJAX is (as is often the case), Internet Explorer. Basically, it didn't support the FormData object until IE10 (which means that, if you care about supporting XP users, they'd better be running not-IE). FormData greatly simplifies the process of uploading stuff via AJAX; if you don't have that, here are your options:
Put a little tiny IFRAME on the page and manage that for the actual file upload.
Encode the form data programmatically using something like JSON and send that via jQuery.
Use a nice plugin that wraps this all for you (and uses one or more of these techniques under the covers).
I'm going to assume you don't care about IE8/9 (pretty much everyone else isn't a problem) and give you a FormData solution. Unlike the previous edit, I'm popping in the whole function in here since it's decently informative. This particular solution uploads an entire form, pulling in the existing fields into the FormData object and treating the files specially.
<!-- Many ways to skin this particular feline; I like this one :-) -->
<form onsubmit="return uploadFiles(this)">
<!-- Access from PHP using $_FILES["somefile"]["name"][$idx]... -->
<input type="file" name="somefiles" multiple="1" />
</form>
<script>
// Function to upload a form via FormData, breaking out files and cutting
// any non-named elements. Assumes that there's a #status DIV and the
// URL is hardcoded.
function uploadFiles(frm) {
var formdata = new FormData();
// I'm doing this to separate out the upload content. Note that multiple
// files can be uploaded and will appear as a decently-friendly PHP array
// in $_FILES. Note also that this does handle multiple files properly
// (a default FormData(frm) wouldn't exactly :-( ).
$(frm).find(":input").each(function(idx, ele) {
// This is a file field. Break it out.
if(ele.files) {
for(i=0; i<ele.files.length; i++) {
formdata.append(ele.name + "[" + i + "]", ele.files[i]);
}
// Not a file element, so put in the upload iff there's a name.
} else if(ele.name) {
formdata.append(ele.name, ele.value);
}
});
// Run the AJAX.
$.ajax({
url: "test.php", // Change Me :-)
type: "POST",
data: formdata,
processData: false, // Need these to keep jQuery from messing up your form
contentType: false,
success: function(data) {
$("#status").html(data);
},
error: function(xhr, status, error) {
$("#status").html("Error uploading file(s): " + error);
},
});
return false; // Keep the form from submitting
}
</script>
I have a complete HTML file and corresponding PHP that work at pastebin.
If I were you, I'd actually just use Sebastian's jQuery File Upload if you can. It's got all that modern UI goodness (include progress metering), browser abstraction, and it's MIT licensed to boot. That said, this answer will get you on your way if you just need something to copypasta. Good luck!

How to query cosm json feed using the cosm javascript library

I am new to web development and I have bit off more than I can chew.
So far, I successfully have created a website to query the latest data at cosm.com
Now I am trying to save the last 10 data points from the cosm.com feed to an array using the cosm javascript library. I can't get the right syntax and I can't find examples to guide me.
cosm.feed.history( 12068, duration:'30seconds', callback(data) );
console.log(data);
http://jsfiddle.net/spuder/29cFT/12/
http://cosm.github.com/cosm-js/docs/
UPDATE 2013-4-14
After implementing #bjpirt's solution, I noticed I wasn't getting 'every' value returned inside the specified duration.
Solved it by adding "interval:0" to the request.
cosm.datastream.history( cosmFeed1, cosmDataStream1, {duration:'60seconds', interval:0}, getHistory );
http://jsfiddle.net/spuder/ft2MJ/1/
#lebreeze is correct with his advice. I got your JSFiddle working so that it is now fetching data from the Cosm API:
http://jsfiddle.net/nLt33/2/
I had to make a few changes to get it working, any of which would have been causing you errors:
The feed ID and datastream ID were incorrect
You didn't have a callback function
The options weren't in a javascript object
Also, that feed doesn't seem to have been updated recently.
Here's the updated code which seems to be working fine now:
//read only key
cosm.setKey("-Ux_JTwgP-8pje981acMa5811-mSAKxpR3VRUHRFQ3RBUT0g");
var cosmFeed = 120687;
var cosmDataStream = "sensor_reading";
$(document).ready( function() {
var success = function(data){
for(var datapoint in data.datapoints){
var dp = data.datapoints[datapoint];
$('#stuff').append('<li>Value: ' + dp.value + ' At: ' + dp.at + '</li>');
}
}
//Print out the last 10 readings or so
cosm.datastream.history( cosmFeed, cosmDataStream, {duration:'1day'}, success );
})
It's difficult to get just the last x datapoints (that's something we should change in the API I think) - what you'd normally do is ask for a specific time period.
Hope this helps.
You may need to wrap your duration:'30seconds' json options in {}
Try something like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://d23cj0cdvyoxg0.cloudfront.net/cosmjs-1.0.0.min.js"></script>
<script>..
cosm.setKey( "APIKEY" );
cosm.feed.history(40360, {duration:'30seconds'}, function(data){
console.log(data);
console.log(data.datastreams);
});
</script>

How do i automatically append column names to post data sent to php when grid loads or refreshes?

I'm new to jqGrid and jquery and i'm learning as fast as i can but i still am a little lost about how to some things like how to append addition information to the post data in jqgrid that gets sent to php.
It would be nice for the php script to know what columns the grid wants when it initially loads or you press the jqgrid refresh/reload button.
I know i can use the postData option: postData:{name:val,,,}, but i was hoping to just automatically pull the column names from the colModel definitions using this function...
postData: function(){
colmodel = $('#tab4-grid').jqGrid('getGridParam','colModel');
colarray = '{';
for (var i in colmodel) {colarray += '"'+colmodel[i].name+'":"'+colmodel[i].name+'",';}
colarray += '}';
return colarray;
},
so i would not have to spell them out manually again. However, while the function produces the correct code, it's not getting posted. I can't seem to figure out the problem. Can someone help please?
thanks.
The first thing which you have to do is to rewrite
postData: function() { ... }
to
postData: {
myColumnsName: function() { ... }
}
jqGrid already send some standard parameters to the server (page, rows ,...). With the code above you will add and additional parameter with the name myColumnsName which you can fill in any way inside of the function body.
You current implementation is very dirty. You don't define local variables colmodel and colarray. Moreover you try to serialize array of strings as object ('{}') and not as array ('[]'). You should not use for (var i in colmodel) construction if you enumerate array items for (var i=0; i<colmodel.length; i++) is better. Additionally 'colModel' contain some column names ('rn', 'cb', 'subgrid') which you should skip in the enumeration. You can define as var colNames = []; and use colNames.push to fill it. Then you can use standard JSON.stringify method from json2.js to convert array to the JSON string.

HTML data from multiple ajax requests to javascript array

I'm trying to pre-load some html content using AJAX and jQuery. The AJAX callback function adds the data to an associative array. I'm fine if I do each request individually:
var contentArray = new Object();
var urlA = "includes/contentA.php";
var urlB = "includes/contentB.php";
var urlC = "includes/contentC.php";
$.get(urlA, function(htmlA) {
contentArray["A"] = htmlA;
});
$.get(urlB, function(htmlB) {
contentArray["B"] = htmlB;
});
$.get(urlC, function(htmlC) {
contentArray["C"] = htmlC;
});
Since I am likely to have a few of these (more than three), I tried to do it a for loop:
var contentArray = new Object();
var pages = new Object();
pages["A"] = "includes/contentA.php";
pages["B"] = "includes/contentB.php";
pages["C"] = "includes/contentC.php";
for (var key in pages) {
var URL = pages[key];
$.get(URL, function(html) {
contentArray[key] = html;
});
}
However, this doesn't work. contentArray only has one property containing html data, rather than three. I'm knew to jQuery, particularly the AJAX stuff, so both explanations and solutions (similar or different-method-same-result) are welome.
By the way, I'm aware that one larger AJAX request is preferable to multiple small ones, but I'm trying to retain compatibility for users without JS enabled, and the current php includes are convenient. Any suggestions as how I might satisfy both these requirements are also very welcome.
Thanks.
The callback function for an AJAX request doesn't run until the request returns. In your case each callback function will use key as it exists in the current context, and since there's no key variable in it's local scope it will use the nearest it can find, the key in your for loop.
The problem is by the time the AJAX requests return, the for loop has been fully iterated over and key is equal to the last key in the array. Thus each of the callback functions will receive the same key, overwriting the previous value in your contentArray.
If you're using jQuery 1.5.1 or above a quick and dirty solution (one that doesn't involve changing the current structure of your PHP files) might be to try the following:
for (var key in pages) {
var URL = pages[key];
$.ajax({
url: URL,
xhrFields: {
'customData': key
},
success: function(html, statusText, jqXHR) {
contentArray[jqXHR.customData] = html;
}
});
}
I haven't tested that but according to the documentation page it should work. All you're doing is using the request object created by jQuery to pass your variable along to the callback function.
Hope that helps

MVC: Set value in autocomplete on Edit

In our MVC application we use jQuery autocomplete control on several pages. This works fine on Create, but I can't make it work on Edit.
Effectively, I don't know how to make the autocomplete controls preload the data from model and still behave as an autocomplete in case the user wants to change the value.
Also how can I make sure that the value is displayed in the same format that is used in Create calls?
All our autocomplete controls have corresponding controllers and all parse Json results.
Let's Try this! Alright Do this:
Suppose you had a list of countries you needed to filter
Auto Complete knows how to some default things by default but suppose you really wanted CountryName and also you know every keypress does an ajax call to the URL you specify.
Create an action method like so:
public ActionResult LookupCountry(string q, int limit)
{
var list = GetListOfCountries(q, 0, limit);
var data = from s in list select new {s.CountryName};
return Json(data);
}
Here is the Jquery:
$(document).ready( function() {
$('#txtCountryName').autocomplete('<%=Url.Action("LookupCountry", "MyController") %>', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].CountryName, result:data[i].CountryName};
}
return rows;
},
formatItem: function(row, i, n) {
return row.CountryName;
},
width: 300,
mustMatch: true,
});
});
Here is the Html
<html><head></head><body>#Html.TextBox("txtCountryName",Model.CountryName)</body></html>
Basically, The magic is in the call to LookUpCountry
The GetCountriesList(string query, int startindex, int limit)
Returns MyCountries.Where(c => c.CountryName.SubString(startindex, limit).Contains(query)).ToList();
So you are making your own trimming function because JQuery has no idea what CountryName is or how to trim it. How ever if it was a javascript object I am not quite sure but do
var jsonString = #Html.GetListOfCountries() //Or Model.Countries.ToJSONString()
var json = JSON.stringify(jsonString); //also JSON.Parse(jsonString) if stringify won't work
which would return the necessary countries as a Html Helper Extension method. And perhaps as a list of javascript objects it would be smart enough to handle it that way in it's native language. However the first approach works for me.

Resources