In controller I have a _remap() for routing.
My controller is as follows:
public function _remap($id)
{
$this->index();
}
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$this->output->view('translation/language');
}
function process(Request $request){
// if(Response::ajax()) return "OK";
return json_encode(array('ok'));
}
My view is as follows:
$('#lang_choice1').each(function() {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?=site_url('translation/language/process')?>',
data: msg,
success: function(data){ }
});
return false;
});
I am trying to call the function process in ajax and its not getting called. How do I need to modify the _remap function to call ajax calls as well?
Try This
Script part
$('#lang_choice1').each(function () {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?= site_url('language/process') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
Controller process function
function process() {
$data = $this->input->post();
$result['status'] = "ok";
$result['response'] = $data;
echo json_encode(array($result));
exit(0);
}
Check response in console
Related
I am a student who is practicing Codeigniter. This is the script that I have formed.
$(document).ready(function () {
$('#hiddenDO').each(function () {
$('#displayoffice').val($("#hiddenDO option:selected").val());
$.ajax({
type: "GET",
url: '<?= site_url('client/displayoffice') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
}
Controller
public function displayoffice() {
$data = $this->input->post();
$result['hiddenDO'] = $data;
echo json_encode(array($result));
exit(0);
}
and my Model
function filterOffice() {
$data = '3'; //In this part I want to call the value to filter
$query=$this->db->query("SELECT bi_emplname, bi_empfname, bi_emppic FROM `tblemployee`
INNER JOIN `tbl_office` ON ji_off_id=off_id
INNER JOIN `tbl201_basicinfo` ON bi_id=ji_bi_id
WHERE ji_off_id='$data'");
return $query->result_array();
}
I have a javascript file from which I am trying to make a ajax call to execute method of a different php file.
Javascript file - a.js
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {"updateMethod()"}
success:function(result){
console.log(result);
}
});
}
PHP file - abcd.php
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
I am not able to make a call to the PHP method. What is wrong with my AJAX query or what do I need to do in PHP file side to call the method.
I don't know what you try to do, but you can do it this way:
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {methodName: "updateMethod"},
success:function(result){
console.log(result);
}
});
}
On server side:
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();
Remove this line
dataType: 'json',
and send data without json
If you sending json in php must be:
$data = file_get_contents('php://input');
PHP "php://input" vs $_POST
Or beter jquery:
var methodName = "YourMethodName";
var y = "Cymbal";
$.post( "test.php", { methodName: methodName, lastname: y })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested):
backend:
class CRUD
{
public function update($args)
{
$input = $args['exampleInput'];
// sanitize input
// prepared query
// $stmt->execute($input);
}
}
function access($class, $method, $args)
{
if (method_exists($class, $method)) {
return call_user_func_array([$class, $method], [$args]);
}
}
$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));
js:
function handleAction(methodName, arguments) {
$.ajax({
url: "crudFile.php";
type: "POST",
data: { method: methodName, args: arguments },
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
var inputs = {
exampleInput: function () {
return document.getElementById('your-div-id').textContent();
},
};
// usage
handleAction('update', inputs);
ajax call does not hit to controllers function, what is the reason and why I am not understanding kindly guide me
I am trying to send ajax call to controller update the record this is my ajax code
$(document).ready(function() {
$(".update").click(function(event) {
debugger;
event.preventDefault();
var vehno = $("input#vn").val();
var vbrand = $("input#vb").val();
var vmodel = $("input#vm").val();
var vcolor = $("input#vcol").val();
debugger;
$.ajax({
type: "ajax",
method:"Post",
url:'<?php echo base_url('index.php/vehicleCtrl/FunUpdate')?>',
//async:false,
dataType: 'json',
data: {vehicle: vehno, brand: vbrand, vmodel:vmodel,vcolor:vcolor},
success: function(res) {
alert("working");
// if (res)
// {
// // Show Entered Value
// jQuery("div#result").show();
// jQuery("div#value").html(res.username);
// jQuery("div#value_pwd").html(res.pwd);
// }
},
error:function(res){
alert(res);
}
});
});
});
this Controller's Function
this is a codeigniter controller
public function FunUpdate()
{
$as= $this->input->post('vehicle');
$id=-1;
$vehicleArray = array('vehicleNo' => $this->input->post('vehicle'),
'Brand' => $this->input->post('brand'),
'Model' => $this->input->post('vmodel'),
'Color' => $this->input->post('vcolor'),
);
echo json_encode($vehicleArray);
$Result=$this->VehicleModel->Update($vehicleArray,$no);
if($Result)
{
$data= array('error' =>'Vehicle Update Successful');
$data["DetailList"]=$this->VehicleModel->FunDetailSearch($no);
$data["EditTrack"]=$this->VehicleModel->EditTrackDetail($id);
$data["NewVehicle"]=$this->VehicleModel->FunfindVehicle($no);
$this->load->view('Layout/header');
$this->load->view('vehicle/create',$data);
$this->load->view('Layout/footer');
}
}
ajax request should look like this
$('#buttonid').click(function(){
var vehno = document.getElementById('vehno').value;
var brand = document.getElementById('brand').value;
$.ajax({
url:'<?=base_url()?>index.php/Controller/function',
method: 'post',
data: {vehno: vehno, brand: brand},
dataType: 'json',
success: function(response){
alert('data updated');
}
});
});
function
public function updateDetails(){
// POST data
$postData = $this->input->post();
//load model
$this->load->model('Main_model');
// get data
$data = $this->Main_model->updateVehicle($postData);
echo json_encode($data);
}
Modal
function updateVehicle($postData){
$response = array();
if($postData['id'] ){
$this->db->where('id',$postData['id']);
return $this->db->update('vehicle',$postData);
}
Hope Now You Update Your Data With Ajax
I'm trying to create a notification feature and I wanted the ajax to be able to run a query via the controller on button click
THIS IS MY SCRIPT
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>'
});
});
THE CONTROLLER
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
return;
}
AND THE MODEL
function read_notifs($id)
{
$read = array(
'read' => '1'
);
$this->db->where('recipient', $id);
$this->db->update('tbl_notifications', $read);
return;
}
I tried this and the data in the database doesn't update.
IN MY HTML IT IS JUST A SIMPLE BUTTON
Script
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
Controller
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
echo $this->db->last_query();
}
It is the sample calling the ajax in ruby on rails . In this code we are calling the controller for getting the values.
$('#Button').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax({
type: 'GET',
url: "<%= Home_index_path %>",
data: { id: selected_resource_id },
success: function (data) {
alert("Ajax success");
}
});
});
use error: to check if there's any error in submitting your form.
$('#button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
My variable data in function ShowFavorits is undefined even do that my ajax call do return a json string.
<script type="text/javascript">
$(document).ready(function () {
ShowFavorits();
function AjaxGet() {
var param = "{'_userID': '1337'}";
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
contentType: "application/json;",
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
return (data.d);
}
},
error: function (data) {
//error
}
});
}
function ShowFavorits() {
var data = AjaxGet();
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});
[WebMethod]
public string GetFavorits(string _userID)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = int.MaxValue;
string JsonData = string.Empty;
var db = new ModelDataContext();
var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();
JsonData = jss.Serialize(list);
return (JsonData);
}
Why cant i return the result from my ajax?
Hope someone can help me, have been stuck for hours now debugging this.
Thanks in advance.
The call to $.ajax in AjaxGet is asynchronous: the function returns undefined because the ajax call hasn't finished.
You should move the call to ShowFavourits into the ajax success function so that it executes once the ajax call is complete/successful
<script type="text/javascript">
$(document).ready(function () {
// Kick-off the ajax request
AjaxGet();
function AjaxGet() {
var param = {_userID: '1337'};
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
ShowFavorits(data.d); // Pass the data to the template
}
}
});
}
function ShowFavorits(data) {
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});