Call CI Controller from ExtJs - extjs

I am creating controller in Code Igniter and make form in ExtJs 4.2.1 now from where i call control and how?
i used url property of form and put controller name there but nothing happen
Update
I think i am not clearing my question actually i want to post data through submit function in which i pass data to php file in my server side i use Code Igniter Rest Api so here i want pass data to specific controller

ExtJs is a javascript framework and is executed on the client side. It has its own MCV system.
It makes no sense to mix up a php controller with a javascript view.
Be sure to read the introduction to MVC in ExtJS.
Also in ExtJS you don't call the controller. On initialisation of the app, all controllers get lloaded. In the controller you define what it has to control, and from then on the magic hhappens: The events defined in the controller are fired whenever needed.

In ExtJS 3.3.1
In login form put the buttons and call function submit_login();
buttons: [{
text: 'Login',
handler: function() {
submit_login();
}
}]
Submit_login() code is, I used Ext.Ajax.request to submit login parameters
You can debug the message with alert(response.responseText):
function submit_login() {var useridx = Ext.getCmp('useridx').getValue();var userpasswordx = Ext.getCmp('userpasswordx').getValue();Ext.Ajax.request({url:'".$url."', method:'POST',
params :{useridx:useridx,userpasswordx:userpasswordx},
success:function(response){
//alert(response.responseText);
//return;
var jsonData = Ext.util.JSON.decode(response.responseText);
var resultMessage = jsonData.Message;
var isLogin = jsonData.isLogin;
if (isLogin)
{
window.location = '';
}
else
{
Ext.Msg.alert('Info',resultMessage);
}
},
failure: function(){
Ext.Msg.alert('Not OK');
}
});
}
variable $url is:
$url = "index.php/apps/login";
You can create Apps controller
and create function login
public function login()
{
$this->load->view('login');
}
Create login.php in view
if ($i==1) {
//session_start();
$this->session->set_userdata('userid',$useridx); echo '{"success" : true, "isLogin": true,"Message" : "User Successfully Login"}';
} else {
echo '{"success" : true, "isLogin": false, "Message" : "Salah User: '.$useridx.' dan Password "}';
}
You also do this in Ext JS 4.2.1 with same code.
This is works for me
Andrex Maulana

Related

Extjs6 Custom js event

I have the following flow: before the app launches I want to check something on the server. Based on the response I want to make a decision. I've created an utility class that wraps my js event and also an app controller.
Bellow is app controller:
Ext.define('MyApp.controller.AppController', {
extend: 'Ext.app.Controller',
appEventDispatcher:function (){
// Create a dummy DOM element
var dummy = document.createTextNode('');
// Create custom wrappers with nicer names
this.off = dummy.removeEventListener.bind(dummy);
this.on = dummy.addEventListener.bind(dummy);
this.trigger = function(eventName, data){
if( !eventName ) return;
var e = new CustomEvent(eventName, {"detail":data});
dummy.dispatchEvent(e);
}
}
});
And my utility class:
Ext.define('MyApp.util.Util', {
statics : {
checkSomethingOnServer: function(customEvent){
var store = Ext.StoreManager.lookup('appStore');
store.load({
scope: this,
callback: function(records, operation, success){
if (success === true){
customEvent.trigger('success', true);
if (success === false)
debugger;
customEvent.trigger('fail', true);
}
}
});
}
}
});
Using the utility class I load a store. In the callback method, I trigger my custom event. This event is handled in the app.js file.
The code works in fiddle and also using app watch, when I want to build the code some errors are occurring complaining(syntax error).
I've created also a fiddle.
How to create a custom event in ExtJS and how to use it? I need the same behavior as with the js event but Extjs implementation.
In ExtJS, you would just attach an event listeners to the store with your custom event's name:
store.on('myownevent', function(success) {
console.log(success);
});
and your code may go ahead and fire events on the store by that name:
store.load({
scope: this,
callback: function(records, operation, success){
store.fireEvent('myownevent', success);
}
});
If no listener for that event is attached, nothing happens; if one or more listeners are attached, they are executed in the order of priority, for those with the same priority, in the order they were added.
https://fiddle.sencha.com/#view/editor&fiddle/21g7

