Essential jQuery Interview Questions

author image Hirely
at 06 Jan, 2025

Question:What is the $.ajax() method in jQuery?

Answer:

The $.ajax() method in jQuery is used to perform asynchronous HTTP (AJAX) requests to load data from a web server without refreshing the page. It is a powerful and flexible function that allows you to interact with servers, send data, and receive responses in various formats like JSON, HTML, XML, or plain text.

The $.ajax() method provides a way to make requests to a server, handle responses, and update parts of the web page without reloading the entire page, thus enabling dynamic content updates in web applications.


Basic Syntax of $.ajax()

$.ajax({
  url: "url",                // URL to which the request is sent
  type: "GET",               // HTTP request type (GET, POST, PUT, DELETE, etc.)
  dataType: "json",          // Type of data expected from the server (json, xml, text, etc.)
  data: {},                  // Data to send to the server (can be an object, array, or string)
  success: function(response) {  // Callback function executed on success
    console.log(response);       // Handle the response here
  },
  error: function(xhr, status, error) {  // Callback function executed on error
    console.log(status + ": " + error);
  },
  complete: function(xhr, status) {  // Callback function executed after the request is complete
    console.log("Request completed");
  }
});

Key Options for $.ajax()

  1. url: The URL where the request is sent. It can be an absolute or relative URL.

    • Example: "https://api.example.com/data"
  2. type: The HTTP method for the request. Common methods include:

    • "GET": Retrieve data from the server.
    • "POST": Send data to the server.
    • "PUT", "DELETE", etc.
  3. dataType: The type of data expected back from the server. Some common values are:

    • "json": Expect a JSON response.
    • "xml": Expect an XML response.
    • "html": Expect an HTML response.
    • "text": Expect plain text.
    • "script": Expect JavaScript to be executed.
  4. data: Data to send with the request. It can be a query string, an object, or an array.

    • Example: data: { name: "John", age: 30 }
  5. success: A callback function to handle the response when the request is successful. It gets the server response as its argument.

    • Example:
      success: function(response) {
        console.log(response);  // Server response
      }
  6. error: A callback function that handles errors during the request. It receives the xhr (XMLHttpRequest) object, the status, and the error message as arguments.

    • Example:
      error: function(xhr, status, error) {
        console.log("Error: " + status + ": " + error);
      }
  7. complete: A callback function that is executed after the request completes, regardless of success or failure.

    • Example:
      complete: function(xhr, status) {
        console.log("Request completed with status: " + status);
      }

Example Usage of $.ajax()

1. Simple GET Request

This example fetches data from a URL and logs the response to the console.

$.ajax({
  url: "https://api.example.com/data",
  type: "GET",
  dataType: "json",
  success: function(response) {
    console.log(response);  // Log the JSON response
  },
  error: function(xhr, status, error) {
    console.log("Error: " + error);
  }
});

2. POST Request with Data

This example sends data to a server via a POST request and logs the server’s response.

$.ajax({
  url: "https://api.example.com/submit",
  type: "POST",
  dataType: "json",
  data: {
    name: "John",
    age: 30
  },
  success: function(response) {
    console.log(response);  // Log the response from the server
  },
  error: function(xhr, status, error) {
    console.log("Error: " + error);
  }
});

3. Handling JSON Data

If the server returns JSON data, jQuery can automatically parse it into a JavaScript object, making it easier to work with.

$.ajax({
  url: "https://api.example.com/data",
  type: "GET",
  dataType: "json",
  success: function(response) {
    // Assuming the response is a JSON object
    console.log("Name: " + response.name);
    console.log("Age: " + response.age);
  },
  error: function(xhr, status, error) {
    console.log("Error: " + error);
  }
});

Advantages of Using $.ajax()

  1. Asynchronous: AJAX allows for asynchronous requests, meaning the page does not need to reload when making requests to the server.
  2. Cross-browser compatibility: jQuery abstracts away browser differences, so $.ajax() works consistently across different browsers.
  3. Handles different data formats: You can work with JSON, XML, HTML, text, and other formats easily.
  4. Customizable: It offers a wide range of options like timeout, beforeSend, headers, and more to customize the request and handle responses.
  5. Chainable: jQuery’s AJAX methods are chainable with other jQuery methods, enabling a more fluid development style.

