0

I have php script with 5 function. The script gets "request_type" "user_id" and "youtube_id" and execute a function (one of a five) suitable to the "request_type"

Each function returns me json.

Now on the client side i have this javascript function. I want it to be generic as much as possible, Which mean that i want it to get data from php and return it as object.

function request_to_server(f_request_type, f_user_id, f_youtube_id) {
                            var my_answer;
                            $.ajax({
                                type : "POST",
                                dataType : "json",
                                url : "http://example.com/youtube_save.php",
                                data : {request_type: f_request_type, user_id : f_user_id, youtube_id:f_youtube_id },
                                success: function(response) {

                                  my_answer = JSON.parse( response );

                                }
                            });
                            return my_answer;
                        }

Here is the example of another function that get this object

function show_button_or_not() {

                            var user_id = $('#hold_user_id').val();
                            var answer = request_to_server('show_button','89',"lala");

                            if(answer.success) {
                              alert("yes");
                            } else {
                                alert("no");
                            }


                        }

But as i said, the php can return different kinds of json. It can have (optional) response.success, response.book, response.author.

Anyone can explain how to do that?

Ilya Libin
  • 1,515
  • 2
  • 17
  • 36
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Ian Mar 04 '14 at 19:45
  • @lan i'll try to find an answer there, thanks – Ilya Libin Mar 04 '14 at 19:50
  • Ajax is asynchronous by nature, meaning that the server request is not complete before you return the result, therefore the success function is not called before you return. You have to set the `async : false` when you create the ajax request so that you wait for the server response. A better option is to create a callback function. – Logan Murphy Mar 04 '14 at 19:50

1 Answers1

0

On the server side, in PHP, add the request_type to the json response so that your client side AJAX callback will receive the request_type that had initiated the AJAX in the first place.

All you have to do after that is evaluate the request_type (with a switch case maybe) and perform the necessary actions for that case (request_type).

But honestly, I wouldn't try to make the AJAX request and callback "generic" and having 1 URL pointing to 5 php functions it's not best practice for a web api.

TchiYuan
  • 4,047
  • 4
  • 26
  • 34