Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call PHP function with jquery $.ajax return json

Tags:

json

jquery

php

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

like image 590
Péter Avatar asked Jul 10 '26 01:07

Péter


1 Answers

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);
like image 134
phirschybar Avatar answered Jul 11 '26 13:07

phirschybar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!