How to respond to ajax call from iframe?

by tressie.damore , in category: HTML & CSS , 9 months ago

How to respond to ajax call from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 9 months ago

@tressie.damore 

To respond to an AJAX call from an iframe, you can use postMessage API. Here is a simple example of how you can achieve this:

  1. In the parent window that contains the iframe, add an event listener to listen for messages sent from the iframe:
1
2
3
4
5
6
window.addEventListener('message', function(event) {
  if (event.origin !== 'https://example.com') return; // Ensure only messages from specific origin are accepted
  
  // Handle the message sent from the iframe
  console.log('Message received from iframe: ', event.data);
});


  1. In the iframe, use the postMessage method to send a message to the parent window:
1
2
// Send message to parent window
window.parent.postMessage('Hello from iframe!', 'https://example.com');


In this example, the parent window listens for messages from the iframe and logs the message received. The iframe sends a message to the parent window using the postMessage method.


Make sure to replace 'https://example.com' with the actual origin of the parent window and the appropriate origin verification logic to ensure secure communication between the iframe and the parent window.

Related Threads:

How to load a partial view in an iframe on ajax call?
How to call ajax in jquery in laravel?
How to get a value from ajax call in laravel?
How to get data from ajax call in laravel?
How to call ajax url properly on wordpress?
How to rerender elementor posts widget with an ajax call?