I am writing REST apis in php without using any framework. I am able to call apis with string data as a prameter, but problem occurs when I call a url with JSON object as parameter.
-My .htaccess file is as:
# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on
# map neat URL to internal URL
RewriteRule ^get/([a-z0-9\-]+)/$ RestController.php?box=$1 [nc,qsa]
RewriteRule ^addinbox/([a-z0-9\-]+)/$ RestController.php?emailObj=$1&mode=addinbox [nc,qsa]
I am using jQuery for making a ajax call:
-ajax call :
var emailObj = {
"name": "Mathew Murddock",
"receiver": receiver,
"sender": "daredevil@marvel.com",
"subject": subject,
"content": body,
"time_stamp": time_stamp
};
var objToSend = JSON.stringify(emailObj);
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: "http://localhost/emailServer/addinbox/",
dataType: 'json',
data: objToSend+'/',
success: function(response){
console.log(response);
}
});
But is returns this error:
XMLHttpRequest cannot load http://localhost/emailServer/addinbox/?{%22name%22:%22Mathew%20Murddock%22,…%22This%20is%20%20some%20dummy%20text.%22,%22time_stamp%22:%2212:35:0%22}/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Although I have allowed cross origin at server side: -RestController.php
<?php
header('Access-Control-Allow-Origin: *');
//Remaining code
The URL I am getting while ajax call is :
http://localhost/emailServer/addinbox/?{%22name%22:%22Mathew%20Murddock%22,%22sender%22:%22daredevil@marvel.com%22,%22subject%22:%22This%20is%20a%20mail%22,%22content%22:%22This%20is%20%20some%20dummy%20text.%22,%22time_stamp%22:%2212:35:0%22}/
Am I rewriting the URL in a wrong way?
([a-z0-9-]+) matches lower-case letters, digits and "-" nothing else so you will not be matching your json, also consider stopping sending json in get all together. It is a bad practice To serve the call you showed us your api should actually require a POST
I think you don't need to use JSON.stringify(emailObj);
contentType: 'application/json; charset=utf-8'
// this line says you need to send json file but you are sending stirng file
I think you don't need to use JSON.stringify or json_decode here at all. Just do:
data : {
"name": "Mathew Murddock",
"receiver": receiver,
"sender": "daredevil@marvel.com",
"subject": subject,
"content": body,
"time_stamp": time_stamp
},
and in php
$name=$_POST['name'];
Pleae inform me if did not work for you?