Why backbone add extra parameter to url path?

I am using backbone.marionette (1.0.0) and node.js (0.10.22). Wondering why backbone add extra parameter when I try to save model data with node.js REST call.
model.js
Backbone.Model.extend ({
urlRoot: function (){
return '/path/' + myApp.companyId;
},
defaults: {
companyId: '',
// other attributes
},
// doesn't use 'id' in model instead companyId
idAttribute: 'companyId'
});
Before view is loaded, I would request model data with myApp.request ('entities:myModel') which issued model.fetch () and node.js backend would fire GET /path/1 route. No issue.
However, when an update button is clicked on the view, this.model.save () would fired PUT /path/1/1. It should be PUT /path/1, with only a single '1' in url path.
view.js:
clicked: function () {
var formData = Backbone.syphon.serialize (this);
this.model.set (formData);
var promise = this.model.save ();
promise.done ().fail ()
}
How can I stop backbone.sync from appending extra parameter to url path? Thanks for taking time out to read this, and I appreciate your help.
You're setting urlRoot incorrectly on the model. It should be
Backbone.Model.extend ({
urlRoot: "path",
// etc
});
Backbone willa dd the ids on it's own.
If you want to specify the ids in your function, use the url function.

Backbone Model not compatible with underscore and ASP.NET MVC Web API Controller?

This is a two stage problem when working with backbone.js and a web api controller.
I have a simple web api controller that returns a JSON string, in fiddler the result looks like this:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
I use the following code to fetch a user from my web api
var user = new Usermodel({ id: "1" });
user.fetch({
success: function (u) {
console.log(u.toJSON());
}
});
now my backbone user object looks like this
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
When I try to bind this backbone model object to my view template that looks like this
<form>
<input type="text" value="<%=Heading%>" />
<input type="submit" value="Save" />
</form>
i get, Heading is undefined but when I use id it binds just fine? It seems like underscore does not like the backbone model object and just want a plain JSON object just like the one I get from my web api?
The second problem with this is that when I save my model with user.save({ Heading: "my new heading }); the payload to my web api is the backbone model which is completely wrong because my api expects a user object like this to be sent to the server:
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading":"The heading"
}
and not the backbone model with the real object wrapped inside. Is it possible to solve so that underscore can handle backbone models and tell backbone to only send the payload that my end point expects?
You may be able to solve the problem by following these steps:
In addition to using fiddler to inspect your response, look at the response on the network tab of Chrome Developer Tools. If the response does not look like this, then your web api is not returning a valid json response, the problem is most likely within your web api. You need to get/provide more information about your web api to solve the problem. Verify that the response looks like this:
After verifying that the response from the web api is correct, check out the following jsfiddle I modified:
http://jsfiddle.net/J83aU/23/
Fix your client side code referencing the example I have provided.
Properly instantiate the Backbone objects.
Call the view.render function at the correct step, after the response is received from the server.
Make sure that the main content div is actually rendered before creating a view which depends on it for the 'view.el' property.
Declare the 'view.el' property properly, with a string rather than jQuery object.
Use development Backbone and underscore to enable debugging, an important concept when learning to use open source frameworks such as Backbone.
Use jsfiddle's echo/json api to mock a valid ajax json response, exactly as described in step 1.
The following json example you submitted is not even valid json, if you update your question with valid json example, it would be easier to solve the problem. It is unlikely that Backbone created this non-json structure and more likely that you have submitted it here incorrectly.
{
id: "1",
{
"$type": "MvcApplication.Models.Article, MvcApplication",
"Id": "1",
"Heading": "The heading"
}
}
Finally, try to provide a screenshot of the http headers or something for the problem that is occurring when you call model.save().
Read over the Backbone documentation for model.save() and make sure you are doing everything just as the example provided.
You may be able to workaround Backbone's funky save function by forcing your attributes into POST parameters using ajax options:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var saveView = Backbone.View.extend({
events:{
'click #saveSubmitButton':'submit'
},
submit:function (event) {
event.preventDefault();
var view = this,
attributes = $('#saveForm').serializeObject();
this.model.save(attributes, {
data:attributes,
processData:true,
success:function (model) {
//....
}
});
},
render:function () {
//.......
}
});
The attributes property of your model should be unaltered. Send those to your template call:
var MyModel = Backbone.Model.extend();
var newModel = new MyModel({
"$type": "MvcApplication.Models.Article, MvcApplication",
"Heading":"The heading"
});
var html = _.template(templateVar, newModel.attributes);
In your templateVar, which is your templated markup, you should be able to reference $type and Heading directly.
If you have a look at the jsFiddle through a debugger like Firebug you can see that the way you construct the model's URL is not working out, because the forward slash gets encoded. Can you try to modify your model declaration to this:
var Usermodel = Backbone.Model.extend({
url: function () {
return '/api/page/articles/' + this.get('id');
}
});
var user = new Usermodel({
id: '85'
});
And see if you still get the same JSON. Basically if you don't have a Backbone.sync override you are using built-in retrieval that for one shouldn't produce invalid JSON.

