Good day! I just can not configure cross-domain ajax request. Help me please.

On one domain there is a form that sends a request to another domain. Another should send a response: either {"error":1} or {"error":0} . Depending on this, the response function is specified in jsonpCallback .

 $.ajax({ url: 'http://site/sendmail.html', dataType: 'jsonp', data: { 'name' : jQuery('#name').val(), 'email' : jQuery('#email').val(), 'phonecode' : jQuery('#phonecode').val(), 'phonenumber' : jQuery('#phonenumber').val(), 'message' : jQuery('#message').val() }, jsonpCallback: "mailResponce" }); function mailResponce(responce) { if(responce.error < 1){ alert('Запрос отправлен!'); }else{ alert('Ошибка при отправлении запроса!'); } } 

After sending the request, the answer comes: http://site.ru/sendmail.html?callback=mailResponce&name=Vasea&email=mail@40yandex.ru

To me, as I understand it, in order for the jsonpCallback: "mailResponce" function to work, the response should be .. html? Callback = mailResponce {"error": 0} & ...
For this, do I need to send something specifically from the server that sends the answer? Now the server issues: echo json_encode($data); either $data['error'] = 0; either $data['error'] = 1; but in the callback function it is not passed.

Tell me what I'm doing wrong! Thank you in advance!

  • A cross domain query is essentially a script load. You load the script, the onload event is triggered on this script, and the function that is specified as "jsonpCallback" is executed. - lampa

2 answers 2

http://site.ru/sendmail.html?callback=mailResponce&name=Vasea&email=mail@40yandex.ru is not the answer. This is the request you sent.

In order for the mailResponce function to work, it is necessary that it be called in the response . An example of a correct jsonp response that a server could give:

 mailResponce({ error : 0}) 

How to get such an answer, think for yourself, I do not know php .


PS But think: what are you doing ?! You give anyone who wants to send any mail to any email address without any authorization! How do you think, how much time will pass before your “service” starts being used by spammers?

    The server that responds to you must additionally transmit the Access-Control-Allow-Origin header: your-domain.ru or so Access-Control-Allow-Origin: *

    Tobish responding server, must explicitly indicate to the browser that you can receive its answers.

    • one
      here is jsonp. this is not ajax, not xmlhttprequest. - Yura Ivanov