How do I protect jQuery.get url? - javascript

Hi i just want to protect my jQuery.get url (data.php) if any chance to make jQuery.get in class or any else?
my code here here
jQuery.get('data.php', null, function(data) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
data = data.split(/\n/g);
jQuery.each(data, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
});
} catch (e) { }
/// options.series[0].data = traffic;
//$res = traffic;
});
and i want to protect the url of data.php
ps: data.php is my side trafic from sql snd im using for highcharts so the the call for hightcharts is
series: [{
name: 'Stats',
data: traffic
Thanks in advance anyone!

Related

Vis.js network: how to get data and options back for saving?

My intention is to create simple graph editor using vis.js and the first feature I'm thinking about is to position nodes manually and save that. However, unlike setting options a straight-forward method to get all the options doesn't seem to exist. Is there any reasonable approach to get them (aside trying to track all the changes using events like dragEnd which sounds way too fragile)?
In fact, I'm looking for a way to extract both data (nodes/edges and their settings) and options so that once the network is rendered using those options, it looks the same (or at least similar) to what was saved.
Vis.js provides a simple example to export and import networks as JSON.
There is also an example with basic Editor-functionality like adding/removing nodes and edges
I've created my js functions to get all options.
For example if I would get the group of each node id:
function getGroup(network, id){
var group = network.body.data.nodes._data[id].group;
return group;
}
UPDATE: I don't have a single function to get all options, but for ex. you can get few options value with this function:
function getOptions(network){
var opt = network.options;
return opt;
}
function getLocale(network){
var locale = getOptions(network).locale;
}
function getClickToUse(network){
var clickToUse = getOptions(network).clickToUse;
}
In my case I don't need the global options, as for saving the data here is what I did:
async function saveJSON() {
// For all nodes:
var str = "{\"nodes\":[";
var ns = nodes._data;
ns.forEach(function(n) {
str += JSON.stringify(n);
str += ",";
});
str = str.slice(0,-1) + "],";
// For all edges:
str += "\"edges\":[";
var es = edges._data;
es.forEach(function(e) {
delete e['id'];
str += JSON.stringify(e);
str += ",";
});
str = str.slice(0,-1) + "]}";
console.log($.ajax({
method: "POST",
url: "network.json",
data: str,
success: function(resp) {}
}));
}
As for loading it's like this:
async function loadJSON() {
$.ajax({
method: "GET",
url: "network.json",
cache: false,
success: function(data0) {
network.destroy();
// data0 seems already parsed as JSON by the server
// No need to do: var data1 = JSON.parse(data0);
// console.log(data0);
nodes = new vis.DataSet(data0.nodes);
edges = new vis.DataSet(data0.edges);
data.nodes = nodes;
data.edges = edges;
network = new vis.Network(container, data, options);
} });
}

Make Ajax call to Express server to retrieve dictionary

I have a dictionary on my server that is set up by Express. I pushed the dictionary, chunks, to the server using the app.get() function and set the url to /search.
Here is that code:
app.get('/search', function (req, res) {
var queryString = req.query.query
console.log(queryString)
var results = Object.keys(index).reduce(function(a, b) {
if (b.toLowerCase() === queryString.toLowerCase()) {
return a.concat(index[b]);
} else {
console.log("error")
}
return a;
}, []);
******
var num_chunks = Math.round(results.length/12)
var chunks = []
for (var i=0; i<num_chunks; i++) {
var j = 12*i
var sliced = results.slice(j, j+12)
chunks.push({
key: Math.floor((Math.random() * 100000000000000000000) + 1),
value: sliced
})
}
******
res.header("Content-Type",'application/json');
res.json(results);
});
Now on the client side of my website, I want to retrieve chunks and interact with the contents of it. Could anyone tell me how I would implement an Ajax/jQuery call to get the dictionary and then reference it in my client side code?
Here is what my ajax function looks like right now, but it is missing the key elements:
$.ajax({
url: '/search',
data: _needs to be filled in_,
success: _needs to be filled in_,
dataType: "json"
});
Any help would be immensely appreciated. Thanks so much in advance.
Cheers, Theo

Can't connect to web service by JQuery

I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .
I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

Connecting New York Times API JSON data to display in HTML

I'm working on the API project now in javascript, and I have not been able to find any answers for how to place the json data from the New York Times API into my html. I have successfully linked to the NYT API.
In the js below, the findSearch() function successfully gets the data from the NY site, but when I use the $.each() to call to the showData(i, result) function, the data comes back as undefined.
I can see that the data is making it’s way up to this function because of a console.log() I did in the showData() function, but I think I am calling the json data incorrectly.
To see the entire project (it’s not the big; don't worry), you can go here.
var showData = function (i, result) {
var template = $(".results .template .searchDisplay").clone();
var headline = template.find('.headline');
headline.text(result.response.docs.headline);
var abstract = template.find('.abstract');
abstract.text(result.response.docs.abstract);
var snippet = template.find('.snippet');
snippet.text(result.response.docs.snippet);
var url = template.find('.url');
url.text(result.response.docs.url);
console.log(result)
console.log(result.response.docs.headline)
$('.searchDisplay').show('fast');
return result;
};
// THIS FUNCTION CALLS OUT TO THE NYT API, GETS DATA
var findSearch = function(search){
var request = {tagged: search,
site: 'New York Times',
order: 'decs',
sort: 'creation'};
var result = $.ajax({
url: 'http://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + search + '&fq=source:("The New York Times")&page=0&sort=oldest&api-key=a1eeb62c8df499298c449983e6967154:3:69423736',
type: 'GET',
dataType: 'json',
data: search,
})
.done(function(result) {
console.log("success");
console.log(result.response);
var searchResults = showSearchData(request.tagged, result.response.docs.length );
$('.info').html(searchResults);
$.each(result.response.docs, function(i, item) {
var showing = showData(item, result);
$('.searchDisplay').append(showing);
});
}).fail(function() {
console.log("error");
$('.results').html('This feature is not working. :-(');
});

Categories