I have an Ext Grid and want to grab the JSON "success":false/true response an execute a function for each situation. I would like to have it as callback function for every grid interaction with the JSON PHP file.
Any examples of this ?
Thank you for your time.
You need to register callbacks to the load and exception events of the JsonStore. Something like this:
var grid = new Ext.grid.GridPanel({
store: new Ext.data.JsonStore({
[...]
listeners: {
load: this.onLoadSuccess.crateDelegate(this),
exception: this.onLoadException.createDelegate(this)
}
}),
onLoadSuccess: function () {
// success
},
onLoadException: function () {
// error
},
[...]
}
Related
axios.get("/api/session/" + this.roomId)
Above is a snippet from my axios call that uses my api.php route ('/api/session/{id} that loads through the controller the requested specific room => /api/session/3 is room 3).
Currently, this snippet is harcoded and always uses integer 1 for 'this.roomId'.
I did that, in oder to check if my vue is even working fine.
My question is now, how am I able to use a dynamic param for my prop roomId?
so I can always say something like
.get/.post('url', $id) ?
If you're passing the roomId as a prop into the component then you need to handle the change in the parent component. For that I'd need a bit more context on where the room-ids come from and how you select the room-id there.
If you have this part down, then you'll want to watch changes on the roomId prop and re-fetch the data when ever it changes. You can do something like this in your room component:
<script>
import axios from 'axios'
const props: {
roomId: {
type: Number,
required: true
}
}
export default {
props,
data() {
return {
room: null
}
},
methods: {
async fetchRoom() {
try {
const response = await axios.get(`/api/session/${this.roomId}`)
this.room = response.data
} catch (err) {
// - handle error
}
}
},
watch: {
roomId: {
immediate: true // so it's executed when component is created
handler: function () {
this.fetchRoom()
}
}
}
}
</script>
I am using laravel 5.
I have a custom action in my controller. By custom I mean it is not used by the resource object in angular. The following is the code of my controller.
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
This is my service code in the angular script.
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
Now, the query() here will send the request to the index method in the laravel controller. How will I access the extras() action in the getExtras() method?
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '#id',
param: '#param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController#custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController#extras');
I got what I wanted using $http.
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
But, that would be nice if anyone suggest me how to do it with Serviceb.query().$promise.then.
I use resource make crud, and in the create page, I have to add a preview page
I tried to use ajax post data to admin/article/previewform then in route action controller method previewform catch data and store in variable with redirect to new page preview show it ...
I have problem
1. Why it doesn't redirect to new page ?
2. Why in js console.log get Faild to load resource … statu?s of 500
3. I also try return Redirect::to('admin/article/previewshow'); in previewform then still not redirect to.
But get js console.log with template show.blade.phpthat is in resource show method call.. ??
How to solve it?
js
$.ajax({
url: 'previewform',
type: 'POST',
data: {data: data},
})
.done(function(response) {
console.log(response);
});
route
//.. prefix=>admin
Route::resource('article','AdminArticleController');
Route::post('admin/article/previewform', 'AdminArticlePreviewController#previewform');
Route::get('admin/article/preview', 'AdminArticlePreviewController#preview');
AdminArticlePreviewController
class AdminArticlePreviewController extends AdminController
{
public function preview()
{
$input = Input::get('data');
return Redirect::route('admin/article/previewshow');
}
public function previewshow()
{
// return View::make('admin.article.preview')->with('data', $data)
}
}
It is not possible to make redirection in this way. For ajax requests you need to catch "redirection command" from the server side script (PHP) and execute it in the JS.
Instead:
return Redirect::route('admin/article/previewshow');
you can use:
return Response::make('/redirect/url', 301)
then JS code:
.done(function(response) {
console.log(response);
});
can be replaced by something like:
.done(function(data, statusText, xhr) {
if(xhr.status == 301) {
window.location = data;
}
});
I have developed an facebook app which is using ajax request/response each 3secs. and also there are menu items which are loading content in main div. Every ajax request is going to common.php. Few ajax are very slow. I want to know that using a single file for all request is slowing performance?
Here is ajax request which is slow:
function FetchMore()
{
document.getElementById("debugger").innerHTML = "Fetch more called";
attempt++;
/*********proccessing ajax***********/
document.getElementById("bldr").style.display="";
var urlp="https://www.shopinion.net/facebook/common.php?FBUID="+fbuid+"&action=more&attempt="+attempt+"&what="+lstevt;
if(lstevt == "home" || lstevt == "rec")
{
if(complete==false)
{
complete=true;
setTimeout("Watcher()",10000);
document.getElementById("debugger").innerHTML = "Reqest send Fetch more called";
MoreAjaxReq = $.ajax({
async: true,
url: urlp,
cache: true,
success: function(data) {
complete=false;
document.getElementById("debugger").innerHTML = "Data received Fetch more";
setTimeout("getScroll()",3000);
document.getElementById("content").innerHTML +=data;
document.getElementById("content").style.opacity="1";
Tip();
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
var handler = null;
// Prepare layout options.
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#content'), // Optional, used for some extra CSS styling
offset: 6, // Optional, the distance between grid items
itemWidth: 210 // Optional, the width of a grid item
};
$(document).bind('scroll', onScroll);
// Call the layout function.
handler = $('#tiles li');
handler.wookmark(options);
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
document.getElementById("bldr").style.display="none";
//FB.Canvas.scrollTo(0,400);
setTimeout("Trick87()",3000);
}
});
}
//
Please help me how to improve response time?
Thanks in advanced.
Oh, there are lots of ways to improve performence. I will list a few
Cache data on server side
Minimize the content in the response
Maybe you don't have to fetch more data if the first request hasn't success yet.
Use as few database calls as possible
I'm having trouble figuring out how to display some return JSON objects.
My script works like this:
I'm making an ajax call, sending some params to a CodeIgniter Controller where I'm processing it with a model, making some queries towards an database and then returning the json_encoded rows to the ajax callback function. This works great btw.
Here is what I want to do now and here its where I'm stuck. I want the new JSON objects (contains database rows) to "replace" the old rows in a html table. So I want it to update the table depending on the params I'm passing but only in the tbody mind.
I'm new at jquery so I've tried i few things. I've tried iterate trough the json data and use the $.html(string) function but i guess this replace everything and it will eventually just display the last object(Am i right?).
So I wonder how in a general sense I would do this?
$.ajax({
type: 'GET',
url: 'someSite.com/someEndpoint'
data: xyz.
success: function( response ) {
//lets say you have an object like this: object = { data: { ... } }
var html = '';
for(var i = 0; i<response.data.length; i++) {
html += '<tr><td>'+response.data[i].title+'</td></tr>';
}
$('#someTable tbody').html(html);
}
});
You don't have to return JSON objects in an AJAX request. Try setting the data_type config setting for the $.ajax call to "html" (or leave it blank--jQuery is really good about figuring it out from the response data).
I usually factor out the <tbody>...</tbody> portion of a view to its own view partial. Then, the "original" page load can use it, and so can an updating AJAX call.
The only asterisk to this is if you need some sort of object-oriented response along with the HTML. I would usually do something like this:
{
"stat": "ok",
"payload": "<tr><td>row1</td></tr><tr><td>row2</td></tr>"
}
And then in the ajax success function:
$.post('/controller/action', { some: 'data' }, function(response) {
$('#my_table tbody').append(response.payload);
}, 'json');
What are the params your passing in?
for example you might use a select or input field to trigger an ajax call and pass its value as the param.
var tableObj = {
var init : function(){
//check that your selectors id exists, then call it
this.foo();
},
foo : function(){
var requestAjax = function(param){
var data = {param : param}
$.ajax({
data : data,
success : function(callback){
console.log(callback);//debug it
$("tbody").empty();//remove existing data
for(var i =0; i < callback.data.length; i++){}//run a loop on the data an build tbody contents
$("tbody").append(someElements);//append new data
}
});
}
//trigger event for bar
$("#bar").keyup(function(){
requestAjax($(this).val());
});
}
}
$(function(){
tableObj.init();
})
Your php method
public function my_method(){
if($this->input->is_ajax_request())
{
//change the output, no view
$json = array(
'status' => 'ok',
'data' => $object
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
else
{
show_404();
}
}