Conclusion:

The $.ajax() method is a core tool in jQuery for making asynchronous HTTP requests. It allows you to interact with servers, send and receive data, and update your web page dynamically without requiring a full page reload. With its flexible options and error handling capabilities, $.ajax() is an essential function for building modern web applications that interact with remote APIs or backend servers.

Question:What is the purpose of the .prop() and .attr() methods in jQuery?

Answer:

Both .prop() and .attr() are jQuery methods used to get or set properties and attributes of HTML elements, but they serve different purposes and are used in different scenarios. Here’s a breakdown of their differences and use cases:


1. .attr() Method:

The .attr() method is used to get or set the attributes of an HTML element. Attributes are the initial settings defined in the HTML markup for elements like href, src, id, class, etc.

Usage:

  • Getting an attribute:

    var hrefValue = $('a').attr('href');
    console.log(hrefValue);  // Retrieves the value of the "href" attribute
  • Setting an attribute:

    $('a').attr('href', 'https://example.com');

Common Use Cases for .attr():

  • Accessing or modifying attributes like src, href, alt, title, etc.
  • Example: Changing the href attribute of an anchor (<a>) element:
    $('a').attr('href', 'https://newsite.com');

2. .prop() Method:

The .prop() method is used to get or set properties of an HTML element. Properties are dynamic attributes that reflect the current state of the element, such as checked, selected, disabled, etc. These properties may change during runtime based on user interaction or script actions.

Usage:

  • Getting a property:

    var isChecked = $('input[type="checkbox"]').prop('checked');
    console.log(isChecked);  // Returns true or false based on whether the checkbox is checked
  • Setting a property:

    $('input[type="checkbox"]').prop('checked', true);

Common Use Cases for .prop():

  • Accessing or modifying properties like checked, disabled, selected, readonly, etc.
  • Example: Setting a checkbox to checked:
    $('input[type="checkbox"]').prop('checked', true);

Key Differences Between .attr() and .prop()

Feature.attr().prop()
PurposeUsed for HTML attributes (static).Used for DOM properties (dynamic).
Common Use CasesRetrieving or setting attributes like href, src, title, etc.Retrieving or setting properties like checked, selected, disabled, etc.
Example<a href="https://example.com">Link</a><input type="checkbox" checked />
BehaviorReflects the value as defined in the HTML source code.Reflects the current state of the element after changes (e.g., user interactions).
Use Case ExampleSetting an anchor’s href attribute to a new URL.Checking if a checkbox is checked.

Examples:

Example 1: Using .attr() to Get and Set Attributes:

<a href="https://oldsite.com" id="link">Visit Old Site</a>
// Get the "href" attribute
var oldHref = $('#link').attr('href');
console.log(oldHref);  // "https://oldsite.com"

// Set a new "href" attribute
$('#link').attr('href', 'https://newsite.com');

Example 2: Using .prop() to Get and Set Properties:

<input type="checkbox" id="check" checked>
// Get the "checked" property
var isChecked = $('#check').prop('checked');
console.log(isChecked);  // true

// Set the "checked" property to false
$('#check').prop('checked', false);

Important Notes:

  • Attributes (used with .attr()) reflect the initial state as defined in HTML. For example, an <input> element may have the checked attribute in the markup, but the actual state of whether it is checked or not is represented by its checked property (which you access with .prop()).

  • Properties (used with .prop()) represent the current state of the element after any changes, such as user interaction. The checked property of a checkbox is updated dynamically when the user checks or unchecks the box.


When to Use .attr() vs .prop()

  • Use .attr() when dealing with static HTML attributes such as href, src, alt, and other attributes defined in the HTML markup.
  • Use .prop() when dealing with dynamic properties that represent the current state of the element, such as checked, disabled, selected, and other properties that may change due to user interaction or script actions.

Conclusion:

  • .attr() is for getting or setting HTML attributes (like href, src), while .prop() is for getting or setting DOM properties (like checked, disabled, selected).
  • Understanding when to use each is crucial to manipulating elements effectively in jQuery, ensuring you interact with the right aspect of the element (whether it’s its static attribute or its dynamic state).

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as jQuery interview questions, jQuery interview experiences, and details about various jQuery job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now