Ajax call in Chrome extension not working - ajax

Trying to send an ajax request in a chrome extension. I have confirmed the request returns a 200 response, it should just console.log to 'test'. I'm not sure if there's some async problems here? I have read chrome extension 'addListener' documentation.
content.js
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell); //this is not working
return true;
});
background.js
require('./modules/communicate.js');
var communicate = new Communicate();
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting === "hello") {
response = communicate.talk('http://127.0.0.1:5000/test', 'GET');
sendResponse({
farewell: response
});
return true; //doing this correctly?
}
});
communicate.js
Communicate = function() {
this.talk = function(url, method) {
$.ajax({
url: url,
method: method,
success: function(result) {
return result;
}
});
};
};
manifest.json
{
"manifest_version": 2,
"icons": { "128": "images/icon.png" },
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "html/popup.html"
},
"background": { "scripts": ["js/background.js"] },
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "js/content.js" ]
}],
"permissions": [ "<all_urls>" ],
"web_accessible_resources": [ "js/*", "html/*", "css/*", "images/*" ],
"content_security_policy": "script-src 'self'; object-src 'self'"
}

Related

Combobox using Sencha Architect

I been trying to load datas from elasticsearch into combobox but unsuccessfully, however load datas from json file to combobox it work.
the only different that is that load data from the store on json file, it successfully loaded the data, but when for elasticsearch, it reply '400: Bad Request'
[Json File]
[
{
"index":"color",
"_type":"_doc",
"_id":1,
"_score":1.0,
"_source":
{
"name":"Red"
}
},
{
"index":"color",
"_type":"_doc",
"_id":2,
"_score":1.0,
"_source":
{
"name":"Blue"
}
}
]
[ElasticSearch Json Reply]
{
"took":3,
"timed_out":false,
"_shards":
{
"total":1,
"successful":1,
"skipped":0,
"failed":0
},
"hits":{
"total":{
"value":4,
"relation":"eq"
},
"max_score":1.0,
"hits":[
{
"_index":"color",
"_type":"_doc",
"_id":1,
"_score":1.0,
"_source":{
"name":"Red"
}
},
{
"_index":"color",
"_type":"_doc",
"_id":2,
"_score":1.0,
"_source":{
"name":"Blue"
}
},
{
"_index":"color",
"_type":"_doc",
"_id":3,
"_score":1.0,
"_source":{
"name":"Green"
}
},
{
"_index":"color",
"_type":"_doc",
"_id":4,
"_score":1.0,
"_source":{
"name":"Yellow"
}
}
]
}
}
My Model Code
Ext.define('MyApp.model.ColorModel',{
extend: 'Ext.data.Model',
alias: 'model.colormodel,
requires: [
'Ext.data.field.String',
'Ext.data.field.Integer'
],
fields: [
{
type:'string',
name:'_index'
},
{
type:'string',
name:'_type'
},
{
type:'string',
name:'_id'
},
{
type:'int',
name:'_score'
},
{
name:'_source'
},
]
});
My Store Code [Json File- That Work]
Ext.define('MyApp.store.ColorStore',{
extend: 'Ext.data.Store",
requires: [
'MyApp.model.ColorModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cgf || {};
me.callParent([Ext.apply({
storeId:'ColorStore',
model:'MyApp.model.ColorModel',
proxy: {
type:'ajax',
url: 'http://localhost:8888/data/color.json,
withCredentials:true,
reader: {
type:'json'
}
}
}, cfg)]);
}
});
[My Another Store that retrieve from elasticsearch] - not working
Ext.define('MyApp.store.ESColorStore',{
extend: 'Ext.data.Store",
requires: [
'MyApp.model.ColorModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cgf || {};
me.callParent([Ext.apply({
storeId:'ESColorStore',
model:'MyApp.model.ColorModel',
proxy: me.processMyAjaxProxy1({
type:'ajax',
read: function(operation, callback, scope){
var request = this.bulidRequest(operation, callback,scope);
var query = {
"from": operation.params.from,
"size": operation.params.size,
"query": {
"query_string" : { }
},
"sort": [
{
"name.raw":{
"order": "asc"
}
}
]
};
Ext.apply(request, {
headers: this.headers,
timeout: this.timeout,
scope: this,
callback: this.createRequestCallback(request,operation,callback,scope),
method: 'POST',
params: operation.params,
jsonData: query,
disableCaching:true,
success: function(rec) {
console.log('[ESColorStore], successfully retrieved query: ' + rec.responseText);
}
failure: function(rec) {
console.log('[ESColorStore], failed retrieved query: ' + rec.responseText);
}
});
Ext.Ajax.request(request);
return request;
},
reader: {
type:'json'
}
}
}, cfg)]);
},
proccessMyAjaxProxy1: function(config) {
config.api = {
read: 'http://localhost:9200/color/_search'
};
config.url = 'http://localhost:9200/color/';
return config
},
});
[Views]
Ext.define('MyApp.view.MyPanel', {
extend: 'Ext.Panel',
alias: 'widget.mypanel',
requires: [
'MyApp.view.MyPanelViewModel',
'Ext.field.ComboBox'
],
viewModel: {
type: 'mypanel'
},
title: 'My Panel',
items: [
{
xtype:'comobobox',
name:'select-the-color',
width: 419,
docked: 'top',
label:'Select The Color',
autoLoadOnValue: true,
displayField: '_source.name',
selectOnTab:false,
store:'ESColorStore',
valueField:'_source.name',
queryCaching: false,
queryParam:''
}
]
});

ExtJS: How to hide specific data on store with filtering?

I want to hide a record on Grid that returns from server.
I've setted a filter on store and can reach that specific data but how I'll handle to hide/ignore this record?
fooStore: {
....
filters: [
function(item) {
let me = this;
let theRecord = item.data.status === MyApp.STATUS; //true
if (theRecord) {
console.log(theRecord); //True
console.log("So filter is here!!")
//How to hide/ignore/avoid to load this specific data record to load Grid??
}
}
]
},
Returned JSON;
{
"success": true,
"msg": "OK",
"count": 3,
"data": [
{
//Filter achives to this record and aim to hide this one; avoid to load this record.
"id": 102913410,
"status": "P"
},
{
"id": 98713410,
"status": "I"
},
{
"id": 563423410,
"status": "A"
}
]
}
I can't save my fiddle cause i don't have sencha forum's account so i give you my code :
Ext.application({
name : 'Fiddle',
launch : function() {
var model = Ext.create('Ext.data.Model', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'status', type: 'string'},
]
});
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: model,
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
rootProperty: 'data'
}
},
filters: [function(item) {
if (item.data.status === "P") {
return true;
}
else {
return false;
}
}],
listeners: {
load: {
fn: function() {
console.log(this.getRange());
}
}
}
});
}
});
Also i create data.json like this :
{
"success": true,
"msg": "OK",
"count": 3,
"data": [{
"id": 102913410,
"status": "P"
}, {
"id": 98713410,
"status": "I"
}, {
"id": 563423410,
"status": "A"
}]
}
I thinks it's near to you'r code and after the loading of the store the filter work as you can this :
Here is sencha fiddle link : https://fiddle.sencha.com/#view/editor
If this can't work, i don't understand what the fuck doing...

