Get Gravatar Img from JSON - javascript

I'm trying to parse data that will display a users Gravatar image. The JSON is the following : http://api.bfhstats.com/api/playerInfo?plat=pc&name=stewartps&output=js On line 34 is 'uGava' which is their gravatar URL. It should be then http://gravatar.com / + uGava
At the moment I have a form which asks for the user to input a name and select a platform.
This is the code I have for that:
$("#playerstuff").submit(function() {
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
//datatype : "json",
success: function(data)
{
document.getElementById("playerrank").innerHTML = '<img src="http://gamingstats.ga/' +data["player"]["rank"].imgLarge + '" />';
$("#formpanel").hide();
$("#dataret").show();
$("#playerimg").show();
}
});
return false;
});
I also just have a standard Image
<div class="user-img-div" id="playerimg" style="display: none;" >
<center><img src="img.png" class="img-circle"></center>
</div>
So my question is how will i use that standard Image to display the users Gravatar from the JSON data?

The data you get is plain JS, not JSON. Also, you don't need to use the bracket notation when the object properties don't have special characters in them. Change your AJAX call to the following:
$("#playerstuff").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
// script data type
datatype: "script",
success: function(){
var data = window.pd;
$("#playerrank").html('<img src="http://gamingstats.ga/' +data.player.rank.imgLarge+'"/>');
$("#formpanel").hide();
$("#dataret").show();
// Use Gravatar as user image
$("#playerimg").attr('src', 'http://gravatar.com/'+data.player.uGava).show();
}
});
});
Alternatively, since their API does support JSON, you can change the output GET parameter and use this instead:
$("#playerstuff").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?output=json&plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
// script data type
datatype: "json",
success: function(data){
$("#playerrank").html('<img src="http://gamingstats.ga/' +data.player.rank.imgLarge+'"/>');
$("#formpanel").hide();
$("#dataret").show();
// Use Gravatar as user image
$("#playerimg").attr('src', 'http://gravatar.com/'+data.player.uGava).show();
}
});
});

Related

Leaflet setView by ajax (cityname or postalCode)

We are trying to switch to Leaflet from gmaps.
SEtting up the map worked fine, markers for all our stores work, too.
I used leaflet-search for this build-in solution for searching for cities.
But it is working on keyPress or sth like that.
We want to have an input with a separate button for submitting.
Earlier, we just used an ajax, with a certain url from gmaps, and appended the searchvalue.
But with Leaflet I just cannot make it ...
It looked like this:
function geocode(key)
{
var address = key.replace(/ /g, '+');
var url = 'https://maps.googleapis.com/maps/api/geocode/json';
url += "?key=" + SitePreferences.GOOGLE_MAP_API_KEY;
$.ajax({
url : url,
data : {address:address},
dataType: "json",
success : function (json)
{
setGeocode(json);
},
error: function()
{
console.log("Google map API geocode error");
}
});}
How do I do that with leaflet ?
I tried sth like that without success though:
var url = 'https://nominatim.openstreetmap.org/search?format=json&q={address}';
$.ajax(
{
url:url,
dataType: "json",
success: function(data)
{
console.log(data),
}
});
Your code was fine, it had a syntax error, i also sent the params using data instead of directly from the url
$('#find').click(function(){
var url = 'https://nominatim.openstreetmap.org/search';
$.ajax(
{
url: url,
dataType: "json",
data:{
format:'json',
q: '{' + $("#address").val() + '}'
},
success: function(data)
{
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="address" />
<button id="find">find address</button>

Create PDF with Ajax

I am using FPDF to create my report.
$pdf = new Report('P','mm','A4', $_POST);
$pdf->AddPage();
$pdf->Output('file.pdf','I');
And I use ajax to make requisition to the PHP.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
window.open(data);
})
I want to show the report in a new tab
I think you should success key. So it would be something like this
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id },
success: function(data){
var blob = new Blob([data]);
window.open(URL.createObjectURL(blob));
}
})
Resolved:
I did the different way:
In my report PHP, I generate one temporay file, passing the parameter 'F'.
$pdf->Output('file.pdf','F');
In Jquery Ajax I opne the file, rather than open the data retorned of ajax request.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
var fileName = "file.pdf";
$('#modalRel').modal('show');
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from here";
object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "../Files/" + fileName);
$("#body-rel").html(object);
})
I hope to have helped who one day to need.

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

jquery $.ajax automatically evaluates javascript file

I have a file list, when the user double clicks a file, it is displayed in an editor,
The problem is, after opening a javascript file, all bootstrap functions get undefined.
UPDATE:
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
After calling this function, bootstrap functions get undefined. I'm calling it from the console, not via events now.
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
dataType: "text", // THIS LINE SOLVED IT!
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
From the jquery documentation:
dataType: (default: Intelligent? Guess (xml, json, script, or html)) Type: String.
The type of data that you're expecting back from the server.
"script" (this was getting selected by default): Evaluates the response as JavaScript and returns it as plain text.

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

Categories

Resources