I am trying to call show function inside Axios request, My Axios request inside another function as shown below:
My Axios request inside Myfunction:
axios({
method: "Get",
timeout: 3000,
headers: {
..................
},
url: "https://XXXXXX/"
})
.then( function(response) {
console.log(response);
//Call function
app.show.bind(response);
})
.catch(function(error) {
console.log(error);
});
And function show is in the method section:
show (workspace_info) {
alert("I am here");
},
but I got an error message:
TypeError: Cannot read property 'bind' of undefined
A very simple method would be to do this:
app.show = function( workspaceInfo ) { // notice the camel case ;)
alert( 'I am here!' );
}
And then bind it to the app like so:
app.show = app.show.bind( this ); // this is something we do a lot in React
Finally, you can use it like:
app.show( response );
Now, remember that you do all the setting up before you actually call the function.
Related
I am currently migrating the use of ajax to the fetch, however I am needing a parameter/function the Ajax native beforeSend: function(). I would like to perform the same action without requiring an implementation in fetch (a creation of a new class for example)
jQuery $.ajax structure:
$.ajax({
url: '...',
type: 'post',
data: {...},
beforeSend: function() {
// perform the action..
},
success: function(response, status, xhr) {
// receive response data
}
});
JavaScript fetch structure:
fetch('...').then((response) => {
return response.text();
}).then((data) => {
console.log(data);
});
How do I determine such a function without needing an implementation or creating a new class on fetch. Is there any means or only implementation? because of my searches I only found implementations like CustomFetch (Is there a beforesend Javascript promise) and others.
Solved problem!
No need to implement and/or create a new fetch class. Using only parameters as "function inside function". I hope you can help others!
function ipGetAddress(format) {
requestFetch = function() {
// perform the action..
console.log('** beforeSend request fetch **');
return fetch.apply(this, arguments);
}
requestFetch(`https://api.ipify.org?format=${format}`).then((response) => {
return response.json();
}).then((data) => {
console.log(data.ip);
});
}
ipGetAddress('json') // return local ip address..
Is there a way to make a function that converts default ajax function.
This is the ajax function i have
$.ajax({
type: "POST",
url: "http://" + document.location.host + '/userajax',
data: 'type=register&name=' + name,
beforeSend:function() {
},
success: function(response) {
}
});
This is what i want it to look like
ajax('url', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
},
success: function(transport) {
}
});
Ive tried to search on the internet but did not find anything
Sure, you can create the function like this:
function ajax(url, params){
// everything is now available here
console.log( url ); // output: http://www.google.com
// you can get the data of the params object like this
console.log( params.method ); // output: get
// you can execute the beforeSend like this:
params.beforeSend();
// additionally you might want to check everything.
// maybe if the method is NOT set, you want it to always use GET
switch(arguments.length) {
case 1: url = throw new Error('Url should be set');
case 2: params.method = 'get';
case 3: break;
default: throw new Error('illegal argument count')
}
}
You would call this like:
ajax('http://www.google.com', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
// some function
},
success: function(transport) {
// some function
}
});
This certainly is possible, it's just a bit of work. Some of the basics you need:
First of all, you need a good understanding of the XMLHTTPRequest API, you can find more info on that on MDN.
Next, finding out how to do a callback, that is actually quite simple, you can pass an anonymous function reference as an option or attribute for a function. That goes like this:
function doSomething(variable, callback){
variable = variable + ' something'; // just doing something with the variable
callback(variable);
}
// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });
You should get an alert that says 'doing something'.
And finally you should know how to read an object, passed as 'options' in the ajax function. Say you have a function like this:
function foo(url, options){
console.log(url);
console.log(options.method);
console.log(options.parameters.name);
}
// call it like this
foo('https://google.com/', {
method: 'get',
parameters: {
name: 'myName'
}
});
That should log the url, method and parameters in the console.
Now from here, you should have all the pieces to put the puzzle together. Good luck!
I don't think so. but you can do this:
$(document).ready(function(){
var parameters = {
name: $("#name").val(),
desc: $("#desc").val()
};
$.ajax({
url: 'path/to/file',
data : parameters,
beforeSend: beforeSubmit,
dataType: "json",
type : 'POST',
})
.done(function(data) {
})
.fail(function() {
console.log("error");
})
})
Also note I don't set the function for the beforeSend directly in the call, I will create an externe function which gives me more freedom.
so I could do this:
function beforeSubmit(){
if(something !== 'somethingelse'){
return false; //ajax call will stop
}else{
return true; //ajax call
}
}
I am using Laravel 4.2.6
This is my function with an ajax call to the controller's method called savesession
function saveActualSession() {
return $.ajax({
url: 'savesession',
data: {
my_username: $('input#username').val()
},
type: 'POST',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
}
In controller I have this:
public function savesession()
{
if(Request::ajax())
{
$my_username = Input::post('my_username');
if ($my_username) { Session::put('my_username', $my_username); }
return $my_username;
}
}
Sessions saving is triggered like this on different places in my javascript code:
saveActualSession()
.done(function(e) {
// Things to be done after saving session
})
.fail(function(e) {
alert('oh no!')
});
The problem is that it's giving me this error in the console:
"NetworkError: 500 Internal Server Error - http://laravelsite.dev/savesession"
It's weird because the url exists 100%, because when I try to do this in the controller:
public function savesession()
{
if(Request::ajax())
{
$my_username = Input::post('my_username');
if ($my_username) { Session::put('my_username', $my_username); }
return $my_username;
}
else
{
print_r("url is working");
die();
}
}
and I access the url directly in my browser like:
http://laravelsite.dev/savesession
It's giving me the print_r message url is not working and it dies.
btw. my routes look like this:
Route::any('savesession', ['as' => 'savesession','uses' => 'RegistrationController#savesession']);
What am I doing wrong?
I have a similar AJAX function for getting sessions and that route works fine and no server errors are shown.
Any idea?
You have a wrong method there. Simply change...
$my_username = Input::post('my_username');
to this...
$my_username = Input::get('my_username');
Get does not refer to the HTTP Method in this context, it refers to what Laravel is doing - get an input value. This value can be GET or POST, it doesn't actually make a difference.
If I have to leverage niceties of jQuery AJAX API and set my own custom settings for each ajax call my app makes like below:
Say I have a page which displays employee information within table by making ajax calls to some API.
define(["jQuery"], function($) {
var infoTable = function (options) {
function init() {
// Provide success callback
options.success_callback = "renderData";
getData();
}
function renderData() {
// This callback function won't be called as it is not
// in global scope and instead $.ajax will try to look
// for function named 'renderData' in global scope.
// How do I pass callbacks defined within requirejs define blocks?
}
function getData() {
$.ajax({
url: options.apiURL,
dataType: options.format,
data: {
format: options.format,
APIKey: options.APIKey,
source: options.source,
sourceData: options.sourceData,
count: options.count,
authMode: options.authMode
},
method: options.method,
jsonpCallback: options.jsonpCallback,
success: options.success_callback,
error: options.error_callback,
timeout: options.timeout
});
}
}
return {
init: init
}
}
How do I achieve this?
I know we can use JSONP request as require calls but that restricts me to using jsonp, making GET requests and all other features $.ajax offers.
This example would let you either use a default success callback, or provide an override, using:
success: options.successCallback || renderData
(The example uses jsfiddle rest URLs - this fact is unimportant, and stripped out the data object to keep the example short)
define("mymodule", ["jquery"], function($) {
function renderData() {
console.log("inside callback");
}
function getData(options) {
$.ajax({
url: options.apiURL,
dataType: options.format,
method: options.method,
jsonpCallback: options.jsonpCallback,
success: options.successCallback || renderData,
error: null,
timeout: options.timeout
});
}
return {
getData: getData
}
});
require(["mymodule"], function(m) {
console.log(m, m.getData({
apiURL: "/echo/json/"
}));
console.log(m, m.getData({
successCallback: function() { console.log("outside callback"); },
apiURL: "/echo/json/"
}));
});
Would print:
GET http://fiddle.jshell.net/echo/json/ 200 OK 263ms
Object { getData=getData()} undefined
GET http://fiddle.jshell.net/echo/json/ 200 OK 160ms
Object { getData=getData()} undefined
inside callback
outside callback
I'm trying to trigger an action after a Javascript object has been created via an AJAX call. My object looks something like this:
function API(uid,accessToken){
$.ajax("path/to/file", {
type: "POST",
data: { user: uid, auth: accessToken },
dataType: "json",
success: function(jsonData) {
arrayname = jsonData[values]
}
});
}
I tried to use JQuery's $.when function to do a callback after the object setup is complete (ie. the array is populated with the ajax response), which looked like this:
$.when( API = new API(uid, accessToken) ).then(function() {
...success function...
});
...but the $.when function triggers with the arrayname values still undefined. From the function's standpoint the deferred object is resolved even though the object values have not yet been set. I've since tried a number of ways to make the API object become deferred based on the completing of the entire ajax call and the setting of the variables, but I'm a bit stuck on the best way to do this.
Any pointers would be most appreciated! Thanks.
You could pass the callback function when you create the object, like so:
function API(uid,accessToken, callback){
$.ajax("path/to/file", {
type: "POST",
data: { user: uid, auth: accessToken },
dataType: "json",
success: function(jsonData) {
arrayname = jsonData[values]
callback(jsonData[values])
}
});
}
and then instantiate the object like so
var api = new API(uid, accessToken, function(array) {
// success function
});
If the problem is due to the "success" callback running after the "then" callbacks, you could try turning success callback into a then callback as well. I don't use JQuery but I guess it would look something like:
function API(uid,accessToken){
return $.ajax("path/to/file", {
type: "POST",
data: { user: uid, auth: accessToken },
dataType: "json",
}).then(function(jsondata){
arrayname = jsondata[values]
});
}
$.when( API = new API(uid, accessToken) ).then(function() {
// ...
});
The reason you use $.when is when you are correlating the callbacks of multiple promises, async tasks, etc. Since jQuery 1.5, all calls to $.ajax and all the wrappers ($.get and $.post) all return promises. Therefore you don't need to wrap this call with the $.when statement unless you want to do $.when(ajaxCall1, ajaxCall2).
Since you want to filter the result from the server, you should use the pipe method of promises:
function API(uid, accessToken)
return $.post(
type: 'POST'
,data: { user: uid, auth: accessToken }
,dataType: 'json'
)
.pipe(function(json) {
return json[values];
})
;
}
This allows you to write your code the way you desire:
API(uid, token)
.then(
// success state (same as promise.done)
function(arrayname /* named from your sample script*/) {
alert('success! ' + arrayname);
}
// error state (same as promise.fail)
,function(jqXHR, status, error) {
console.warn('oh noes!', error);
}
)
.done(function() { /* done #2 */ })
.fail(function() { /* fail #2 */ })
;
Note: promise.pipe() also allows you to filter (change the data passed to) the error callback as well.