I would like to send data by POST method , which will be send by $.ajax metod on JQuery from formulage. I am trying to send this data to controler writted in PHP. I dont know much about MVC but I have read that controller is responsible for collecting data from user for example by completing formulage.
Here is the code :
`$.ajax({
type: 'POST',
url: 'http://www.somepage.pl/index.php?strona=uzytkownicy',
data: {
login: hLogin_u,
nazwaOddzialu: hNazwaOddzialu,
haslo: hPassword,
nazwa: hNazwa_u,
tylkozip: hTylkoIP,
uprawnienia: myDataCheck
},
timeout: 5000,
cache: false,
success: function(msg){
alert('Zapytanie zakonczylo sie sukcesem! Zwrócone dane to '+msg);
},
beforeSend: function() {
$('#errorDiv').show();
//alert('zaraz wysle sie ajax');
},
error: function(){
$('#errorDiv').html('<p>Przepraszamy wystąpił błąd!</p>').show();
//alert('error nastapil');
}
});
I know that only wrong is URL address but I don't know how to send this data to controller. How is correct url.
For example controller name is controler.php and is in directory /contr/controler.php
How is correct url for this configuration.
Am I doing something incorrect sending this data to controller?
I am giving you the code of controller : Maybe this will help to solve the problem.
class Controller // kontroler
{
// składowe
private $strona;
private $model;
private $widok;
// konstruktor
public function __construct()
{
$this->loadModel();
$this->takeData();
$this->loadView();
$this->runView();
}
// załadowanie odpowiedniego modelu
private function loadModel()
{
if (Autoryzacja::czyZalogowany() == false)
{
$this->strona = "logowanie";
}
else
{
if (!isset($_GET['strona']))
{
$this->strona = "glowna";
}
else
{
$this->strona = Narzedzia::security_get($_GET[strona]);
global $baza;
$baza->execute("SELECT 1 FROM wiadomosci WHERE
wiadomosci.pracownik in (1,8) AND
NOT EXISTS
(SELECT 1 FROM wiadomosci_przeczytania WHERE
wiadomosc=id_wiadomosci AND
pracownik=$_SESSION[zalogowany_id_c9])");
if ($baza->count() > 0)
{
$this->strona = "glowna";
}
}
}
$dane=array("logowanie","glowna","dodajw","kalkulator","hasla","zarzadzaj","edycja","chat"," skan",
"logi","ajax_logi","kalendarz","ajaxkalendarz","uzytkownicy");
if (!in_array($this->strona,$dane))
{
$this->strona = "glowna";
}
$this->model = new $this->strona();
}
// załadowanie danych przez model
private function takeData()
{
$this->model->loadData();
}
// załadowanie odpowiedniego widoku
private function loadView()
{
$w = $this->strona."_widok";
$this->widok = new $w($this->model);
}
// uruchomienie widoku
private function runView()
{
$this->widok->show();
}
}`
Related
I'm using Yii2 and I have setup a login process which works fine (cookies as well) via the standard login page which is not AJAX.
I have built a dropdown login field which works fine at logging them in, however it doesn't seem to set the cookie as the user doesn't stay logged in and there is no bookie created.
I figured that this was because of AJAX and the cookie wasn't being created on the users system, but upon further reading it seems it should work.
I have verified that the cookie value is being set correctly, the only issue is the cookie doesn't seem to being created.
My login code:
JS:
function doLogin() {
// Set file to prepare our data
var loadUrl = "../../user/login/";
// Set parameters
var dataObject = $('#login_form').serialize();
// Set status element holder
var status_el = $('#login_status');
// Make sure status element is hidden
status_el.hide();
// Run request
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
if (response.result == 'success') {
//.......
} else {
//.......
}
})
.fail(function() {
//.......
});
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
if ($('meta[name="csrf-token"]').length) {
// Add our CSRF token to our data object
dataObject._csrf = $('meta[name="csrf-token"]').attr('content');
}
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
Controller:
public function actionLogin() {
// Check if they already logged in
if (!Yii::$app->user->isGuest and !Yii::$app->request->isAjax) {
return $this->redirect('/');
}
if (Yii::$app->request->isAjax) {
// Set our data holder
$response = ['output' => '', 'result' => 'error'];
}
// Let's send the POST data to the model and see if their login was valid
if (Yii::$app->request->isAjax and $this->user->validate() and $this->user->login()) {
$response['result'] = 'success';
} elseif (!Yii::$app->request->isAjax and Yii::$app->request->isPost and $this->user->validate() and $this->user->login()) {
//.......
} else {
//.......
}
if (Yii::$app->request->isAjax) {
echo Json::encode($response);
}
}
Model:
public function login() {
// Set cookie expire time
$cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];
return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));
}
As I suspected (see my earlier comment) response might not be correctly generated in case of simply echoing the data. Or maybe Content-Type header matters. If someone can confirm this it will be great.
Anyway, I'm glad it works now (data needs to be returned).
And you can use Response handy format as well.
public function actionLogin() {
// ...
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $response;
}
}
I am new to the world of Kohana/php and am having some issues understanding how to get the result of an ajax request. This request is being called from a click action and is invoking the following method.
function addClickHandlerAjax(marker, l){
google.maps.event.addListener(marker, "click",function(){
console.log(l.facilityId);
removeInfoWindow();
//get content via ajax
$.ajax({
url: 'map/getInfoWindow',
type: 'get',
data: {'facilityID': l.facilityId },
success: function(data, status) {
if(data == "ok") {
console.log('ok');
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
}
Inside of my controller I have a method
public function action_getInfoWindow(){
if ($this->request->current()->method() === HTTP_Request::GET) {
$data = array(
'facility' => 'derp',
);
// JSON response
$this->auto_render = false;
$this->request->response = json_encode($data);
}
}
I see an HTTP request in fiddler and it passed the correct facilityID parameter. However I am having some disconnect about how to connect all the pieces together.
To send a response to the browser, you should user Controller::response instead of Controller::request::response. So your code should look like this:
public function action_getInfoWindow() {
// retrieve data
$this->response->body(json_encode($data));
}
That should give you some output.
Checkout the Documentation for more detailed info.
Edit
What you could do, to make your life a bit easier, especially if you gonna use ajax requests a lot, is to create an Ajax controller. You can stuff all checks and transforms in it, and never worry about it anymore. An example controller could look like below. Also checkout the Controller_Template which is shipped as an example by Kohana.
class Controller_Ajax extends Controller {
function before() {
if( ! $this->request->is_ajax() ) {
throw Kohana_Exception::factory(500, 'Expecting an Ajax request');
}
}
private $_content;
function content($content = null) {
if( is_null( $content ) ) {
return $this->_content;
}
$this->_content = $content;
}
function after() {
$this->response->body( json_encode( $this->_content ) );
}
}
// example usage
class Controller_Home extends Controller_Ajax {
public function action_getInfoWindow() {
// retrieve the data
$this->content( $data );
}
}
I was wondering if is there any good practices to call method from php class with Javascript, by the way of Ajax.
This is my current "style" to execute it.
(The method in the class are only here for example)
PHP side :
<?php
if(isset($_POST['action']) && $_POST['action'] != null)
{
extract($_POST);
if($action)
{
$ajaxCommand = new EleveUpdate();
if(method_exists($ajaxCommand, $action))
{
$reponse = call_user_func(array($ajaxCommand, $action),$_POST);
echo $reponse;
exit(0);
}
else
{
throw new Exception("Cette méthode n'existe pas");
}
}
}
else
{
echo 'Cette action n\'est pas autorisée';
return false;
}
class EleveUpdate
{
public function __construct()
{
}
public function testfunct($data)
{
echo $data['eleve'];
}
}
Javascript side:
$(document).ready(function() {
$.ajax({
url: 'eleveupdate.php',
type: 'POST',
data: {
action: "testfunct",
eleve: 1
},
beforeSend: function()
{
loading(true);
},
error: function()
{
console.log('error');
},
success: function(data)
{
loading(false);
console.log(data);
}
});
});
The problem is that the isset $_POST is always in my class, I'm pretty sure this is not the right way to do it so, I'm here to found help about it.
Thanks you in advance
Simon
The problem is it's not easy to call scope-namings based on a string-request.
You can use something called LAMBDA, or anonymous functions. This way you can store an array of strings with a LAMBDA attached to them. Like this:
<?php
class EleveUpdate {
private $funcs = array();
function __construct($which_function) {
$funcs['testfunct'] = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
$funcs[$which_function];
}
}
?>
See more info here: http://www.php.net/manual/en/function.create-function.php
You probably won't even need the Class anymore with this method, but just showing.
I am using codeigniter, i have written a function to check if a user password exists which it does. This is my model
The model: user
public function get_some_password($username,$password) {
$this->db->where('user_password', $password);
$this->db->where('user_username',$username);
$query=$this->db->get('some_users_table');
if($query->num_rows()==1){
return true;
}else{
return false;
}
the controller
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
$this->user->get_some_password($username,$password);
}
The ajax on the view
//done on page load
var success1 = $(".success"); //a div on the view that appears if success
var error1 = $(".error"); //a div on the view that appears if error
success1.hide();
error1.hide();
$('#change_password').click(function() {
var username = $('#username').val();
dataString2 = $('#changpassword').serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>controller_name/check_password/' + username,
data: dataString2,
success: function() {
$('.success').html('password successfully updated!'),
success1.slideDown('slow');
},
error: function() {
$('.error').html('Wrong current password!'),
error1.slideDown('slow');
}
});
The problem: Ajax loads the success div even when the username or password returned is false, where am i missing something
This is a correct behavior as jquery error is executed when response code is not 200:
1) You can parse returned value in success method.
e.g.
success: function(data) {
if (data == 'true') {
// Success
} else {
// Error
}
}
2) You can return error code from server 404, 500, 503 ... To trigger execution of error function.
e.g.
header("Status: 404 Not Found");
note: Header should executed before any output is done.
Try in your controller:
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
if(!$this->user->get_some_password($username,$password)) {
$this->output->set_status_header('500');
return;
}
...
}
I have a table named state with columns state_id, state_name. Currently I can add new states and edit them, but I can't delete states. What might be wrong with my code?
{title:"Actions",template:'<a class="left" onclick="javascript:openEditStatePopup(this);">Edit</a>' +
'<a class="right" onclick="javascript:deleteState(this);">Delete</a>'
,width:120,sortable:false}
This snippet is the view code, and when I click the link, it executes the following JavaScript:
function deleteState(element)
{
var countryDetail = {};
var GriddataItem = $("#state_grid").data("kendoGrid").dataItem($(element).closest("tr"));
countryDetail.state_id =GriddataItem.state_id;
countryDetail.state_name = GriddataItem.state_name;
// alert(countryDetail.state_id);
$.ajax({
url:"<?= $this->baseUrl('admin/state/delete')?>",
data: {state_id : countryDetail.state_id},
dataType: "json",
type: "POST",
success: function(){
alert('success');
},
failure:function(){
alert('not working');
}
});
}
When I echo alert(countryDetail.state_id) before the $.ajax call, I can get the correct state id.
My delete controller is:
public function deleteAction()
{
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
}
and the model mapper for deleting is:
public function delete(Application_Model_State $state)
{
$data = $state->toArray();
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$data['state_id']));
}
Hi you need to write deleteAction as following
public function deleteAction()
{
$state = $this->_getParam('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateId = $stateMapper->delete($state);
$this->_helper->json(array('success'=>1));
}
in your controller action deleteAction() you are getting POST param 'state_id'
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
and you are passing that $state in the $stateMapper->delete($state); function
in your model class function public function delete(Application_Model_State $state) definition you are passing State model object not and state id, so you should change this to
public function delete($state_id)
{
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$state_id));
}
Then it should work...
Another thing I have not seen
failure:function(){
alert('not working');
}
Rather it is
error:function(){
alert('not working');
}