I have test code for WordPress here.
jQuery(document).ready(function($) {
var link = 'http://000.00.00.00/cgi-bin/test.cgi';
$("#sub").click(function() {
$.ajax({
type:'POST',
url: link,
crossDomain: true,
crossOrigin: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'text/html'
},
dataType: "json",
success: function(data) {
console.log(JSON.stringify(data));
},
error: function(e) {
console.log("Error: " + e);
},
});
});
the request seems fine because when i view my chrome network > headers tab status code is OK but the problem is that there is no data. I should have a working output like this..
{ "loyalty" : { "status" : { "rows" : "1", "sql" : "success", "result" : "ok" }, "data" : [ { "card_number" : "1410104000350018" , "card_type" : "BEAUTY ADDICT" , "first_name" : "TINA" , "middle_initial" : "M" , "last_name" : "LIM" } ] } }
You can use JSONP to get data from other domain than your javascript host, which is something like blow:
$("#sub").click(function() {
$.ajax({
url: link,
dataType:'jsonp',
jsonp:'callback',
success: function(data) {
console.log(JSON.stringify(data));
},
error: function(e) {
console.log("Error: " + e);
},
});
and because JSONP transmit data through GET, so In your server side code you need retrieve data from $_GET like this(if you use PHP):
$your_param = $_GET['your_param'];
$callBack = $_GET['callback'];
//do something .....and get $result
echo($callBack . '(' .json_encode($result) . ')');
Related
I have writtent this script to send notification from my HTML page.
When i try to send the request, i get both messages "Success" and "Fail" and the notification is not sent. I call the function get_data_for_notification() on button click.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function get_data_for_notification(){
var title = document.getElementById('news_title').value;
var subtitle = document.getElementById('news_small_description').value;
$.ajax({
type : 'POST',
url : "https://fcm.googleapis.com/fcm/send",
headers : {
Authorization : 'key=mykey'
},
contentType : 'application/json',
dataType: 'json',
data: JSON.stringify({"to": "/topics/android", "priority" : "high", "notification": {"title":title,"body":subtitle}}),
success : alert("Success") ,
error : alert("Fail")
}) ;
}
</script>
Your script executes, before sending the request, alert("Success") and alert("Fail") and assigns their return value as the event handlers.
You have to wrap them in an anonymous function:
$.ajax({
type: 'POST',
url: "https://fcm.googleapis.com/fcm/send",
headers: {
Authorization: 'key=mykey'
},
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
"to": "/topics/android",
"priority": "high",
"notification": {
"title": title,
"body": subtitle
}
}),
success: function(responseData) {
alert("Success");
}
error: function(jqXhr, textStatus, errorThrown) {
/*alert("Fail");*/ // alerting "Fail" isn't useful in case of an error...
alert("Status: " + textStatus + "\nError: " + errorThrown);
}
});
The problem was on the button type, i needed to use type="button" and not type="submit".
I have an openIDM program and when users submit for update new password , it show "X-openIDM-Reauth-Password" which include my old password that i need to retype. Following is the screen shot from openidm side.
So, i have my own UI and i was request from javascript ajax side with following ajax call.
$.ajax({
contentType: "application/json; charset=UTF-8",
datatype: 'json',
url: targetHost+"openidm/managed/user/"+userId,
xhrFields: {
withCredentials: true,
},
headers: {
"X-Requested-With":"XMLHttpRequest" ,
"X-OpenIDM-Reauth-Password": oldPassword
},
crossDomain:true,
data: JSON.stringify(data),
type: 'PATCH',
success:function(result) {
console.log("success");
swal({
title: updateSuccessMsgs.formSubmit.slogan,
text: updateSuccessMsgs.formSubmit.success,
type: "success"
}, function() {
window.location = "my-profile.html";
});
},
error:function (error){
sweetAlert(updateErrorMsgs.updateError.slogan, updateErrorMsgs.updateError.fail, "error");
console.log(error);
}
});
and it throw me this error.
XMLHttpRequest cannot load http://localhost:9090/openidm/managed/user/09096425-4ff1-42d4-8a4d-3a6b5004afca. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Can someone explain me why? Appreciate it.
I found the solution. I try to add one more value in servletfilter-cors.json as follow. I added the value of "X-OpenIDM-Reauth-Password" in "allowedHeaders" and it is success.
{
"classPathURLs" : [ ],
"systemProperties" : { },
"requestAttributes" : { },
"scriptExtensions" : { },
"initParams" : {
"allowedOrigins" : "*",
"allowedMethods" : "GET,POST,PUT,DELETE,PATCH",
"allowedHeaders" : "accept,x-openidm-password,x-openidm-nosession,x-openidm-username,content-type,origin,X-OpenIDM-Reauth-Password,x-requested-with",
"allowCredentials" : "true",
"chainPreflight" : "false"
},
"urlPatterns" : [
"/*"
],
"filterClass" : "org.eclipse.jetty.servlets.CrossOriginFilter"
}
I'm sending this request, and it is perfectly fine as long as it's successful. However, if I try to create a user with existing username or email, I should get 400 bad request and response detailing what's the problem.
Thing is, when I send this request and get 400, nothing gets written to console/console (not even the 'fail!' string), but I can see that response is correct in console/network tab so the problem is probably not in the backend.
$("#registerForm").submit(function(e){
e.preventDefault()
$.ajax({
type: "POST",
url: "./register",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": formcontent['username'],
"email": formcontent['email'],
"password": formcontent['password'],
}),
success: function(e) {
window.location.href = './login'
return false
},
fail: function(e) {
console.log('fail!')
console.log(e)
//react to error
return false
},
})
})
I think 'fail' is a invalid function, Please try with below structure
$.ajax({
type : "POST",
url : "/register",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : JSON.stringify({
"username" : formcontent['username'],
"email" : formcontent['email'],
"password" : formcontent['password'],
}),
success : function(response) {
console.log(response);
},
error : function(response, status, err) {
console.log(response);
console.log(status);
console.log(err);
}
});
When i try to POST my JSON am not able to see any request and also my local server not even getting these calls.
This is my ajax part
function callserver(){
var markers = {"regDate" : 1451330123000, "specialities" : " ", "isActive" : true, "mobileNo" : "876876","id" : 0, "completed" : false,"mcname" : "", "password" : "hgh","role" : "SuperAdmin,Consultant","logins" : [],"email" : "testtestets#test.com","name" : "regcg","organization" : "hghjg"};
alert(markers);
$.ajax({
type: "POST",
data:markers,
headers: {
'Accept':'application/vnd.company.productname-v1+json',
'X-PD-Authentication':'42</B7Tg8o5C7`7<7Ar0?]pJs`#Noplt>I1m>QYQn[v=osDl:unWyx`SYqBK#0?w',
'Content-Type':'application/json'
},
dataType: "json",
url: "http://x.x.x.x:9001/users",
success: function(data) {
alert("success");
},
error: function () {
alert("failure");
}
});
}
Till alert(markers); is working but after that
am not getting "Success" or "failure" alert.
Console screenshots
Please help me
As you are not ready to show the full HTML, it looks like you are using another library with jQuery, because jQuery works. So kindly change all the $ to jQuery:
function callserver(){
var markers = {"regDate" : 1451330123000, "specialities" : " ", "isActive" : true, "mobileNo" : "876876","id" : 0, "completed" : false,"mcname" : "", "password" : "hgh","role" : "SuperAdmin,Consultant","logins" : [],"email" : "testtestets#test.com","name" : "regcg","organization" : "hghjg"};
alert(markers);
// Change here
jQuery.ajax({
type: "POST",
data:markers,
headers: {
'Accept':'application/vnd.company.productname-v1+json',
'X-PD-Authentication':'42</B7Tg8o5C7`7<7Ar0?]pJs`#Noplt>I1m>QYQn[v=osDl:unWyx`SYqBK#0?w',
'Content-Type':'application/json'
},
dataType: "json",
url: "http://x.x.x.x:9001/users",
success: function(data) {
alert("success");
},
error: function () {
alert("failure");
}
});
}
Hi there are already lots of threads related to this problem.
But still i got stuck into the same . When I am trying to access this REST api, I couldnt able to get the response. I cannot control server side response header because its public API .can any body help on this.
Below is my code
$(document).ready(function() {
$("#medication").autocomplete({
select : function(request, response) {
//$(this).value(response.item.value);
getMedicationIdByName(response.item.value);
},
search : function(){$(this).addClass('working');},
open : function(){$(this).removeClass('working');},
source : function(request, response) {
$.ajax({
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
type : "GET",
url : "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data : "name="+ request.term,
crossDomain: 'true',
dataFil ter : function(data) {
return data;
},
success : function(data) {
try {
//alert("success!!"+JSON.stringify(data));
data = data.suggestionGroup.suggestionList["suggestion"]+ "";
data = data.split(",");
response($.map(data,function(item) {
//alert("success!!"+JSON.stringify(item))
return {
value : item
};
}));
} catch (e) {
alert(e);
}
},
error : function() {
alert('Cannot connect to REST API!!!');
}
});
},
minLength : 4
});
});
You need to set dataType to jsonp in your ajax request.
type: "GET",
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url: "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data: { name: "bard"},
dataType: "jsonp",
crossdomain: true,