0

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.

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.