Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  6] [ 2]  / answers: 1 / hits: 15406  / 9 Years ago, wed, october 14, 2015, 12:00:00

I have a javascript file in which i want to send json data to a ERP system:


 var formData1 = JSON.stringify($('#msform').serializeObject());
$.ajax({
url:'http://102.101.101.11:80/c/orders',
type:'POST',
data:formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function(data) {
//window.location.href = "http://www.petlooza.com";
console.log(data);
}
});

This script works with chrome and IE, but FIREFOX gives me this error:



Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at the url. Reason: Cors-request failed.



How to fix this? See solution below!


More From » json

 Answers
9

I fixed it by doing the following:


A. You need a .htaccess on the host where you run the script.


<FilesMatch ".(php)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

secondly the ERP system also need headers to be set. You can check with curl if headers are correctly set or not.


B. Another option: if you do not want to work with headers, or are unable to set some headers then you can use CURL to do the job :


when clicking submit on my form, my script will call a .php file in which i have this code:


<?php
//
//code to send json to lotus webservice without cors errors
//
$jsondata = $_GET['jsondata'];
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"102.101.101.11:80/c/orders");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$jsondata);

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);


curl_close ($ch);



?>

and it works! no more cors errors! and data send to the server and also received by server :)


[#64748] Sunday, October 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;