JSON VALUE AS QUERY STRING - javascript

I'm using Maxmind.Com's GeoIP2 (Omni) Webservice on my Drupal 7 website to pull geographic data based on my visitor's IP.
I am able to get a JSON document by using this code:
<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.0/geoip2.js">
</script>
<script type="text/javascript">
var onSuccess = function(location){
console.log(
"Lookup successful:\n\n"
+ JSON.stringify(location.city.names.en, undefined, 4)
);
};
var onError = function(error){
alert(
"Error:\n\n"
+ JSON.stringify(error, undefined, 4)
);
};
geoip2.omni(onSuccess, onError);
</script>
One of the returned values is the visitor's city name. How can I use the returned value as part of a query string?
For example, if 'city.names.en' = 'Detroit', how could I use "Detroit" as a key to retrieve data (e.g. Local phone number) from another document, table, etc?
The end goal is to dynamically insert a "local" phone number into the "contact us" section based on the visitor's location.

Typically you'll format a query string like this:
http://mydomain.com/route?parameterName=value
For your example it may look like this:
http://mydomain.com/phoneNumbers/phoneNumber?city=Detroit

There can be two approach to achieve what you want to do.
Load the contact information after getting the city name using ajax. Here's an example:
<span id="contact"></span>
<script type="text/javascript">
$(document).ready(function() {
geoip2.omni(function(data) {
$.ajax({
type: "GET",
url: "your/url/to/contact/getter/service",
data: {
city : data.city.names.en
},
success: function(contact) {
// update your contact information
$("#contact").text(contact);
}
}
}, function(data) {
debugger;
});
});
</script>
Obviously, you need a resource that you can request to provide the contact information given the city name.
Create a contact information map and use it to get the contact information for a City without having to send a request again.
<span id="contact"></span>
<script type="text/javascript">
var contactMap = {
NewYork : "123123",
London : "9797987"
}
$(document).ready(function() {
geoip2.omni(function(data) {
// update your contact information
$("#contact").text(contactMap[data.city.names.en]);
}, function(data) {
debugger;
});
});
</script>

Related

Javascript function (with variable information in URL) for a simple GET request

The situation is as follows:
A webpage with two inputs; input_1 and input_2
input_1 is a code to be entered by the user
input_2 is more like a token string, pre-filled or to be filled by user
The URL format for the GET request is like this: https://www.apiserver.com/api/v1/static_param_1/input_1/tokens/redeem?token=input_2
The webpage has a form, which includes a button with an element_id of button_1, two text elements with element id's elem_input_1 and elem_input_2.
I need to use javascript to create the GET request which gets fired when the user has input the values and clicked the button.
I tried the following so far. Any help is highly appreciated:
var button = document.getElementById('button_1');
function executeGetReq() {
var input_1 = document.getElementById('elem_input_1').value;
var input_2 = document.getElementById('elem_input_2').value;
var url = "https://www.apiserver.com/api/v1/static_param_1/" + input_1 + "/tokens/redeem"
var data = {
token: input_2,
};
$.get(url, data, function (result) {
if (result == 'ok')
alert('Success!');
else
alert('Failure');
});
}
button.onclick = executeGetReq;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="elem_input_1" value="input_1"/>
<input id="elem_input_2" value="input_2"/>
<button id="button_1">Go</button>
EDIT:
Well, it seems the problem is with CORS. Still digging.
Try to set the dataType to jsonp (But before set it to json).
$.get(url, data, function (result) {
//...
}, 'jsonp');
If it doesn't work search for ajax cors on the web.
Or take a look at https://www.codegrepper.com/code-examples/javascript/ajax+cors+error

Passing and retrieving multiple parameters

I can best explain my problem by showing the code first. I am working on a project with my friend (Rent a car project), so the code isn't completely mine. I searched (and used) some of the answers i found on similar questions, but none solved my problem. All of the pages here will be used by administrator.
1st
client_requests.php
This page contains javascript function called sureToApprove with which i have a problem : in the url the car variable is undefined (&car=undefined), while id has a value (it works). Also, this page contains some of the data from database.
<script type="text/javascript">
function sureToApprove(id, car) {
if (confirm("Da li ste sigurni?")) {
window.location.href = "approve.php?id=" + id + "&car=" + car;
}
}
function deleteRequest(id){
if (confirm("Da li ste sigurni?")) {
window.location.href = 'delete_request.php?id=' + id;
}
}
</script>
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "fetch_requests.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
2nd page is fetch_requests.php which contains a query which will be shown on 1st page (client_requests.php). Query and the rest of the code works perfectly.
<tr>
<td>'.$row["fname"].'</td>
<td>'.$row["lname"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["phone"].'</td>
<td>'.$row["car_name"].'</td>
<td>'.$row["mpesa"].'</td>
<td>'.$row["status"].'</td>
<td>
IzbriĆĄi
Approve
</td>
</tr>
When the link approve is clicked, it redirects to 3rd page (approve.php) in which the data in database is regulated. The url looks something like this
http://localhost/Rent-a-car/admin/approve.php?id=7&car=undefined
I need the car variable for regulating the database, and i can't find out why it is not picking up the value instead is undefined. Thank you in advance.

Pass multiple objects from servlet to Javascript file using ajax call

In my login servlet page have some conditions.The user is registered user pass URL to JavaScript using ajax call. If the user is not registered then try to login i need to display error message and redirect to same page URL but here i am unable to pass both URL and message at a time to JavaScript file using ajax call i am able to pass only one object either URL or message anyone please tell me how to pass both objects to JavaScript.
You can concatenate the Strings of URL and MSG and pass in out.println with a delimiter and then split the same at other end in JS.
if
{
data ="Login.jsp$Sorry, you are not a registered user! Please sign up
first";
}
PrintWriter out = response.getWriter();
out.print(data);
This happens Because print(arg) of Class PrintWriter that you referred by out only accepts one single argument. be it of any type. view API here. Assuming that you always get a success callback.
try should work:
code:
String resp= ""; // final response
if(User.isValid())
{
resp="MyList.jsp" ;
}
else
{
Url="Login.jsp";
Msg="Sorry, you are not a registered user! Please sign up first";
resp= Url + "#" + Msg;
}
PrintWriter out = response.getWriter();
out.print(resp); // based upon your condition above.
change your JS:
<script type="text/javascript">
$(document).ready(function() {
$('#btnLogin').click(function ()
{
$.ajax({
type: "post",
url: "Login", //this is my servlet
data: "uname=" +$('#inputUserID').val()+"&pwd="+$('#inputPassword').val(),
success: function(data){
alert(data);
var response = data.split("#");
if(response.length>1){
// if user is a valid user
$(window.location).attr('href', response[0]);
} else {
// if user in invalid
$(window.location).attr('href', response[0]);
$("#message").html(response[1]);
}
}
});
});
});
</script>

display ajax called data in an UI

i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});

