0

I've been trying for days to make this work:

            $.ajax({
                url: 'http://otherdomain.com/mail.json' ,
                dataType: 'json',
                data: jsonObject,
                success: function(data){
                    alert("Thank you for your inquiry. We will get back to you soon.");                     
                }
            });

The mail.json API works when I use the Chrome Postman app to test and the response header is this:

Accept-Ranges →bytes
Access-Control-Allow-Origin →*
Alternate-Protocol →80:quic,p=0.002
Cache-Control →private
Content-Encoding →gzip
Content-Length →22
Content-Type →application/json; charset=UTF-8
Date →Mon, 15 Sep 2014 05:18:09 GMT
Server →Google Frontend
Vary →Accept-Charset, Accept-Encoding, Accept-Language, Accept

What could be wrong in my Jquery code, as the server works fine.

2
  • is there any error in your console Commented Sep 15, 2014 at 5:27
  • I can't see any error in the console, actually the page re-loads when the form submit button is clicked where this ajax call is in. Commented Sep 15, 2014 at 5:32

3 Answers 3

1

For cross domain ajax calls it is preferable to use JSONP. You can get more information here: JSONP stackoverflow

Sign up to request clarification or add additional context in comments.

Comments

1

As you saied,the page reloads when the form submit button is clicked where this ajax call is in.If using asynchronous submission,you should prvent the default action of browser.For exanple,

$('submit').click(function(e){
    //prevent default action
    e.preventDefault();
    $.ajax({
       url: ,
       success: function(res) {

       }
    })
})

Comments

0

The URL http://otherdomain.com/mail.json is from another domain. According to the "Same Origin Policy", you should not be able to send the request (Unless you simply open your HTML file in the browser with deploying to a server, something like file:///C:/Projects/HTML5/WebContent/request.html, I guess).

To make cross-domain Ajax requests, you can try JSONP as @Vivin suggests. So your jQuery code could be like this:

$.ajax({
        url: url,
        dataType: 'jsonp',
        jsonp: 'jsonpcallback',
    }).done(function(data) { // deal with your data
    });

In your server-side, your need to return something like jsonpcallback(YOUR_DATA_IN_JSON_STRING). For a more detailed tutorial, you can search online. Here is a Chinese tutorial written by me: JSONP Tutorial

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.