I am trying to make an API call and the following errors with Ajax not being a function:
import $ from 'jquery';
const apiCall = function () {
var url = 'https://images.nasa.gov/#/search-results';
var request = {
q: 'sun',
media_type: 'image'
};
var result = $.ajax({
url: url,
dataType: 'json',
data: request,
type: 'GET'
})
.done(function() {
alert(JSON.stringify(result));
})
.fail(function() {
alert('failed');
})
}
module.exports = apiCall;
I am importing the above in another module and calling it on a button click in the react's render() function like:
import apiCall from './../api/apiCall';
class Gallery extends React.Component {
render () {
return (
<section id="gallery" className="g-site-container gallery">
<div className="grid grid--full">
<div className="gallery__intro">
<Button extraClass=""
type="button"
handleButtonClick={apiCall} />
</div>
</div>
</section>
)
}
}
module.exports = Gallery;
Any thoughts with what am I doing wrong?
In my experience, this type of issue is most often because your transpilation is not working as you might expect - or you are transpiling your code while also using jquery (or any other lib) by including it with a CDN link. If this is the case, here's some info that might help you sort it out:
First, check that your transpiler is actually pulling jquery in. Just having it on the page won't necessarily allow this code to work - because when your transpiler operates on:
import $ from 'jquery'
It's going to expect to first load the jquery package from node_modules and then create an internal name for it, such as $_1 which will be used inside your bundle. If you intend to include jquery on the page via CDN, rather than bundling it in this fashion, you need to mark it as external in your webpack or rollup config. If using webpack, it would look something like:
{
entry: '/path/to/your/application.js',
externals: {
'jquery': '$',
}
}
This essentially tells webpack, "when I import from 'jquery', don't look in node_modules - instead, just assume jquery already exists on the page as window.$. Now, webpack won't attempt to include and bundle all of the jquery lib - and instead of creating $_1 it will actually honor what $ is.
If you do intend to load and bundle jquery as part of your build (not recommended, due to the incredible size-bloat it will entail) - I suggest ensuring that it's installed in node_modules. You can do this with:
npm install -S jquery
or, if you're using yarn:
yarn add jquery
Now, your import statement should load the lib correctly when you re-transpile.
First, ensure you're not using jquery-lite as it excludes ajax features.
Btw, it's not recommended to use both exports.module together with ES6's import / export. Try to just use one of them. Not pretty sure, but it may cause some module troubles that hard to understand.
Additionally, based on $.ajax official document, you have to process data in the callback
$.ajax({
url: url,
dataType: 'json',
data: request,
type: 'GET'
})
.done(function(data) {
// Process data provided from callback function
alert(data);
})
.fail(function() {
alert('failed');
})
Personally I do prefer isomorphic-fetch to make ajax call in React application.
Related
New to VueJs. I'm wondering how/where would I make an Ajax call to pull data dynamically down to populate the following Vue table?
https://jsfiddle.net/yyx990803/xkkbfL3L/?utm_source=website&utm_medium=embed&utm_campaign=xkkbfL3L
I've (roughly) modified the example above as follows:
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: []
},
methods: {
fetchUsers: function() {
...
// ajax call using axiom, fetches data into gridData like this:
axios.get('http://localhost/url')
.then(function(response) {
this.gridData = response.data;
})
.catch(function(error) { console.log("error"); })
...
}
},
created: function() {
this.fetchUsers();
}
})
I'm trying to incorporate the ajax pieces from here:
https://jsfiddle.net/chrisvfritz/aomd3y9n/
I've added the fetchUser method which makes the ajax call to pull the data down. I'm able to pull down my data and print it to the console using both fetch and axiom, so I know that part works.
However, my data never appears or updates. The table loads blank. I think it has something to do with me putting the method and created hook on the Vue model object (demo), rather than on the component itself. But I'm not quite sure how to modify the example to resolve it, as the example passes the data in from the parent.
Can someone give me some guidance?
You problem is right over here:
.then(function(response) {
this.gridData = response.data;
})
Within your anonymous function within your then you don't have the context you expect. The most simple solution is adding a .bind(this) to the method.
.then(function(response) {
this.gridData = response.data;
}.bind(this))
By adding it your method body will be aware of the outer context and you can access your components data.
According to the docs and examples, I have perfectly working code that functions great:
Vue.component('admin-competitions-index', {
data: function() {
return {
competitions: []
}
},
mounted() {
this.$http.get('/api/admin/competitions')
.then(response => {
this.competitions = response.data;
});
},
methods: {
/**
* Toggle whether a competition is published or not.
*/
togglePublished(competition) {
Spark.patch(`/api/admin/competitions/togglePublished/${competition.id}`, this.togglePublishedForm)
.then(response => {
competition.is_published = response;
});
}
}
});
However, I'd like to change this code to save the extra request that is made on page load. I don't see a convention anywhere in Laravel or Spark where this is done. I'm guessing that all I need to do is set a JS variable but I'm not sure where it would be proper to do so.
I also understand that this kind of defeats the point of using vue for asynchronous loading, but nevertheless I would like to learn this. I think it will become more useful if I were to use vue for my #show restful requests where even if I wanted everything to load asynchronously I would at the very least have to supply vue with the competition ID that I want loaded.
This works out of the box:
#section('scripts')
<script>
var competition = {!! $competition !!};
</script>
#endsection
So I have this Backbone App where I use Codeigniter for the Backend. For some reason, pushState:true does not work.
So, my main.js of my backbone app has this:
Backbone.history.start({ pushState: true, root: App.ROOT });
My app.js has this:
var App = {
ROOT: '/projects/mdk/'
};
and my navigation module, which renders the menulinks, each item has this:
this.insertView(new ItemView({
model: new Navigation.ItemModel({
href: App.ROOT + 'home',
class: 'home',
triggers: 'home',
route: this.route
})
}));
and the model for it:
Navigation.ItemModel = Backbone.Model.extend({
defaults: {
href: '',
text: '',
triggers: [],
route: ''
}
});
All I get from this is "Page not found"...
Add: When I in the view change it to href:'#news' - it works, but it dont really makes sense...
Anyone who knows the issue here?
From the documentation (http://backbonejs.org/#History):
Note that using real URLs requires your web server to be able to
correctly render those pages, so back-end changes are required as
well. For example, if you have a route of /documents/100, your web
server must be able to serve that page, if the browser visits that URL
directly.
The problem is that your server isn't responding to whatever URL your app is on. For every URL that your Backbone app can reach, your server MUST return a valid HTML page (contianing your Backbone app).
ok I found a solution by myself:
I made this hack:
$(document).on('click', 'a:not([data-bypass])', function (evt) {
var href = $(this).attr('href');
if (href && href.indexOf('#') === 0) {
evt.preventDefault();
Backbone.history.navigate(href, true);
}
});
and then I made:
href: '#home',
That solved the problem, now evereythings runs fluently..
I am creating an MVC3 application, with requireJS. In my views I need to convert the Model object into a knockout viewmodel object. So I need to use knockout and knockout.mapping libraries.
My application is designed in the following way,
1). All the script files are categorized into folders
Scripts/app/home/ - contains the scripts for the views in Home controller.
Scripts/lib/ - contains the scripts like jQuery, knockout,knockout.mapping, requirejs etc
2). In the "_Layout.cshtml" I am referencing "require.js" like this.
<script src="#Url.Content("~/Scripts/lib/require.js")" type="text/javascript"></script>
3). To configure the require.js settings I am using a different script file called "common.js" (Scripts/lib/common.js)
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
ko: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
}
});
4). This is my index.js file which is in 'Scripts/app/home/"
define(['ko', 'komapping'], function (ko, komapping) {
var person = function () {
var self = this;
self.getPersonViewModel = function (data) {
return ko.mapping.fromJS(data); ;
};
};
return { Person: person };
});
5). This is my "Index" action method in the "Home" controller
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "John",
Addresses = new List<Address>(new[]{new Address{Country = "Country 1", City = "City 1"}})
};
return View(person);
}
6). Finally this is my "Index" view
#model MMS.Web.Models.Person
<script type="text/javascript">
require(["/Scripts/common/common.js"], function () {
require(["app/home/index"], function (indexJS) {
var person = new indexJS.Person();
var vm = person.getPersonViewModel(#Html.Raw(Json.Encode(Model)));
});
});
</script>
The problem which I am facing is when loading the index.js file, I get a script error that the knockout.js cannot be loaded.
Failed to load resource: the server responded with a status of 404 (Not Found) - http:///Scripts/knockout.js
But if I remove the dependency of "komapping" inside the "index.js" file it loads correctly, but then I cannot use the mapping functionality.
I had a look inside these links, but couldn't find a solution,
Knockout.js mapping plugin with require.js and
https://github.com/SteveSanderson/knockout.mapping/issues/57
Your help, suggestions are much appreciated. Thanks!
I had the same issue. The problem is that the knockout.mapping defines a knockout dependency, so you need to satisfy this one when you load the script.
Here is how you should load your mapping stuff
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
knockout: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
},
shim: {
komapping: {
deps: ['knockout'],
exports: 'komapping'
}
}
});
Then in my case, I use an index.js file with a requirejs call like the following
requirejs(['jquery', 'knockout', 'komapping'], function($, ko, komapping){
ko.mapping = komapping;
//Do other stuff here
});
I'm writing a sencha touch app using sencha architect. Because my app do lot of ajax request, most of it need to send 'token' in request header for authentication. So I think of create child class base on Ext.Ajax which always has 'token' in request header. Then I can use this child class without care of the header.
MyApp.override.Ajax.request({ ... })
I try define this in app/override/Ajax.js
Ext.define('Myapp.override.Ajax', {
override: 'Ext.Ajax',
headers: {
'token': 'test'
}
});
I also set this as 'requires' in Application. But get error when try to call
Myapp.override.Ajax.request({ ... })
Seem Myapp can not locate .override package (MyApp.override is undifined)
How to let MyApp know override package or what is the correct/best way to do this.
A quick example is very appreciated. Thank you very much.
Update info:
override file location: app\override\Ajax.js
html file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script>
var Ext = Ext || {};
Ext.theme = {
name: "Default"
};
</script>
<script src="sencha-touch-all-debug.js"></script>
<link rel="stylesheet" href="resources/css/sencha-touch.css">
<script src="app/override/Ajax.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>
app.js file
Ext.Loader.setConfig({
});
Ext.application({
requires: [
'MyApp.override.Ajax'
],
views: [
'ContactDetailView'
],
name: 'MyApp'
...
App can start without error, but when call MyApp.override.Ajax.request : Cannot read property 'Ajax' of undefined , mean MyApp.override is undefined
Update
Here something news, it better but not working yet.
Ext.define('MyApp.Ajax', {
extend: 'Ext.data.Connection',
singleton: true,
request: function( options ) {
this.constructor(options, options.url);
console.log(options);
options.header = {'Token':'mytoken'};
this.callParent( options );
}
});
and error when try MyApp.Ajax.request() . I'm sure that options.url is exist in options by check the log
[ERROR][Ext.data.Connection#request] No URL specified
I add extend from constructor function
constructor : function (config, url)
{
config = config || {};
//config.url = 'google.com';
this.initConfig(config);
this.callParent(config);
},
Error just disappear when I remove comment from config.url = 'google.com'; but it comes that the config.url there is ajax request url but local file url ??? I see from chrome console and network ?
GET file:///C:/MyApp/assets/www/google.com?_dc=1370855149720
Please help. thanks.
Finally, this is work with me
Ext.define('MyApp.Ajax', {
extend: 'Ext.data.Connection',
singleton: true,
request: function( options ) {
options.headers = {
Token: 'mytoken',
};
this.callParent( [options] );
}
});
And this simple do what i want too, great.
Ext.Ajax.on('beforerequest', (function(conn, options, eOpts) {
options.headers = {
Token: 'mytoken',
};
}), this);
You don't seem to agree with yourself about the name of your override class:
Myapp.override.Ajax
Lunex.override.Ajax
Myapp.override.data.proxy.Ajax
Which one is it? Pay attention to this, the Loader won't go easy about it...
Anyway, you seem a bit confused about override and extend.
extend does create a new class from the parent class, with the modifications you've specified. Then you can use the class you defined, like you're trying to do.
override, on the other hand, applies the modification to the existing class. In this case, the class name is only used for the require statement, and by the loader. No actual class is created. So, in your example, the namespace MyApp.override is not defined, hence the error. Nevertheless, whenever you use Ext.Ajax, your custom header should be sent. Provided you're manager to load your file, that is ;p
Now, your case is a bit special because Ext.Ajax is a singleton instance of Ext.data.Connection. See its code, there's not much in there. And while overriding a singleton can make sense, extending from it would be disturbing.
So, what you were probably trying to do is that:
Ext.define('Myapp.Ajax', {
extend: 'Ext.data.Connection',
headers: {
'token': 'test'
}
});
So that you can do:
Myapp.Ajax.request({ ... });
Whether the best choice here is to override or to extend is a tough question. I'm glad you didn't ask it!
Why not using the config 'defaultHeaders' in your extended class? In that way it's always added to your headers.
http://docs-origin.sencha.com/touch/2.4.0/apidocs/#!/api/Ext.data.Connection-cfg-defaultHeaders
From the source of Ext.data.Connection
setupHeaders: function(xhr, options, data, params) {
var me = this,
headers = Ext.apply({}, options.headers || {}, me.getDefaultHeaders() || {}),
contentType = me.getDefaultPostHeader(),
jsonData = options.jsonData,
xmlData = options.xmlData,
key,
header;