Passing variables with jQuery

i'm relatively new to jquery and javascript and am trying to pass
a unique id (number) into a flickr search function (jquery.flickr-1.0-js) like so, (number is the variable where i'm storing the unique id)
<script type="text/javascript" src="javascripts/jquery.flickr-1.0.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery(".btnRefresh").click(function(){
var number = $(this).attr("id");
$('#gallery_flickr_'+number+'').show();
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15
});
});
});
</script>
When i try to pass it in to the flickr-1.0.js function like so (abbreviated)
(function($) {
$.fn.flickr = function(o){
var s = {
text: $('input#flickr_search_'+number+'').val(),
};
};
})(jQuery);
i get a error
number is not defined
[Break on this error] text: $('input#flickr_search_'+numbe...] for type=='search' free text search
please help, what do i need to do to pass the variable between the two scripts?
Thanks,
Try adjusting your scripts as below:
...
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15,
search_text: $('input#flickr_search_'+number+'').val()
});
...
(function($) {
$.fn.flickr = function(o){
var s = {
text: o.search_text
};
};
})(jQuery);
The idea is that you need to find the search text based on the id of the clicked item. You do that in the function where the id is available, then pass the value of the input to the flickr function with the other values in the hash argument. In the flickr function you extract the named item from the hash and use the value.
You can pass parameters in JQuery very easily; for example:
$.ajax({
type: "POST",
url: "/<%=domainMap%>/registration/recieptList.jsp",
data: "patientId=" + patientId+"golbalSearch="+golbalSearch,
success: function(response){
// we have the response
$('#loadPatientReciept').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
}
I just realized 'flicker' != 'flickr'
darn you cutesy web 2.0 names!!!
Thanks!

Categories