3

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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

If you were willing to explore an alternative to Jquery, there is a tool called XAJAX that allows you to directly call PHP functions asynchronously via AJAX. It's a pretty nifty tool, though the support and forums are a bit cryptic. For those who are hardcore PHP (but not JAVASCRIPT) guys, this tool is a great option.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.