I have fetched values From my MySQL Database and stored it in JSON Format. Now What I am trying to do is that I need to show those values on the JvectorMap.
but I am not able to do it.
Here is my PHP code :
$json_data=array();
foreach($result as $rec)
{
$json_array['Country']=$rec['user_country'];
$json_array['CountryCode']=$rec['country_code'];
$json_array['persons']=$rec['usercountry'];
array_push($json_data,$json_array);
} echo json_encode($json_data) ;
The JSON That I am recieving is :
[
{"Country":"Australia","CountryCode":"AU","persons":"5"},
{"Country":"Spain","CountryCode":"ES","persons":"2"},
{"Country":"India","CountryCode":"IN","persons":"8"},
{"Country":"Mexico","CountryCode":"MX","persons":"4"},
{"Country":"United States","CountryCode":"US","persons":"4"}
]
The Script that I am using is :
<script type="text/javascript">
var dataC = '<?php echo $data ; ?>' ;
var countryData = {};
$.each(dataC, function() {
countryData[this.CountryCode] = this.persons;
});
$(function() {
$('#world-map').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
values: countryData, //load the data
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'}]
},
//-----------------------------------------------
// changed to onRegionLabelShow from onLabelShow
//-----------------------------------------------
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country =$.grep(dataC, function(obj, index) {
return obj.CountryCode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() +
"<br/><b>Code: </b>" +country.CountryCode +
"<br/><b>Name: </b>" + country.Country +
"<br/><b>persons: </b>" + country.persons);
}
}
});
});
</script>
But I am getting the error :
" jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"Country":"Australia","CountryCode":"AU","persons":"5"},{"Country":"Spain","CountryCode":"ES","persons":"2"},{"Country":"India","CountryCode":"IN","persons":"8"},{"Country":"Mexico","CountryCode":"MX","persons":"4"},{"Country":"United States","CountryCode":"US","persons":"4"}] "
Related
When I execute a php file it give me this result:
[{"title":{"0":"Offer Number 1"},"link":{"0":"https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn"}}]
the offer title is .$offeritem->title. and the URL is .$offeritem->link.
I want to make a php file that show like this result of an offer and its url.
And then I want to call them (offer title + url) via javascript using this code:
openVerification: function() {
var e = this;
jQuery.getJSON("functions/offers.php", function(t) {
if (!t.error) {
var n = "";
$.each(t, function(e, t) {
n += '\n <li class="list-group-item"><a target="_blank" href="' + offerlink[0] + '">' + title[0] + "</a></li>\n
}), i.hideAll(), i.dialog({
message: '\n <ul class="list-group">\n ' + n + '\n </ul>\n ',
title: "offers",
closeButton: !1,
buttons: {
cancel: {
label: "Cancelar",
className: "btn-default",
callback: function() {
e.resetGenerator()
}
}
}
})
}
})
},
so in short I want to make the offers.php file.
Your JSON OP is not efficient
[
{
"title":{"0":"Offer Number 1"},
"link":{"0":"https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn"}
}
]
According to me it should be
[
{"title"::"Offer Number 1","link":"https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn"},
{"title"::"Offer Number 1","link":"https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn"}
]
I am writting PHP code for both JSON OP:-
For 1st One:-
$offer[0]['title'][0] = "Offer Number 1";
$offer[0]['link'][0] = "https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn";
$offer[1]['title'][0] = "Offer Number 2";
$offer[1]['link'][0] = "https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn";
echo json_encode($offer);
For 2nd One:-
$offer[0]['title'] = "Offer Number 1";
$offer[0]['link'] = "https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn";
$offer[1]['title'] = "Offer Number 2";
$offer[1]['link'] = "https:\/\/www.domain.com\/show.php?l=0&u=8793&id=6335&tracking_id=mnn";
echo json_encode($offer);
your offers.php code should be somthing like-
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
Then your JavaScript (in this example I use jQuery):
$.getJSON('http://localhost/yourProject/offers.php', function(data) {
console.log(data);
});
This should be a start to get PHP arrays in to your JavaScript.and your access that with index of data.
I want to send an array generated in jQuery to a php file. I get stuck on this. I tried several way but no luck. I want to echo/print_r the array in php file. Experts give me your kind look. My code is given below :
js:
<script>
jQuery(document).ready(function($){
url = '<?php echo includes_url().'cs_cause.php'; ?>';
var allVals = [];
$('#deleteProduct').click(function(){
$('.delete-product:checked').each(function() {
allVals.push($(this).val());
});
$.post(url,{ array : allVals }, function(response,status){
alert( response+ ' ' + status);
});
})
})
</script>
php :
<?php
if($_POST['array'])
{
$r = $_POST["array"];
print_r($r);
}
?>
Try something like this mate.
<script>
jQuery(document).ready(function($){
url = "http://localhost/fundraise/wp-content/themes/aidreform/include/cs_cause.php";
var allVals = [];
$('#deleteProduct').click(function(){
$('.delete-product:checked').each(function() {
allVals.push($(this).val());
});
$.post(url,{ array : allVals }, function(response,status){
alert( response+ ' ' + status);
});
})
})
</script>
Incase u move this file to the server change the url to
url = "/wp-content/themes/aidreform/include/cs_cause.php";
I'm trying to show data from visitors inside a map created using jvectormap plugin.
This is driving me crazy, i can not load the data through ajax, if i put the data manually it works.
So far i have this:
map.php
$datos = array();
$link->set_charset("utf8");
$sql = $link->query("SELECT SUM(ID) as visitors, state FROM visitors WHERE state != '' GROUP BY state");
while($row = $sql->fetch_row()){
$ss = $link->query("SELECT * FROM states WHERE state = '".$row[1]."'");
$rr = $ss->fetch_row();
$datos[] = array("ccode" => $rr[2], "visits" => $row[0]);
}
$data = array("countries" => $datos);
echo json_encode($data,JSON_NUMERIC_CHECK);
This returns the following data:
{"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]}
Now the function to load the map:
function cargaMapa(){
//jvectormap data
$.post("ajax/map.php",{},function(mapa){
var dataC = eval(mapa);
//var dataC = {"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]};
var countryData = [];
//for each country, set the code and value
$.each(dataC.countries, function() {
countryData[this.ccode] = this.visits;
console.log("Estado: "+this.ccode+" Visitas: "+this.visits);
});
//World map by jvectormap
$('#world-map').vectorMap({
map: 've_mill_en',
backgroundColor: "#fff",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: countryData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country = $.grep(dataC.countries, function(obj, index) {
return obj.ccode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() + ': ' + country.ccode + country.visits + ' visitas');
}
}
});
});
}
As you can see in the function i have the var dataC, if i load in there the array coming from map.php it gives me Uncaught SyntaxError: Unexpected token : but if copy and paste the result of map.php into the var dataC it works pretty good.
How can i solve this?
I appreciate any help
Thanks
I figured it out, just changed $.post for $.getJSON and the magic began
Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected
I'm just starting to learn Handlebars.js, I used the Handlebars.js site (http://handlebarsjs.com/expressions.html) to help write this following snippet here:
http://jsfiddle.net/3TxVx/2/
var story = {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
};
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString(
"<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(story);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
Not sure why I get the following error when I run it:
Uncaught TypeError: Cannot read property 'url' of undefined
Thanks!
Try replacing
registerHelper('link', function(object)
with
registerHelper('link', function(text, url)
From the docs:
Handlebars.registerHelper('link', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '' + text + '';
return new Handlebars.SafeString(result);
});
http://handlebarsjs.com/
Turns out Handlebars is very picky on the format of the data or context. I made the the following change to the story object and it worked.
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
So now my entire code looks like this:
<script id="header" type="text/x-handlebars-template">
{{{link story}}}
</script>
<script type="text/javascript">
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString("<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(data);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
</script>