marcelo2605
marcelo2605

Reputation: 2794

jQuery $.when() and ajax call

I'm a little confusing of how I can wait ajax return values and then do something. Here what I tryed:

$('.project-item').on('click', function(){
  var id = $(this).attr('id');
  $.when(getImages(id)).done(function(resp) {
    console.log(resp.responseJSON);
  });
});

function getImages(id) {
  var data = {
    'action' : 'getImages',
    'id' : id,
  };
  var result = $.Deferred();
  result.resolve($.post(ajaxurl, data));
  return result.promise();
}

But console.log(resp.responseJSON); immediattely return undefined;

The ajax call was tested before and is returning results.

Upvotes: 0

Views: 64

Answers (2)

charlietfl
charlietfl

Reputation: 171669

You don't need the $.when or the $.Deferred() since jQuery ajax methods already return a deferred/promise object.

var ajaxurl ='https://my-json-server.typicode.com/typicode/demo/posts'

$('.project-item').on('click', function(){
  var id = $(this).attr('id');
  getImages(id).done(function(resp) {
    console.clear();
    console.log(resp);
  });
});

function getImages(id) {
  var data = {
    'action' : 'getImages',
    'id' : id,
  };
  return $.post(ajaxurl, data)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="project-item" id="10">Item 1</li>
  <li class="project-item" id="20">Item 2</li>
  <li class="project-item" id="30">Item 3</li>
  <li class="project-item" id="40">Item 4</li>
  <li class="project-item" id="50">Item 5</li>
</ul>

Upvotes: 1

Benny Powers
Benny Powers

Reputation: 5836

You can do this with plain old JavaScript

// define a function to handle a fetch Response as JSON.
const handleAsJson = response => response.json();

// Get a reference to your element
const item = document.querySelector('.project-item');

// Set up the click listener
item.addEventListener('click', async function onClickItem(event) {

  // Initialize the fetch request with your data
  const id = this.getAttribute('id');
  const method = 'POST';
  const action = 'getImages';
  const body = JSON.stringify({ id, action });

  // Send the fetch request and handle it as JSON
  const resp = await fetch(ajaxurl, { method, body })
    .then(handleAsJson)

  // finally, log the result
  console.log(resp)
});

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Upvotes: 0

Related Questions