How to extract axios response data into variables?

In routes, I define a route "/ajax/tutorials/unique/images" that returns the below output:
{
"data": [
{
"path": "/images/posts/1474360249_qDhAVF0mA4TnCVUmfcIpkNtvEkyhpV.png"
},
{
"path": "/images/posts/1475575942_ZjuBj3u1rIvxdz1sK0pAuufzY8yjCT.png"
},
{
"path": "/images/posts/1476871481_H63O2o55sBg8Qx1bf6S8wW1M82XXJ1.png"
},
{
"path": "/images/posts/1476896115_JdyLpsxpcfL8kcpUwpFURV963WdeNa.png"
},
{
"path": "/images/posts/1487368925_RSouQqnDiu1ieBGfWStfHlodcptVWA.png"
},
{
"path": "/images/posts/1487368919_iAJUQpd3qx7RTB3ZnMsND0KmjrKrKu.png"
}
],
"paginator": {
"total_count": 15,
"total_pages": 3,
"current_page": 1,
"limit": 6
}
}
I wrote this code in app.js file:
new Vue({
el: '#app',
data: {
images: [],
pagination: [],
},
mounted() {
axios.get('/ajax/tutorials/unique/images')
.then(function (response) {
this.images = response.data.data;
this.pagination = response.data.paginator;
console.log(response.data.data);
console.log(response.data.paginator);
});
}
});
The images and pagination array that I define in app.js don't have any value after running this code, but in the browser console I can see the output:
But Vue doesn't set the response to variables:
When I use arrow function for callback it works, the problem is that I want to set two variable.
new Vue({
el: '#app',
data: {
images: [],
pagination: [],
},
mounted() {
axios.get('/ajax/tutorials/unique/images')
.then(response => this.images = response.data.data);
}
});
Oh I didn't know that, We can use array in arrow function for callback, So I changed code like below, and it's work
axios.get('/ajax/tutorials/unique/images')
.then( response => [
this.images = response.data.data,
this.pagination = response.data.paginator,
]);
You need to return a function from data.
data: function(){
return {
images: [],
pagination: [],
}
}
This is how Vue will observe the images and pagination changes later when you component runs.
You could simply do this:
axios.get('/ajax/tutorials/unique/images')
.then(response => {
this.images = response.data.data
this.pagination = response.data.paginator
console.log(response.data.data)
console.log(response.data.paginator)
})

