Search code examples
phpjqueryajaxweb-servicesajax-request

No response from a jQuery Ajax request to a PHP Webservice


I have a little issue with a application wich is specified the following:

I need to send to a credit card payment webservice some data by post, so the webservice will proccess the information and return a XML.

I thought I could do it with the $.post() jQuery Ajax method. That's my code:

$.post("https://comercio.locaweb.com.br/comercio.comp", { 
identificacao: dadosPagamento[0], 
modulo: dadosPagamento[1], 
operacao: dadosPagamento[2], 
ambiente: dadosPagamento[3], 
bin: dadosPagamento[4], 
idioma: dadosPagamento[5], 
valor: dadosPagamento[6], 
pedido: dadosPagamento[7], 
descricao: dadosPagamento[8], 
bandeira: dadosPagamento[9], 
forma_pagamento: dadosPagamento[10], 
parcelas: dadosPagamento[11], 
autorizar: dadosPagamento[12], 
capturar: dadosPagamento[13] 
},
function(data) {
alert(data);
window.open('../negocio/index.php?mod=cliente&acao=gambs&xml=' + encodeURI(data));
$('#resultadoFinal').html(data);
}
);

The alert(data) I'm using just to test the response, and the problem is: I send it to local test file (@ window.open('../negocio/...') ), and then the response is working ok, otherwise in the webservice (https://comercio.locaweb.com.br...) there's no response, and the XML I'm waiting for doesn't even exist.

Does anybody know what's happening? Or if I'm doing it the wrong way, could someone tell me a better way to get the XML sending data by Post?

Thank you.


Solution

  • Vinicius,

    It looks like you are trying to use ajax to interact with a web service running on another domain? Browsers will not allow this due to the fact that they follow the Same Origin Policy when making ajax requests.

    There are a number of methods to get around this limitation. One of which would be to host a proxy on your PHP site which performs the web request for you. Then your code can make the request the page that you host (which is allowed under the Same Origin Policy) but you are still able to call this service you require. There is a more detailed description of this limitation available on this page which even includes sample PHP code for this proxy page.

    There is also a JavaScript library called easyXDM (which is mentioned in the Wikipedia article above). This library will determine the best method to use to perform this cross-site communication based on the user's browser. More information on this project is available here. I'm not sure how widely used easyXDM is in the wild, but I see that it does require that flash is installed on the user's computer before IE6-7. This means that would be expected that any IE 6-7 users of your site would have to have flash installed in order to use this payment service (could be a potential headache).

    Personally I'm not a big fan of adding dependencies user dependencies like this unless I have to, so I would try to implement the proxy solution.