0

I am intending to create a small api, that will do some php functions, but can be implemented by js only.
I want to create a similar solution to the facebook sdk.
So I created a php file named rest.php
and a js file nammed conjs.js now I need to perform an ajax request from the conjs.js file, but I get an undefined when trying to request an ajax request.
1) How should I build this?
2) What am I doing wrong?

rest.php

<?php 

echo "Hello from ".$_GET['name'];
?>

conjs.js --> included on the html page of client (similar to

connect.facebook.net/en_US/all.js off facebook)

function getDev(){
$.ajax({
    url: 'http://mydomain/rest.php',
    type: 'GET',
    data: 'Name=John', // or $('#myform').serializeArray()
    success: function(data) { return('Get completed '+data); }
});
}

Client smaple html page: -not on domain-

<html><head> <script src="http://mydomain/conjs.js"></script></head><body>
<script>
alert(getDev());
</script>
</body></html>

Thanks in advance :)

funerr
  • 7,212
  • 14
  • 81
  • 129

2 Answers2

3

You need to use a callback due to ajax's asynchronous nature.

A callback is a function that is passed as an argument to another function which executes the callback at an interesting point. In the case below, it's in the success block of the ajax response which is considered as interesting.

Try this:

function getDev(callback){
$.ajax({
    url: 'http://mydomain.com/rest/rest.php',
    type: 'GET',
    data: 'Name=John', // or $('#myform').serializeArray()
    success: function(data) { 
        callback('Get completed '+data); 
    }
});
}

Later when calling:

<script type="text/javascript">
getDev(function (response) {
    alert(response);
});
</script>
Community
  • 1
  • 1
T. Junghans
  • 11,385
  • 7
  • 52
  • 75
  • Are there any articles I could read about relating to this "nature"? – funerr Mar 25 '12 at 21:02
  • 1
    @agam360 Have a look at the links in my answer. If you google "javascript + callback" you'll get plenty of good results. For example: http://recurial.com/programming/understanding-callback-functions-in-javascript/ – T. Junghans Mar 25 '12 at 21:36
  • It doesn't work, it just does nothing... I think it's because of the same origin policy. – funerr Mar 27 '12 at 16:34
1

AFAIK $_GET[] is case sensitive. So either send lower case 'name=John' or read the correct $_GET['Name']

Martin Hansen
  • 5,154
  • 3
  • 32
  • 53