Catching data in controller - javascript

I have a question about javascript and cakephp, I need to send data via Post and recive it in the other side (the controller) and make the normal process that I already have. But I don't know how can I catch the data. I'm working with Ajax
function editFun(clicked_id){
var id = clicked_id;
$("#Content").empty();
$('#Content').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/Posts/edit',
data: (id)
})
.done(function(data){
console.log(data);
$('#Content').html(data);
})
.fail(function(data){
$('#Content').html(data);
});
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}

In that case you should send your id in URL. So even GET method is enough, because you controller receive $id param from URL.
So all what you need to change are post arguments:
$.ajax({
type: 'POST',
url: '/Posts/edit/' + id
})

Related

Calling method in PHP file from separate JavaScript file

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);

How to return parameter route from Laravel to Ajax

I am trying to return the parameter of a laravel route to an ajax response. This is my
public function getPermissions(Request $request)
{
//$v = request()->route()->parameters('profile');
$v = request()->route()->parameters();
return var_dump($v);
}
JS:
function getPermissions() {
let data_permissions = '';
$.post({
url: '/permisos',
async: false,
success: (res) => {
console.log(res)
}
});
}
This is my route:
http://base-laravel.test/profiles/1/edit
In the console returns an empty array.
I intend to obtain the 1 that they see on the route. Suggestions?
You have not added the data to send from Laravel to Ajax Controller. You can pass the data inside the object of the data like
$.post({
url: '/permisos',
type: "POST",
data: {
id: '{{$user->id}}' // Suppose you need to pass the user id to the controller
},
async: false,
success: (res) => {
console.log(res)
}
});
When retrieving the id in the AjaxController, you can simply use the Request $request variable.
public function getPermissions(Request $request)
{
//dd($request->all())
//dd can be use to die and dump the all variable values
return $request->id;
}
Viewing in the console, it will display the Ajax Request Id.
You can use this way
$data = $this->route('parameter_to_access');
return $data

POST variable always stays empty

This is the method in which i manage the data send with jquery.ajax. By default is send an empty string and on each change i watch the change on the input and resend it. Through console things are good but in php $this->searchField always has the value of an empty string
function checkInfo(){
if(isset($_POST['searchField'])){
$this->searchField = json_decode($_POST['searchField']);
if ($this->searchField != ""){
$this->query = "SELECT * FROM myguests WHERE firstName like '%".$searchField."%'";
}
else if ($this->searchField == "") {
$this->query = "SELECT * FROM myguests ORDER BY id";
}
$this->tableDisplay();
exit();
}
else{
return "error";
}
}
This is my jquery ajax function :
function searchGuests(users){
var data = {
"searchField": users
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};
Any idea what I am missing?
Try encoding the users to a string before sending it over.
function searchGuests(users){
var data = {
"searchField": JSON.stringify(users);
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

CodeIgniter Ajax call

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

Categories