2

i want to request as json to API and get response and i tried it with postman and i got response:

json request to API:

{
"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"
}

response that i got in postman and it is ok

{
"status": 200,
"result": {
    "winner": "s",
    "options": {
        "1": "mar",
        "2": "feb",
        "3": "jan",
        "4": "aug"
    },
    "question": "how old are u?",
    "answer": 3
}

}

my problem is i want to send ajax request and get response.i try this code but it doesnt get any response?

var data = {"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"};
$.ajax({
type:'post',
dataType:'json',
url:'http://207.154.251.233:8039/app_dev.php/question/get',
data:JSON.stringify(data),
success:(function (response) {
alert(response);
})
})
sepehr
  • 165
  • 1
  • 2
  • 10

2 Answers2

0

Use this modified code:

var data = {"apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp"};
$.ajax({
    type:'post',
    dataType:'json',
    url:'http://207.154.251.233:8039/app_dev.php/question/get',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    crossDomain: true,
    data:JSON.stringify(data),
    success:(function (response) {
        alert(response);
    })
});

Further if your script runs from different host you must use cross origin access permission. For this, use

Access-Control-Allow-Origin: http://foo.example 

If your application built in php then use:

header("Access-Control-Allow-Origin: *"); 
// or your script's host, e.g http://foo.example instead of "*"
fatih
  • 330
  • 8
  • 17
0

The response you are getting is of type object, and will show up as [object] [object]. You will need to JSON.stringify if you want to do an alert on it. I suggest using console.log instead, it's better for debugging.

Scriptonomy
  • 3,975
  • 1
  • 15
  • 23