how to call ajax function from controller...in codeigniter - javascript

i need to create country drop down list in codeigniter. onchange event im calling a another controller of project thats name is ajax.php i need to know that how to get url and send data to url in codeigniter.
my ajax function is
var base_url = "<? echo base_url()?>";
function getstate(value) {
if (value !== '') {
//alert('test');
$.ajax({
type: "POST",
url:base_url+"adminzone/ajax/ajax.php",
data: "do=getstate&value=" + value,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
$('#reg1').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
my ajax controller is
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
//error_reporting(0); class ajax extends CI_Controller {
public function __construct() {
parent::__construct();
if (!$this->session->userdata('admin_logged_in')) {
redirect('adminzone');
}
$this->load->model('doctor_model');
}
public function getstate(){
echo $this->input->post();exit;
}
}

ajax function in view
$('#countryfield').change(function() {
var passedvalue = $('#countryfield').val();
var path = base_url+"ajax/getState";
$.ajax({
type: "POST",
url: path,
data: {'passedvalue': passedvalue},
success: function(data) {
if (data) {
alert(success);//task done on success
}
},
error: function() {
alert('some error occurred');
},
});
})
Now you can write function in ajax.php controller .
name of function should be getState
public function getstate(){
echo $this->input->post('passedvalue'); //now here you can perform your task
exit;
}
Now you can perform your task in controller and echo the value that you want to pass to the view.

Related

Getting exeption when sending variable via ajax

Getting an error when trying to delete a user from db.
Here is the code that i wrote:
This is server side:
#RestController
public class EmployeeRestController {
#DeleteMapping( value = "/delete_user")
public List<Employee> deleteEmployee(#RequestParam(value = "id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}
Client side:
function delete_row(id){
$.ajax({
type:'DELETE',
url:'/delete_user',
dataType: 'json',
data:JSON.stringify({
id:id
}),
success:function(data){
console.log(data);
}
});
}
Error from server side :
DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'id' is not present]
Error code from client side is 400
I am noob at ajax , javascript and spring. Sorry if the problem is obvious and thanks in advance.
did you tried this
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user",
data: { id: id },
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
or directly bind to url
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user?id="+id,
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
Try using PathVariable instead of RequestParam.
#DeleteMapping(value = "/delete_user/{id}")
public List<Employee> deleteEmployee(#PathVariable("id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}

symfony Redirect to an other page after true comparison of request from ajax

I have a function in my JavaScript that returns data. I would like to send data to my controller and do a test with that data from my js. Then, if true, I want to display another page.
$.ajax({
type: "POST",
url: path,
data: { s_certifiedNir: a.Patients[0].s_certifiedNir },
success: function (data) {
console.log('yooo' + a.Patients[0].s_certifiedNir) ;
}
,
error: function () {
alert('ko');
}
});
Here is my controller :
public function getCpsInfosAction(Request $request)
{
$nir= $request->get('s_certifiedNir');
if ($request->isXmlHttpRequest()) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$data = $serializer->normalize($nir);
if ($data=='2550699999999 34')
{
return $this->redirectToRoute('test');
}
//return new JsonResponse($data);
}
}
I got ko and There are no registered paths for namespace " DMP".
DMP is the first route of my page.
Why not just set the redirect URL in the response and handle it in your JS?:
public function getCpsInfosAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
// ...
if ($data === '2550699999999 34') {
return new JsonResponse([
'success' => true,
'redirect' => $this->generateUrl('your_route');
]);
}
return new JsonResponse(['success' => false]); // else..
}
}
Then just run the redirect from JavaScript:
$.ajax({
// ...
success: function (data) {
if (data.success) {
window.location.href = data.redirect; // <-- HERE
}
},
// ...
});

How to make a AJAX GET call in ASP.NET MVC application

I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});

Can't send data to the Controller with a POST method Symfony3

I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}

Calling controller with ajax in mvc

I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
DatabaseContext db = new DatabaseContext();
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And this is my ajax call:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
dataType: 'json',
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)
Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
....
}
Inherit you PatientController with Base Controller Class
public class PatientController : Controller
In controller
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And Specify the type of ajax calling
type: "POST" or type: "GET" ....
This will help you to fix error
Try using this, may be this works..!!
View:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
//dataType: 'json',
type:"POST", // GET or POST
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
Controller:
public class PatientController : Controller
{
....
}

Categories

Resources