Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL:

http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br>

I am utilizing ajax jsonp for this task.
Below is the complete code snippet:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<Script>

var asciilast;
var asciiname="";
var lat="21.283300399780273";
var lng="72.9832992553711";
var radius="10000";

function getascii(){
  $.ajax({
    url: "http://services.gisgraphy.com/geoloc/search?lat="+lat+"&lng="+lng+"&radius="+radius+"&format=json",
    async: false,
    dataType:'jsonp',
    success: function(data1) {
      for(i=0;i<data1.result.length;i++) {
        asciiname = asciiname+data1.result[i].asciiName+",";
        console.log(asciiname);
        asciilast = asciiname.replace(/\,$/, '');
      }
      alert(asciilast);
    }
  });   
}
</Script>
<body onload="getascii()">
</body>

This code has been effective in providing the desired output.
However, there are instances when it encounters issues such as returning undefined if certain results do not have an asciiName.
To address this issue, I want to avoid obtaining undefined values when the result lacks an asciiName.

Answer №1

    cityName = '';
    cityLast = '';

    if(data1.result[i].cityName){
        cityName = cityName+data1.result[i].cityName+",";
        console.log(cityName);
        cityLast = cityName.replace(/\,$/, '');
    }

Answer №2

Make sure to verify if the value is undefined

var cityName = data1.result[i].asciiName || "";

or

var cityName = data1.result[i].asciiName;
if (cityName) {
   //carry out necessary tasks
}

Answer №3

Make sure to include the following condition:

If(jQuery.type(data1) === "undefined" || jQuery.type(data1.result[i])=== "undefined"){
    // Handle logic here
}

This code should be placed within the success method.

Answer №4

asciiname = asciiname + data1.result[i].asciiName+",";// this line

Set a default value:

asciiname += data1.result[i].asciiName ? data1.result[i].asciiName : "default";

If you prefer to avoid using any if statements:

asciiname += data1.result[i].asciiName || "default";

You can replace "default" with your desired text. I am utilizing a ternary condition here:

(condition) ? a : b; // similar to if(condition) {a} else {b};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js: implementing method overriding

I'm currently exploring the most effective method to override a function in a custom module using node.js. As part of my project, I am developing a custom middleware that will assist me in automatically loading various custom modules such as security ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Validation in ASP.Net to ensure the correct number of days between the arrival and departure dates

One of my project requirements involves checking the validation of the number of days entered between two date selectors (From & To Dates). The constraint is that the difference should not exceed 100 days. I'm considering using ASP.NET validators for ...

What is the best way to display a div after a form submission?

I recently added a contact form to my website and successfully set it up so that when the user clicks the contact button, the form pops out. However, instead of redirecting the user to a separate result page after submitting the form, I want a result div ...

Contrast between PHP and JavaScript output texts

Hey everyone, I'm dealing with a bit of an awkward situation here. I am trying to return a string variable from PHP to JavaScript and use it for a simple comparison in my code. However, the results are not turning out as expected. Initially, I send a ...

What is the reason behind combining all states into a single location in Redux, even if they are not globally accessible?

As a newcomer to React and Redux, I have found them to be quite enjoyable when used together in a small sandbox application. However, as I consider larger applications, I can't help but question why Redux stores the entire application state in a singl ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

The font size varies depending on the language being used

On a single web page, there are 3 different language words displayed: Language / 한국어 / ภาษาไทย I am interested in enlarging the Thai word (ภาษาไทย) to make it stand out. <span class="thai">ภาษาไท ...

What is the best way to resize a PDF to match the width and height of a canvas using

I need help with a project involving rendering previews of PDF documents in a UI similar to Google Docs. {documents.map((doc) => { return ( <div key={doc.id} className=" ...

Transforming FullCalendar (jquery) into asp.net (ashx)

///////////// Expert //////////////// $(document).ready(function() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar').fullCalendar({ ...

developing a shader that transitions between day and night based on the movement of a light source

I've set up a scene with a sphere illuminated by a DirectionalLight to simulate the sun shining on Earth. My goal is to incorporate a shader that displays the earth at night on the unlit portions of the globe and during the day on the lit areas. Event ...

What is the best way to transform a List<Pair<String, String>> to a List<String> using JavaScript?

Here is the data output structure: Map<String, List<Pair<String, String>>> "testdata": [ { "1.0": "True" }, { "1.1": "False" } ] ...

Navigating through information using Axios in React JS

Issue Currently, I am facing a challenge while trying to iterate through the data retrieved from an API call using Axios in a React.js application. The response is successfully received, but I am encountering difficulties when trying to display the inform ...

What is the best way to upload multiple files using ASP.Net and Jquery?

On my aspx page, I have included the following JavaScripts... <script src="jquery-1.3.2.js" type="text/javascript"></script> <script src="jquery.MultiFile.js" type="text/javascript"></script> In addition, I have inserted the follo ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...

Using Angular to invoke the transclude directive function inside the transcluded component

I am looking to develop a component that includes a transcluded section, take a look at this example: http://jsfiddle.net/vp2dnj65/1/ Upon clicking the "do" button in the example, nothing seems to happen. Is there a way to execute the transcluded cont ...

I'm puzzled as to why I have to encode the path parameter twice in order for the REST call to properly handle special characters

I have a challenge with a REST call that fetches a product's ingredients using the product name as the path variable. I allow for any character to be used, and I know I need to use encodeURIComponent(name) to encode characters such as "/" to prevent m ...