0

I want to convert curl command :

curl -X POST -H "X-Requested-With: XMLHttpRequest" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{"username": "admin","password": "admin"}' "http://localhost:8080/api/auth/login"

to ajax jquery, i have tried to use this code below but it does not work:

$.ajax({
    type: 'POST',
    crossDomain: true,
    url: 'http://localhost:8080/api/auth/login',
    dataType : 'json',
    data: JSON.stringify(datax),
    success:function(data){
        console.log(data);
    },
    error: function(data) { // if error occured
        var responseText = $.parseJSON(data.responseText);
        if(responseText.error){

        }

    }
})
.done(function(data) {

})
Jagadish Upadhyay
  • 1,236
  • 13
  • 22
aldo
  • 312
  • 3
  • 12
  • try using php with ajax – Rahul Singh Jan 04 '17 at 10:08
  • Can you tell us a bit more than "it does not work"? Does it give an error message? Can you see anything in the browser console? I presume you've tried putting a `console.log` in the `error` and `done` callbacks as well and looked for that output? Also, where is `datax` defined? – IMSoP Jan 04 '17 at 10:09
  • @RahulSingh This has nothing to do with PHP – IMSoP Jan 04 '17 at 10:10
  • you can call a php page in ajax. from that php page you make curl call. – Rahul Singh Jan 04 '17 at 10:14
  • @RahulSingh But it's making the AJAX call the OP is having the problem with. Saying "make another AJAX call, which makes this one in the background" doesn't really help. – IMSoP Jan 04 '17 at 10:20
  • @IMSoP as you can see ajax is making an cross domian call. which is not recomended. while making an call from php. you can validate input.http://stackoverflow.com/questions/466737/why-the-cross-domain-ajax-is-a-security-concern http://stackoverflow.com/questions/5383045/why-cross-domain-ajax-call-is-not-allowed as i an still learning. please correct me if am wrong. thank you – Rahul Singh Jan 04 '17 at 10:33
  • @RahulSingh I can't see that at all, because as I said in my comment, not enough details were provided; for all I know, this site is entirely hosted on `localhost:8080`, and there is no domain crossing involved. If that is the problem, then yes, you would need to AJAX to a local page (not necessarily PHP) then make the other call from the server. – IMSoP Jan 04 '17 at 10:43

1 Answers1

0

dataType: 'json' does not reflects the contentType. It's for jQuery to know how to handle the answer.

You are looking for contentType...

$.ajax({
    type: 'POST',
    crossDomain: true,
    cache: false,
    url: 'http://localhost:8080/api/auth/login',
    contentType : 'application/json',
    data: JSON.stringify(datax) //Expecting datax is  username & password
})
.done(function(data) {
})

http://api.jquery.com/jquery.ajax/

DarkLegend
  • 1,706
  • 1
  • 11
  • 10