CakePHP: JQuery submit() returns a blank page

I create a function in CakePHP controller class to process AJAX request. But I found different result when using CakePHP function and simple (Non-MVC) PHP code. My problem is when it goes to submit() process. When using CakePHP function it returns blank page.
Here is the AJAX request code that I use:
var userdata = {username : $("#UserUsername").val()};
$.ajax({
type:'POST',
url: 'http://localhost/mycakephp/users/login',
data: userdata,
success: function(data){
if(data==0){
alert("empty");
} else {
$("#UserLoginForm").submit();
}
}
});
But when I pointed the url to external site like this:
url: 'http://localhost/test/test.php'
Which test.php is a simple PHP code to handle request, submit process works fine.
Sorry, but your code looks bizarre to me: There you have a login form, you send using ajax your username calling the Controller "UsersController" / function "login", and when you have an answer from this function, then you submit again another form ("#UserLoginForm") and send it again to the controller? You are sending two forms! Most probably this is not what you want. Correct me if I am wrong.
I guess what you want is just submit the UserLoginForm and wait for an answer, whatever it is OK or NotOK, and finally show this result.
You have two options to do this: either CakePHP way or your own ajax code using JQuery. I like to use both, depending on the user experience I want to get.
1. CakePHP way
Include JS Helper in the controler using the public $helpers = array('Js'); and then create a Form in the view, using the submit from the JsHelper.
View
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('whatever');
// use the Js submit from JsHelper
echo $this->Js->submit('Send', array(
'url'=> array('controller' => 'users', 'action' => 'login'),
'update' => '#update_ajax_div',
));
echo $this->Form->end();
// Next line is actually very important in order
// to print the automatically created ajax code from JsHelper.
echo $this->Js->writeBuffer();
?>
<div id="update_ajax_div">
this will be overwritten after submit.
</div>
Controller
In the controller all the data in the form will be sent in the $this->data[] array. For example $this->data['Users'] if this is the Model being used in the Form->create().
The code is pretty standard, except the layout, which must be set to ajax.
public function login(){
// print the data being sent
$dataFromAjaxLink = $this->data[];
$v = var_export($dataFromAjaxLink, true);
$this->log("Ajax log: ".$v, 'debug');
if(isset($this->data['User'])){
$user_name = $this->data['User']['username'];
...
// do your stuff
}
// the answer must be ajax layout
$this->layout = "ajax";
// I like to use elements when using ajax, it keeps the folders clean
// in this example /app/View/Elements/display_ajax_result.ctp
$this->render('/elements/display_ajax_result');
}
The content of this element will be printed in the div "update_ajax_div"
2. Pure Ajax way
The second version is done by manually typing ajax code in <script> tags. This solution gives you more freedom, allowing you to do more complex stuff, but the code is not so clean!
The following JQuery code must be inside some button/div/whatever event...
$(document).ready(function(){
$(".someButton").click(function() {
// create the json data to be sent
var username = $(....).val();
var dataString = ...
// call ajax
$.ajax({
type: "POST",
// never type full paths as in your example. They are sources of errors!
url: "<?php echo $this->Html->url(array(
"controller" => "users",
"action" => "login")); ?>,
data: dataString,
cache: false,
success: function(html){
$("#update_ajax_div").html(html);
}
});
...
The controller is the same as the CakePHP way. Remember to add ajax layout.
I hope it helps you.
According to your comment, if you use the SecurityComponent, you could disable POST validation on the login action. In your UsersController, add this:
function beforeFilter()
{
parent :: beforeFilter();
switch($this->request->params['action'])
{
case 'login':
$this->Security->validatePost = false;
$this->Security->csrfCheck = false;
break;
}
}
But off course you loose the value added by the SecurityComponent on the login action.

CakePHP and AJAX to update Database without page refresh

I'm working with CakePHP 1.3.7 and I'm trying to do the following:
On a given page, the user can click a link (or image, or button, doesn't matter) that passes a parameter which is saved into a database. BUT, all this, without refreshing the page.
I've been doing some research and I believe I need to use AJAX as well to acomplish this. However, I can't find the a good example/explanation on how to do it.
I think that the idea is to create the link using AJAX, which calls the controller/action that would receive the variable as a parameter and performs the operation to save it in its corresponding field/table of the DB.
Does anyone have a small example of what I want to do? Or maybe point me to some tutorial that explains it... Thanks so much in advance!
EDIT
Well, thank you guys for your replies. THey're not working directly, but I think I'm getting closer to what I want. Here's what i'm doing now:
I have this code in my view:
<div id="prev"><a>click me</a></div>
<div id="message_board"> </div>
I call this JS file:
$(document).ready(function () {
$("#prev").click(function(event) {
$.ajax({data:{name:"John",id:"100"}, dataType:"html", success:function (data, textStatus) {$("#message_board").html(data);}, type:"post", url:"\/galleries\/add"});
return false;
});
});
And my add action in my galleries controller looks like:
function add() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
echo "<h2>Hello</h2>";
print_r($this->data);
$this->layout = 'ajax';
if(!empty($this->data)) {
$fields = array('phone' => 8, 'modified' => false);
$this->User->id = 6;
$this->User->save($fields, false, array('phone'));
}
}
}
When clicking on the '#prev' element, I get a response from the add action, I know because the text 'Hello' is printed inside #message_board. And it does this without refreshing the page, which is why I need. My problem is that I can't make the $.ajax() function to send any data, when it gets to the controller the $this->data is empty, so it never goes inside the if that saves the info to the database (right now it's saving just an easy thing, but I will want it to save the data that comes from the view).
Can anyone see what am I doing wrong? How can I send the data to the controller?
CakePHP does not matter, most of the code you would need for this would be at clientside. Implementing AJAX by yourself is a pain in the $, so you really want to use a library; currently the most popular is probably jQuery. There's a bunch of examples on their AJAX page: http://api.jquery.com/jQuery.ajax/
So, assuming you have something like this in the document:
<form id="s">
<input id="q"/>
<input type="submit" href="Search!"/>
</form>
<div id="r"/>
you can put this in the JavaScript:
$('#s').submit(function(evt) {
evt.preventDefault();
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#r').html(data);
}
});
return false;
});
Then your foo.php only needs to return the fragment HTML that would go into the div#r.
EDIT: I forgot to stop the submit :( Thanks to #Leo for the correction.
EDIT: I can see what your confusion is about. You will not get a data. I haven't worked with CakePHP, but I assume $this->data is what you'd get from $_REQUEST['data']? You don't get that on the server. data is a hash of what is getting submitted; you will directly get the $_REQUEST['name'] and $_REQUEST['id'] (which, I assume, translate into CakePHP as $this->name and $this->id).
You need to add
$('#s').submit(function(evt) {
evt.preventDefault();
To prevent a page refresh, as in Amadans answer just refer to your controller/ action in the url variable
$('#s').submit(function(evt) {
$.ajax({
url: '/patients/search/',
data: {
query: $('#q').val()
},
success: function(data) {
$('#r').html(data);
}
In the patients/add controller action make sure you return a valid result ( in json is good )

Resources