0

i need some help to understand this js / jquery - thing..

I`am not the best js scripter, but i want to lean something about it.

I want to create an rest-api, the backend with php is no problem, but now i have to script the frontend.

The interactive communication with the frontend i want to realize with jquery / ajax. After a few hours to trying to understand this function i ask you.

Actually verry simple i want to return the response of the $.post(...).done(..); function.

The code i´ve wrote:

      function apiCall($methode = '', $value = ''){
        return $.post(endpoint, {'apiKey': apiKey, contentType: 'application/json; charset=utf-8',async: false,dataType: "json"}).done(function (response){console.log('inner response: ' + response['status']);return response});
      }

The output in the console:

1.

{
    "readyState": 4,
    "responseText": "{\"status\":\"ok\"}",
    "responseJSON": {
        "status": "ok"
    },
    "status": 200,
    "statusText": "OK"
}
inner response: ok

My function call:

      $(document).ready(function(){
        $("#my-submit").click(function (){
            console.log((apiCall()))
        });
      });

How its possible to throw the return from the .done() function up to my console.log((apiCall())) call?

I´ve tried everything i know from other programming / script languages, global variables some other funciton calls, but nothing work. :(

EDIT: I have to adress my return with the ````then``` argument. This works for me:

      $(document).ready(function(){
        $("#domain-report-submit").click(function (){
            apiCall().then((data) => console.log(data['status']));
        });
      });
NETFLOX
  • 119
  • 1
  • 10
  • 1
    You can't have a value **now** when it won't exist until some time in the future. – Quentin Nov 01 '22 at 17:02
  • 1
    Try changing the `async` to true. Also, since the ajax is a promise, await the apiCall() – AntonyMN Nov 01 '22 at 17:04
  • @Quentin ithe thought I had also, but in the first output, so the function call in the log he has the output? The 1st output would then have to be null or something similar? – NETFLOX Nov 01 '22 at 17:06
  • @AntonyMN no, same. I belive my problem is, that i dont know ho to address the result? Something like ```console.log((apiCall()['status']))``` dont work. – NETFLOX Nov 01 '22 at 17:07
  • What I mean is, `console.log(await (apiCall()))`. Don't forget to put the function in an async. – AntonyMN Nov 01 '22 at 17:11
  • @AntonyMN doenst work to :( But if i use ```then``` it works. Thank you. – NETFLOX Nov 02 '22 at 08:03

0 Answers0