JSON Broken on Display - ajax

I have a JSON File, giving by vendor
{"html": "\n<link href=\"//apply.fundingoptions.com/static/msmclone/css/oembed-v3.css\" rel=\"stylesheet\">\n<script type=\"text/javascript\">\n var __raconfig = __raconfig || {};\n __raconfig.uid = '53302e56328ff';\n __raconfig.action = 'track';\n (function () {\n var ra = document.createElement('script');\n ra.type = 'text/javascript';\n ra.src = ('https:'==document.location.protocol?'https://':'http://')\n +'www.ruleranalytics.com/lib/1.0/ra-bootstrap.min.js';\n var s = document.getElementsByTagName('script')[0];\n s.parentNode.insertBefore(ra, s);\n }());\n</script>\n\n<div id=\"oembed-widget-container\" class=\"oembed-widget-container\">\n <div class=\"callout\">Initialising Finance Finder...</div>\n</div>\n<script type=\"text/javascript\">\n \n var widget_affiliate_id = 10;\n \n \n var widget_continue_url = \"//apply.fundingoptions.com/continue/\";\n \n \n var widget_submission_url = \"//apply.fundingoptions.com/oembed/submit/\";\n \n \n var widget_match_url = \"//apply.fundingoptions.com/match/\";\n \n \n var widget_title = \"Your funding options\";\n \n</script>\n<script src=\"//apply.fundingoptions.com/static/oembed/oembed-v4.js\"></script>\n\n",
"title": "Funding Options Finance Finder",
"version": 0,
"type": "rich",
"width": 500,
"height": 400
}
and I am parsing it on a webpage using this method
$.ajax({
type: 'GET',
url: 'json/data.json',
data: { get_param: 'value' },
dataType:'json',
success: function (data) {
var names = data
$('#summary').html(data.html);
}
});
But in the end , its show something like that on webpage:
as I am implementing it first time , I am not sure its my bad or json is corrupt or what else.

Looks like this is a Cross Origin Resource Sharing issue.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Check your browser console and look at the error you are getting when you try to load the page. It should say something similar to:
XMLHttpRequest cannot load http://apply.fundingoptions.com/match/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Because the data you are requesting is not on the same server as you you are being denied access.
It looks like the error is happening when the following request is made in the oembed-v4.js library:
jQuery.ajax({
url: that.match_url,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR) {
that.data = data;
if (data['next_question'] == null) {
that.showActions();
that.$spinnerElement.removeClass('fa-cog');
that.$spinnerElement.addClass('fa-check');
} else {
that.drawQuestion();
}
},
error: function(jqXHR, textStatus, errorThrown) {
that.displayError();
},
complete: function() {
that.toggleSpinner(false);
}
});
The vendor may need to enable Cross Origin Resource Sharing on their end from your domain.

Here is a working example of the jQuery Ajax call:
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
dataType:'json',
success: function (resp) {
console.log(resp)
var names = resp.title
$('#summary').html(names);
},
error: function (resp) {
console.log('error')
}
});
You can edit this to match your data. Make sure that the url is correct, you can try:
'./json/data.json'
You JSON is parsed correctly according to: https://jsonlint.com/
So it must be the URL.

Related

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

Parameter shown as "0:" in ajax request

var frm = $('#updateStickyForm');
frm.submit(function (e) {
var id = "{{note.id}}"
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data:
frm.serialize() + '&' + $.param(id),
success: function (data) {
console.log('Submission was successful.');
$('#test').show();
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
When I look at the network logs in Chrome the parameter is shown as "0:". I'm able to access the parameter just fine with Django and do what I want to do with it, I just want to know how I can change it from "0" to something of my choosing.
id seems to have a key 0 for the value you want to post, you can construct an object to pass to $.param with the key you want
frm.serialize() + '&' + $.param({"myid":id['0']}),

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Doing POST with AJAX returns "Response for preflight is invalid (redirect)"

I am getting a "Response for preflight is invalid (redirect)" everytime I try to execute a POST with AJAX into my webservice. I have downloaded a CORS plug in for my browser and I am able to execute a 'GET' request with it.
$(function(){
var $name = $("#nameTxtB");
var $order = $("#orderTxtB");
var $price = $("#priceTxtB");
var $link = "http://localhost:51834/CoffeeService.svc/addorder";
$("#addButton").on('click', function(){
var $try1 = $price.val();
var $parse = parseInt($try1);
console.log($parse);
var CoffeeOrders = {
Name: $name.val(),
Order: $order.val(),
Price: $parse,
};
console.log(CoffeeOrders);
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : 'json',
type: 'POST',
url: $link,
data: CoffeeOrders,
success: function(){
alert("Order was sucessfully created!");
},
error: function(){
alert("Something went wrong!");
}
});
});
});
The server needs to actually implement the CORS-preflight protocol if you want to make complicated requests like that. It's explained in the standard: https://fetch.spec.whatwg.org/#http-cors-protocol.

Ajax success: function(data) is undefined

Edit: could've researched better... reading this post now: How do I return the response from an asynchronous call?
I have an ajax request which returns JSON data. When I watch it in fiddler, it does go out to the service and get the JSON data, but when I try to set a variable to it's response, that variable is "undefined". If I alert in the success method, it alerts, but the variable is still undefined.
I tried changing the function(data) to function(something) incase that had anything to do with it... same story.
var returndata
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
returndata = data; //undefined
alert('haaalp');
}
});
The JSON is like below
[
{
"DelegateSid":null,
"DisplayName":"Tom",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Tim",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Jake",
"HasDelegation":true,
"HasEtaManagement":false
},
{
"DelegateSid":null,
"DisplayName":"Ryan",
"HasDelegation":true,
"HasEtaManagement":false
}
]
Try:
var returndata;
$.ajax({
type: "GET",
url: "GetSecurables/",
data: { etaNumber: etaNumber },
success: function (data) {
console.log(data);
returndata = data;
console.log(returndata);
}
});
If the 2 outputs are the same it might be the case that you're trying to access returndata from outside its scope, hence the undefined, or that you're accessing returndata before the Ajax call completes.

Resources