Thursday 6 September 2018

Call the PHP function with jquery $ .ajax return json

How can I call (if even possible) a PHP function from javascript targeting one method just like ASP.NET.
PHP:
...
function a($some_string){
return json_encode(array(
                "username" => "bob",
                "items" => array(
                        "item1" => "sandwich",
                        "item2" => "applejuice"
                )
        ));
}

JS:
    $.ajax(
        {url:"index.php/a",
        type:"POST",
        contentType:"application/json; charset=utf-8",
                    data:{some_string:"blabla"},
        dataType:"json",
        success:function(data){
            alert(data);
            },
        error:function(a,b,c){
            }
        });

In C#:
[WebMethod()]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static object a(string some_string)
{
  return new {
                user_name = "bob",
                items = new {
                    item1 = "sanwitch",
                    item2 = "applejuice"
                    }
                };
        }

Thanks,
Péter

You can just put that one function in a PHP file alone. Then run the function within that file (so it echoes out the JSON). Have ajax call that file.
In your case:
echo a($string);

0 comments:

Post a Comment