CodeIgniter Access Controller from PHP Require - javascript

I am using codeigniter for my project and I am stuck trying to figure this out.
I have some javascript that needs to perform an AJAX call to fetch some results based on a dropdown value that was selected.
function fetchLines(){
$.ajax({
url: baseURL + "resources/ajax.php?node=fetchLines",
type: 'GET',
cache: false,
data: {
lineType: 'business'
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
In this AJAX file, I am trying to include my controller and then access the function within it.
<?php
define('BASEPATH', "AJAX");
require_once('../application/controllers/Project.php');
switch($_REQUEST['node']){
case 'fetchLines':
$objLines = new Project();
$objLines->fetchLines($_REQUEST['lineType']);
break;
}
?>
My CI Controller then has a private function in it which I am trying to call to get the data I need:
private function fetchLines($lineType){
$lines = $this->project_model->fetchLines($lineType);
return $lines;
}
My goal here is to have an AJAX file or controller (if needed) be used for all my AJAX calls. It needs to be able to access a controller and return data.
With the current code above, I am getting the error: Class 'CI_Controller' not found in <b>C:\xampp\htdocs\blueprint\application\controllers
\Project.php
Is there a better way to handle situations like this? I'm not an expert with OOP but some reading suggested something along these lines.

why you are not sending this request to the controller method instead ?
function fetchLines(){
$.ajax({
url: baseURL + "controller-name/method-name",
type: 'GET',
cache: false,
data: {lineType: 'business'},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
NOTE and in controller you can access these values as
function method-name(){
echo $this->input->get('lineType');
}

Lets say my ajax file is in the controllers folder
And I want to re-use my controllers, i would do it like this :
$this->load->library('../controllers/your_controller');
$this->your_controller->_some_method($data);
Load the controller as library and used it like a library.
Hope this helps.

You should put the code that listens to AJAX call in a controller function only. The way you are trying to do is not a good practice at all.
If you want a method to be executed only if the request was an XHR i.e.AJAX request then use
if($this->input->is_ajax_request()){
//your code
}else{
redirect(base_url())
}

Related

Ajax post not sending data to c# API Controller

I am trying to use $.Ajax() function to post data after a triggered event to my controller, but the data is not being sent. If I change the same function to "GET" method instead of "POST", it sends the data correctly, so I guess it has something to do with the VS2019 ASP.NET web project configuration, but I cannot find what it is.
The front code I am using is as follows:
marker.on('click', function (ev) {
let id = ev.target.features.properties.id
$.ajax({
url: "/public/pushDocuments",
method: "POST",
data: {
id: id,
objectname: "Prueba2",
bucketkey: "Prueba2"
},
contentType: "JSON",
success: function (data) {
launchViewer(data.urn);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
and in the server side:
[HttpPost]
[Route("public/pushDocuments")]
public async Task<IActionResult> postDocument(string id, string objectname, string bucketkey)
{
//Code here
}
but, as I said, the server is not getting the information. Nevertheless, if I change the method to GET in the server and front, I do get the data I am sending, but it is not the correct way to do it, as the work I want to do inside the server function is to save some data to a database. I have done it multiple times in other project and works, but I cannot figure out why it is not working on this one.

Opening new page passing parameters without showing them on the URL

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

Call php function with jquery using ajax

I'm trying to call a php function that is defined on a php file.
On the php file I have this that will call the function
if(isset($_GET))
{
submit(); //Do something with your GET
}
But I'm getting an error when calling the php function within the jquery. I imagine it could be a path problem. The jquery file is in js/file.js and the php function is on data/php/function.php so I try it calling it like this.
$.ajax({
url: "../data/php/functions.php&paperid="+$('#table-paperid').text(),
type: "GET",
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
But no matter what I write on the url I always get the exception error. Any ideas?
It's better practice to use a POST ajax call in this case. You should also put the "type" property before the "url" field, although, I doubt this is the source of the error. Try an ajax call that looks something like this.
$.ajax({
type: 'post',
url: '/some/path',
data: { paperid : $('#table-paperid').text()},
success: function(data) {
var response = JSON.parse(data);
}
})
and your php should be modified to.
if(isset($_POST['paperid']))
{
submit(); //Do something with your GET
}
I've done this many times with no issue so hopefully this will solve your problem.
Best of luck!
You can set the query string this way as well:
$.ajax({
url: "../data/php/functions.php",
type: "GET",
data: {paperid: $('#table-paperid').text() }
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});

retrieving json data in cross domain

I need to make a ajax call to retrieve data(json) from the RESTfull Web Service which is running in the different domain(KARAF using cxf) and the client from which the ajax call is being made, is on different domain(Apache Tomcat).
The Web Service is returning the data in the form of MediaType.APPLICATION_JSON but due to cross domain call I am receiving the data in the form of jsonp object.
$.ajax({
url: "http://localhost:8181/cxf/view/ID_123",
type: "GET",
crossDomain : true,
contentType: "applicaion/json",
dataType : "jsonp",
jsonpCallback : 'myJsonCallBack',
sucess : function(json) {
alert("Success Called");
},
error : function(xhr) {
alert("Error");
}
});
and the myJsonCallBack funcation is as below..
function myJsonCallBack(data) {
alert("Callback Called");
}
The web service method is as below..
#GET
#Path("/view/{userid}")
public ViewPreference getViewPreference(#PathParam("userid") String userId) {
ViewPreference viewPreference = new ViewPreference("GRID VIEW");
return viewPreference;
}
which is returning json object as below..
{
"viewPreference": {
"preference": "GRID VIEW"
}
}
The problem is when ever I make a ajax call neither the success callback runs nor the myJsonCallBack only error is run.
while checking in firebug it is showing some syntax error telling SyntaxError: missing ; before statement {"viewPreference":{"preference":"GRID VIEW"}}.
How to resolve this problem..?
here's what you should do:
you should return this from the server:
'myJsonCallBack({"viewPreference": {"preference": "GRID VIEW"}})'
rather than this: {"viewPreference": {"preference": "GRID VIEW"}}
this will call the myJsonCallback function and others without syntax errors
hope this helps :)

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Categories

Resources