Reputation: 3270
I'm trying to access my rest api which I have created. Its working perfectly fine, when I type the following:
http://localhost:8080/rest/index.php/api/practice/test/name/Peter/surname/Potter/format/json
I get a correct json response. Now I have a website and simply just want to access the rest api using ajax. Here is the code:
$(document).on('pagebeforeshow','#page2',
function(){
$('#submit').click(function()
{
var name = $("#username").val();
var surname = $("#usersurname").val();
alert(name + " " + surname);
//alert("http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname);
$.getJSON({
type: "GET",
crossDomain: true,
dataType: "jsonp",
url: "http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname,
success: function(data)
{
alert("workings");
}
});
});
});
Now when I use this code I get a 404 not found response. I know for a fact when I got to that url that I'm meant to get a json response. Here is my Controller from the rest api:
<?php
require(APPPATH.'libraries/REST_Controller.php');
class practice extends REST_Controller
{
function test_get()
{
//echo "working fine ";
$name = $this->get('name');
$surname = $this->get('surname');
//echo $name." ".$surname;
$result = array('result' => "Working likes a boss ".$name." ".$surname);
$this->response($result,200);
}
}
?>
Upvotes: 0
Views: 4854
Reputation: 15
you should set header to json :
<?php
require(APPPATH.'libraries/REST_Controller.php');
class practice extends REST_Controller
{
function test_get()
{
//echo "working fine ";
$name = $this->get('name');
$surname = $this->get('surname');
//echo $name." ".$surname;
$result = array('result' => "Working likes a boss ".$name." ".$surname);
header('Content-Type: application/json');
echo json_encode( $result );
}
}
?>
Upvotes: 0
Reputation: 74028
In your call $.getJSON(...)
, you have the URL
url: "http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname
which misses the /format/json
part from above.
You also have
dataType: "jsonp",
which isn't json
.
Update:
I just looked up jQuery.getJSON()
and the call is
jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )
It seems you must change your call to
$.getJSON("http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname + "/format/json",
function(data) { alert("workings"); });
or use jQuery.ajax()
Upvotes: 1