I'm having some issues trying to send and receive parameters in javascript and Ajax. I´m sending to /api/getHighScores and that function requires a timestamp for input and the output is a json-file with user information and a value, the highscore. When I receive the response, I want it to print in my Chrome plugin as well.
This is the code right now.
data = {
"startTime": JSON.stringify(1490208166633),
}
function getHighscores() {
$("#knapp2").click(function() {
$.ajax({
type:"GET",
url: "/api/getHighscores",
data:[startTime=1490208166633],
success: function (response){}
});
});
}
{
"manifest_version": 2,
"version": "1.1",
"browser_action": {
"default_icon": "resources/img/clock-icon-png-10763.png",
"default_popup": "popup/popup.html"
},
"background": {
"scripts": ["background/background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/"
]
}
I've made a few assumptions here about your API structure but this is what I would expect to be.
Typically the
api/getHighScores
endpoint would get all the high scores independent of the time stamp variable.
var data = { startTime: 1490208166633 };
var userInfomation;
$("#knapp2").click(function() {
$.ajax({
type:"GET",
url: "/api/getHighscores/" + data.startTime,
success: function (userInfo)
{
userInfomation = userInfo;
}
error: function (response)
{
// you should deal with the error case as well
// it could give you more information about whats going wrong.
}
});
});
function getHighscores() {
$("#knapp2").trigger("click");
}
If you are actually sending data under a GET method.
var data = { startTime: 1490208166633 };
var userInfomation;
$("#knapp2").click(function() {
$.ajax({
type:"GET",
url: "/api/getHighscores",
data: JSON.stringify(data);
success: function (userInfo)
{
userInfomation = userInfo;
}
});
});
Related
I need to load a datatable with a JSON dataset. I don't want to do server side processing. but I do want to retrieve the full set of data from a URL. I got to the point where there's no error on load but for some reason, the table stays empty with 0 results.
I am building the JSON on the server side like this:
public static function datatableOutput($array){
foreach($array as $key=>$line){
$output[] = [
"href"=>$line['href'],
"code"=>$line['code'],
"time"=>$line['time'],
"img_count"=>$line['img_count'],
"int_count"=>$line['int_count'],
"ext_count"=>$line['ext_count']
];
}
return array('data'=> $output);
}
Later in the code it returns a json string like this:
return response()->json($this::datatableOutput($links));
And in the view my script looks like this:
$.ajax({
url: '/crawl',
type: "post",
data: {
url: $("#url").val(),
pages: $("#pages").val(),
_token:"{{ csrf_token() }}"
},
dataType : 'json',
success: function(data){
// Done state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#crawl').hide();
$('#report_section').show();
$('#report').DataTable( {
data: data,
columns: [
{ title: "href" },
{ title: "code" },
{ title: "time" },
{ title: "img_count" },
{ title: "int_count" },
{ title: "ext_count" }
]
} );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Error state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#goaheaddude').show();
$('#error').show();
}
});
The JSON data set returned looks like this:
{
"data":[
{
"href":"\/",
"code":200,
"time":0.2746608257293701,
"img_count":6,
"int_count":204,
"ext_count":6
},
{
"href":"\/feature\/automated-marketing-reports",
"code":200,
"time":0.1753251552581787,
"img_count":7,
"int_count":72,
"ext_count":6
},
{
"href":"\/feature\/marketing-dashboard-2",
"code":200,
"time":0.15781521797180176,
"img_count":8,
"int_count":73,
"ext_count":6
}
]
}
Everything seems to be valid but for some reason I still get 0 results ... I am probably missing something obvious thought. I tried the JSON with and with out the "data" array.
Whe are busy building a web based app. And we inherited the code where the previous developers used jstree so now the whole site consist out of a tree that uses jstree.
Everything worked even the search on the tree, but then we came across a problem where certain tabs loaded too long because of the tree which was too big.
So we went and made the the tree async / lazy loading which works perfectly but know the problem is that the search doesn't work that well.
Because we made a api for the search which works but it doesn't do the call back after new tree has been loaded.
Can someone help because I've been struggling for 3 days now and its giving me a head ache.
// Tree Search
searchAjaxFunction: function () {
var TreeCustomApiRequest = {
nTreeCustomDesc: document.getElementById("tree_search").value,
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: 'api/TreeCustomSearch.aspx',
success: function (jsonData)
{
Tree.dataJson = jsonData;
// Clear the tree.
//Tree.dataJson = jsonData;
if ($("#tree").jstree()) {
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
$('#tree').jstree(true).refresh();
}
},
contentType: "application/json"
});
},
onClickFunctionNode: function(node) {
Tree.treeDivIdSelector.jstree(true).toggle_node(node);
},
pluginsArray: ["search", "checkbox", "types", "json_data","html_data"],
treeMenuContextItems: {},
Init: function(initData) {
Tree.dataJson = initData.dataJson;
Tree.treeDivIdSelector = initData.chartDivId;
Tree.searchDivIdSelector = initData.searchDivId;
var apiUriTree = 'api/TreeCustomChildren.aspx';
Tree.treeDivIdSelector.jstree({
"checkbox": {
"keep_selected_style": true,
"three_state": false
},
"plugins": Tree.pluginsArray,
'core': {
'data': function (node, cb) {
// Fetch tree custom parent nodes
if (node.id === "#") {
cb(Tree.dataJson);
}
else {
var _cb = cb;
//Fetch tree custom Child nodes
var TreeCustomApiRequest = {
nUserId: document.getElementById("TrendUserID").value,
nAccessLevel: document.getElementById("hfTrendAccessLevel").value,
nTreeCustomParentId: node.id
}
function recieveData(data) {
cb(data);
}
$.ajax({
type: "POST",
data: JSON.stringify(TreeCustomApiRequest),
url: apiUriTree,
success: recieveData,
contentType: "application/json"
});
}
},
"themes": {
"icons": false
}
},
"contextmenu": {
items: Tree.pluginsArray.indexOf("contextmenu") > -1 ? Tree.treeMenuContextItems : null
}
});
var tree = Tree.treeDivIdSelector.jstree();
function getNode(sNodeID) {
return tree.get_node(sNodeID);
}
Tree.treeDivIdSelector.on('click', '.jstree-anchor', function(e) {
Tree.onClickFunctionNode(this);
}
);
//Tree.searchDivIdSelector.keyup(Tree.searchFunction);
},
The next code is in the client side......
<script type="text/javascript">
$(document).ready(function () {
var dataJson = <%=sTreeViewJson%>
Tree.Init({ dataJson: dataJson, chartDivId: $("#tree") });
$("#btnSearch").click(function () {
// Do the Ajax search
Tree.searchAjaxFunction();
//var value = document.getElementById("tree_search").value;
//Tree.searchFunction();
})
});
</script>
Thank you Nikolay, it was a stupid mistake from me so what I added was just this to my code:
success: function (jsonData, callback )
{
//Goes back to the Callback with the new search data
Tree.Init({ dataJson: jsonData, chartDivId: $("#tree"), searchDivId: $("#tree_search") });
$('#tree').jstree(true).refresh();
}
So I removed the
$('#tree').jstree(true).settings.core.data = jsonData;
$('#tree').jstree(true).deselect_node(this);
$('#tree').jstree(true).toggle_node(this);
Know it gets my data and refreshes the table with the init function while it has my new data.
Hope this also may help someone = ).
First time using the site to ask a question. I'm new to Chrome Extensions so I'm sure I'm making some stupid mistake. I apologize in advance.
I'm trying to grab the current tab's url and POST it to a URL that will then recieve it and push it into a database. Like my own personal bookmarking service. I've debuged as much as I can, the data is making it all the way to where i'm sending my XHR request.. but the data doesn't come out when I echo it on my server side script. I'm confirming that it's hitting my URL because i'm console logging the output... but again no data is being passed.
BACKGROUND.JS
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.open(method, request.url, true);
xhttp.send(request.data);
xhttp.onload = function() {
callback(xhttp.responseText);
};
return true
}
});
MANIFEST.json
{
"name": "bookmarker",
"version": "0.0.1",
"manifest_version": 2,
"description": "POSTIN BOOKMARKS!",
"homepage_url": "URL",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": [
"contentSettings",
"cookies",
"tabs",
"geolocation",
"http://*/*"
],
"content_scripts": [
{
"js": ["contentscript.js"],
"matches": ["http://*/*"]
}
],
"browser_action": {
"default_icon": "icons/icon16.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
MAIN.JS
jQuery(function() {
jQuery('.reminded').on('click', function(e){
e.preventDefault();
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var url = tabs[0].url,
date = 1391048414,
clientId = 1234
chrome.runtime.sendMessage({
method: "POST",
action: "xhttp",
url: "http://www.API.com/endpoint",
data: {url: url, date: date, clientId: clientId}
}, function(responseText) {
console.log(responseText);
});
});
});
});
Thank you very much in advance for any light anyone can share.
You didn't mention where "main.js" was used, but I guess that it's used in the popup page, right? The popup page can also make cross-domain requests in a Chrome extension when you've declared the permissions in the manifest file. So, just use jQuery.ajax directly to make the cross-domain request:
jQuery.ajax({
type: "POST",
url: "http://www.API.com/endpoint",
data: {url: url, date: date, clientId: clientId},
success: function(data) {
console.log(data);
}
});
For the record, the code in your question is failing because you're trying to submit a JavaScript Object ({url: url, date: date, clientId: clientId} via the .send method of a XMLHttpRequest. This makes no sense, and your server would receive the string [object Object] because of the default serialization of objects.
To get your original code to work, you should use jQuery.param to serialize the form data and xhttp.setRequestHeader("Content-Type", "application/x-www-form-url-encoded");.
Is there a more efficient way to write the following? I need to loop through objList and pass the UnqKey to wfrmPrint. On success of that I then have to loop though the Pages. I am looping through the pages and unqkeys by passing a integer and checking to see if it is less than the length. I tried to use .when.apply taken from http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects, but it was loading the unqkeys and then the pages.
//sample objList
[
{
"UnqKey": 1,
"Pages": [
"wfrmSet1Page1.aspx",
"wfrmSet1Page2.aspx"
]
},
{
"UnqKey": 2,
"Pages": [
"wfrmSet2Page1.aspx",
"wfrmSet2Page2.aspx",
"wfrmSet3Page2.aspx",
"wfrmSet4Page2.aspx"
]
}
]
function Loop(iListIndex) {
var obj = objList[iListIndex];
if (iListIndex < objList.length) {
jQuery.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + obj.UnqKey, //load session that is used in wfrmSet1Pages.. or wfrmSet2Pages..
success: function () {
AddPages(obj, iListIndex, 0);
}
})
} else {
alert('Done');
}
}
function AddPages(obj, iListIndex, iPageIndex) {
if (iPageIndex < obj.Pages.length) {
jQuery.ajax({
type: "GET",
url: obj.Pages[iPageIndex] + '?Print=1', //load html
async: true,
success: function (html) {
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
},
error: function () {
alert('Failed!');
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
}
});
} else {
iListIndex++
Loop(iListIndex);
}
}
You might be able to do something like this,
function getData(arr,arrindex) {
$.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + arr[arrindex].UnqKey
}).then(function(data){
var deferredObj = $.Deferred(), defArr = $.map(arr[arrindex].Pages,function(page){
return $.ajax({type: "GET", url: page + '?Print=1'});
});
$.when.apply(null,defArr).done(deferredObj.resolveWith).fail(deferredObj.resolveWith);
return deferredObj.promise();
}).done(function(){
arrindex++;
if (arr[arrindex]) {
getData(arr,arrindex);
}
else {
alert("done!");
}
}).fail(function(){
alert("FAIL!");
});
}
getData(objList,0);
It gets each wfrm sequentially, and when each one finishes, requests all of the pages for that one at once. Somewhat of a combination between your loop and a deferred $.when
Edit: fixed $.map argument order
the post title may not explain fully, but here is what I am hoping to do: I have my JavaScript code in a separate file, and I have it arranged like so
var PK = {
"vars" : {
"uris" : {
"app1": "http://this/server/",
"app2": "http://that/server/"
},
"something": {
"objects": [],
"obj1": { "url": PK.vars.uris.app1 },
"obj2": { "url": PK.vars.uris.app2 }
}
},
"methods" : {
"doThis" : function(a) {
$.ajax({
url: PK.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
},
"doThat" : function(a) {
$.ajax({
url: PK.vars.uris.app2,
data: data,
type: "GET",
success: function(data) { .. do something else .. }
});
},
"init" : function(position) {
if (position) { PK.methods.doThis();
}
else {
PK.methods.doThat();
}
}
}
};
and then, in my html, I have the following
$(document).ready(function() {
PK.vars.uris.app1 = "[% app1 %]";
PK.vars.uris.app2 = "[% app2 %]";
PK.methods.init();
});
where the values of app1 and app2 are sent from the server based on a config file. Except, it doesn't work as expected, because, when the separate JavaScript loads, PK.vars.uris is not defined at that time. Of course, everything works beautifully if I have PK.vars.uris{} hardcoded.
How can I delay the evaluation of var PK until after the document has loaded and PK.vars.uris is available to be used in the JavaScript code?
Is the problem that you need to pass values into an initialiser?
How's this approach:
In your external file:
function PK_Constructor(app1Uri, app2Uri) {
this.vars = { "uris" : {
"app1" : app1Uri,
"app2" : app2Uri
},
"something": {
"objects": [],
"obj1": { "url": app1Uri },
"obj2": { "url": app1Uri }
},
};
this.doThis = function(a) {
$.ajax({
url: this.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
// etc
}
And in you HTML:
// Ensuring PK has global scope
var PK = undefined;
$(document).ready(function() {
PK = new PK_Constructor("[% app1 %]", "[% app2 %]");
});