InvalidPathException: No action config found for the specified url

I am getting below error as Ajax call response.
Below is the response body for Ajax call.
Apache Tomcat/7.0.61 - Error report
HTTP Status 500 - org.apache.struts.chain.commands.InvalidPathException: No action config found for the specified url.type Status reportmessage org.apache.struts.chain.commands.InvalidPathException: No action config found for the specified url.description The server encountered an internal error that prevented it from fulfilling this request.Apache Tomcat/7.0.61
Is it something to do with JRE 7?
Here is the JavaScript code from my JSP file.
I have defined a table in my JSP file which is referenced here.
function showLogHistory() {
var questionId = document.getElementById('txtQuestionId').innerHTML;
var url = "myAction.do?dispatchMethodName=showmyAudit&questionId="+questionId;
if ( $.fn.DataTable.isDataTable('#tblmyAudit') ) {
$('#tblmyAudit').DataTable().destroy();
}
$('#tblmyAudit').DataTable( {
"initComplete": function(settings, json) {
$("#tblmyAudit tbody tr.data-in-table").each(function () {
var i=0;
$(this).find('td').each(function (index) {
var currentCell = $(this);
var nextCell =
$(this).closest('tr').next('tr').find('td').eq(i).length > 0 ?
$(this).closest('tr').next('tr').find('td').eq(i) : null;
if ( currentCell.text() !== nextCell.text()) {
currentCell.css('backgroundColor', 'yellow');
}
i=i+1;
});
});
},
"ajax": {
"url": url,
"cache": true
},
"columns": [
{ "data": "questionId" },
{ "data": "Category" },
{ "data": "Area" },
{ "data": "question" },
{ "data": "answer" },
{ "data": "updated_by" },
{ "data": "updated_date" }
],
"scrollX": true,
"columnDefs": [ {
"targets": [ '_all' ],
"orderable": false
} ],
"createdRow": function( row, data, dataIndex ) {
$(row).addClass( 'data-in-table' );
}
} );
$('#detmyAudit').modal('show');
}
URL that gets generated for Ajax seems proper.

AJAX call doesn't parse JSON

I have the following piece of JSON:
[
{
"number": "0",
"name": "Russell Westbrook",
"attemptedFG": [
{
"x": "333",
"y": "97",
"made": "true",
"assisted": "false"
},
{
"x": "571",
"y": "389",
"made": "true",
"assisted": "false"
}
],
"attemptedFT": [
{
"made": "true"
},
{
"made": "false"
}
],
"rebounds": "5",
"assists": "8",
"steals": "2",
"blocks": "1",
"turnovers": "3",
"fouls": "4"
}
]
and I'm trying to parse it with this AJAX call using ReactJS:
loadStatsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
All the values in the JSON are still stringified after the AJAX call succeeds. The server sends back a response header with 'Content-Type', 'application/json' so I'm not sure why it's not parsing.
Server-side call:
app.get('/stats.json', function(req, res) {
fs.readFile('stats.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
Thanks a bunch.
When you send a stringified json object from server to client, you need to parse that object to readable javascript object. So, you need to parse json in success event of ajax request:
success: function(data) {
var result = $.parseJSON(data);
}
Now result is a javascript readable object.

Resources