I am trying to parse Bing Search API Version 7 JSON using the following code, but not sure what I am doing wrong. Would like to parse "name" and "url", my code is below.
Bing JSON Results are at the following URL -> http://52.15.219.114/bing2.php?q=freebsd&s=10&p=0&m=en-us
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
len = data.webPages.value.length
for (i=0; i<len; i++ ){
results += "<p><a href='" + data.webPages.value[i].url + "'>" + data.webPages.value[i].name + "</a>: " + data.webPages.value[i].snippet + "</p>";
}
$("#bookout").html(results);
},
error: function() {
// console.log(data);
}
});
Below is a fix for parsing the Bing Search JSON API.
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
var obj = JSON.parse(data)
var ocean = obj.webPages.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].name);
//FORMAT RESULTS
var ocean_format = '<div><div>' + '' + ocean[i].name + '</div><div>' + ocean[i].snippet + '</div><div class="text-secondary">' + ocean[i].displayUrl + '</div></div>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
},
error: function() {
// console.log(data);
}
});
Related
I have written code in an ASP.NET Core 6 controller and calling this from view. This code gives response to my view but I don't know how to parse the data in view.
Previously I was using JsonrequestBehaviour.Allowget which is now deprecated in .NET 6. Please help me for better appraoch of json call which can return any dynamic object.
Here is my controller code:
public IActionResult GetAccountLevelAndCode(Int32 GroupAccountID, Int32 Companyid)
{
string AccountLevels = ""; string Returnerror; string ReturnBranches;
DataTable AL = new GetDataClass().GetAccountNoAndAndLevels(GroupAccountID, Companyid, out Returnerror);
//a = (GLChartOFAccountModel)AL.Rows[0].ConvertDataRowToObject(a);
string Sql = #"select cab.BranchID from GLChartOFAccount ca inner join GLChartOfAccountBranchDetail cab on ca.GLCAID=cab.GLCAID where cab.GLCAID=" + GroupAccountID;
DataTable dt = new DataTable();
dt = StaticClass.SelectAll(Sql).Tables[0];
AccountLevels = JsonConvert.SerializeObject(AL);
ReturnBranches = JsonConvert.SerializeObject(dt);
Returnerror = JsonConvert.SerializeObject(Returnerror);
return Json(new { AccountLevels, ReturnBranches, Returnerror });
}
Following is my view call and response allocation:
function GetAccountNoandLevel() {
var DATA={"GroupAccountID" : $('#isParent').val(), Companyid : #Model.CompanyID }
var execCode = true;
$.ajax({
async: false,
type: "POST",
url: "/GLChartOFAccount/GetAccountLevelAndCode",
data: DATA,
dataType: "json",
success: function (data) {
try {
var c = JSON.parse(data.AccountLevels)
var b = JSON.parse(data.ReturnBranches)
var er = JSON.parse(data.Returnerror)
if (b.length>0) {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = true;
});
var dataarray = '';
for (var i = 0; i < b.length; i++) {
dataarray += b[i]["BranchID"] + ',';
}
dataarray = dataarray.replace(/,\s*$/, "");
var data = dataarray.split(",");
$("#BrachIDs").val(data);
$("#BrachIDs").change();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$("#BrachIDs option").filter("[value='" + data[i] + "']").attr('disabled', false);
}
}
}
else {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = false;
});
$("#BrachIDs option:selected").removeAttr("selected");
}
if (ShowErrorOK(er)) {
$('#GLCode').val('');
}else{
RowToFillValues(c)
}
} catch (e) {
//console.log(e + " GetAccountNoandLevel "); document.getElementById("DisplayErrorMessage").innerText = e.message; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log(e + " GetAccountNoandLevel "); console.log(e.message)
}
},
error: function (err) {
//console.log(err.responseText); document.getElementById("DisplayErrorMessage").innerText = "AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details"; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log("AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details")
}
});
if (execCode) {
}
}
The response data is showing undefined...
you don't need serialize and parse manually, it will be done automaticaly
return new JsonResult(new { AccountLevels=AL, ReturnBranches=dt, Returnerror= Returnerror });
and ajax
var c = data.AccountLevels;
var b = data.ReturnBranches;
var er = data.Returnerror;
I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>
I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});
I have a json array:
[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]
My code is :
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, value) {
items.push("<tr>");
items.push("<td id=''" + key + "''>" + value.value+ < /td>");
items.push("<td id=''" + key + "''>" + total of values + < /td>");
items.push("</tr>");
});
}
});
I want to calculate the values, how to do with that?
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType:'json',
success: function(data){
var items = [];
var totalOfValue = 0;
$.each(data,function(key,value){
totalOfValue = totalOfValue + parseInt(value.value);
});
$.each(data,function(key,value){
items.push("<tr>");
items.push("<td id='" +key+ "'>" + value.value+</td>");
items.push("<td id='" +key+ "'>" + totalOfValue +</td>");
items.push("</tr>");
});
}
}
);
A simple way is to use the reduce method:
Something like this:
var total = arr.reduce(function(t, v) {
return t += Number(v.value);
}, 0);
I have some files downloaded and I wanna push them to a server. Every time I try to push the file I get the error
Error: Can't set headers after they are sent.
I have a for loop that reads all the files and parse them and after that I want to send them to the server one by one.
app.get('/dataparser', function(req, res) {
var fs = require('fs');
var obj;
var jsonGis = new Array();
var jsonArray;
var filePaths = [];
const downloadFolder = './sampletest/';
var mtimes = {};
var reloadTimes = 10000;
fs.readdir(downloadFolder, (err, files) => {
files.forEach(file => {
filePaths.push("sampletest/" + file);
});
})
var execFunction = function() {
for (var i = 0; i < filePaths.length; i++) {
parseFile(filePaths[i], mtimes[filePaths[i]]);
}
};
execFunction();
setInterval(execFunction, reloadTimes);
function parseFile(fileName, lastModifiedTime) {
fs.stat(fileName, function(err, fd) {
for (var i=0, len = filePaths.length; i<len; i++) {
if (fd.mtime !== lastModifiedTime) {
mtimes[fileName] = fd.mtime;
fs.readFile(filePaths[i], function(err, data) {
if (err) {
return console.error(err);
}
obj = JSON.parse(data);
jsonGis.push('"Person1"');
jsonGis.push('"' + obj.pages[1].answers[2].values[0] + '"');
jsonGis.push('"person2"');
jsonGis.push('"' + obj.pages[1].answers[0].values[0] + '"');
jsonGis.push('"codewals"');
jsonGis.push('"42343GSDS"');
jsonGis.push('"geometry":{');
jsonGis.push('"x":' + obj.pages[1].answers[4].values[0].coordinates.latitude + ',');
jsonGis.push('"y":' + obj.pages[1].answers[4].values[0].coordinates.longitude);
var str = "[{ " + jsonGis[0] + jsonGis[1] + jsonGis[2] + ": " + jsonGis[3] + "," + jsonGis[4] + ": " + jsonGis[16] + "}}]"
//pushing to the server
console.log("check here");
console.log(str);
var qs = require("querystring");
var http = require("http");
var options = {
"method": "POST",
"hostname": "twst2.gtw.com",
"port": null,
"path": "localpath/",
"headers": {
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(qs.stringify({features: str}));
res.send("The server was updated");
req.end();
});
}
}
});
};
Just need to send the data to the server from file1.json and then file2.json then file3.json and so on.
Try creating a separate callback function that includes .write, .send, and .end, then let it be the callback for .request.