ajax get boolean value from C# function T4MVC - javascript

I have a research bar on my website, the code for it is the following:
<form onsubmit="return IsValidCustomer()">
<input class=" sb-search-input" placeholder="Chercher un client..." type="text" value="" name="search" id="search">
<input class="sb-search-submit" type="submit" value="" id="submit-search">
<span class="sb-icon-search"></span>
</form>
As you see, it calls a javascript function:
function IsValidCustomer() {
var name = document.getElementById('search').value;
$.ajax({
type: 'GET',
url: lookForCustomerUrl,
data: {'name' : name },
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (e) {
alert(e.value);
}
});
return false;
}
Which will call my c# function, to see if the customer I'm looking for actually exist. If it does, for the moment, I just want to show the result, which is suppose to be True or False. But I'm only getting the error alert...
Here's my C# code, in my controller:
public virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}
The SearchClient function you see is working fine and the returned boolean is correct.
Thanks for help... I just want to save a unnecessary page...

When you make an ajax call from an aspx page to a method in the code-behind, you need to decorate the method with an attribute [Webmethod].Also, it needs to be a static method. That means, you would also need to change 'SearchClient' to a static method if it isn't so.
[Webmethod]
public static virtual bool LookIfCustomerExist(string name)
{
List<Customer> customers = SearchClient(name);
bool returnedValue = customers.Count != 0;
return returnedValue;
}

Related

Ajax passing data to ASP.NET controller

I'm attempting to run an ajax request on my ASP.NET web app where I pass a search term and receive some data back
<div class="form-group">
<input type="text" id="orgSearch" placeholder="Search organisation by name..." class="form-control" name="search" autocomplete="off" data-controller="#Model.ControllerName" data-target-property="#Model.LookaheadProperty">
</div>
<script>
$(document).ready(function () {
var form = document.getElementById("orgSearch");
form.addEventListener("keyup", function (event) {
event.preventDefault();
var search = document.getElementById("orgSearch").value;
$.ajax({
type: "GET",
url: "Organisation/Search?search=" + search,
success: function (object) {
console.log(object);
}
});
});
});
</script>
And then here's the method in my OrganisationsController.cs class
public class OrganisationsController : Controller
{
[HttpGet]
public async Task<IActionResult> Search([FromRoute] string search)
{
var items = await _organisationsService.SearchAsync(search);
return Ok(items);
}
}
However, when I try it the ajax call isn't even being made (It's generating a 404 error on the console log) and I can't work out how to pass the search parameter. Does anyone have any suggestions?
Fix ajax url from organization to organizations and add "/" in the beginning:
url: "/Organisations/Search?search=" + search,
your action then
public async Task<IActionResult> Search([FromQuery] string search)
{
......
}
You can also try to use [FromUri] instead [FromQuery]
And by the way, if your version Mvc supports attribute routing, it maybe better to change action to this:
[Route("~/Organizations/Search/{search}")]
public async Task<IActionResult> Search( string search)
{
....
}
in this case your ajax url:
url: "/Organisations/Search/" + search,

POST Form Submission in JQuery/AJAX and PHP

I'm a bit new to working with form submissions in JQuery/AJAX and PHP, so I've been trying to follow some tutorials online and have run into a few issues.
I am trying to build a form that handles submissions through PHP. Here's what I have for my index.html file.
<body>
<h1>Food Preference</h1>
<p>Please let us know what types of foods you would like to see on the menu.</p>
<form id="food-form">
<label for="appetizer">Appetizer</label>
<input type="text" id="appetizer" required>
<label for="entree">Entree</label>
<input name="entree" type="entree" id="entree" required>
<label for="dessert">Dessert</label>
<textarea name="dessert" id="dessert" required></textarea>
<button id="submit_button" type="submit">Send</button>
<p id="form_content">
</p>
</form>
And here is my index.js file
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val() +
"&entree=" + $("#entree").val() +
"&dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
And here is handler.php
<?php
class runForm {
public function handle_food_form($request) {
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
print "<p class='success'>Thank you for your opinion.</p>";
return array('post_id' => $new_post_id );
}
}
}
runForm();
?>
It doesn't seem like my submission saves anywhere, or if it does, I'm not sure how to find it. Can anyone give any pointers for anything I might be doing wrong?
I am wondering if this line in handler.php is correct, since I haven't really defined "opinion".
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"]))
You have many issues in this code snippet, and you should first check the errors that PHP shows to you and try to resolve them first.
The PHP file (handler.php)
opinion() function is not defined.
runForm() is not a function , it's a name of a class, if you want to call handle_food_form() function, then you can make it a static function and call it like this runForm::handle_food_form();
The final version of your PHP file should be something like this
<?php
class RunForm {
public static function opinion($appetizer, $entree, $dessert)
{
// do your logic here and return true or false
return true;
}
public static function handle_food_form() {
if (!isset($_POST["appetizer"])) $_POST["appetizer"] = null;
if (!isset($_POST["appeentreetizer"])) $_POST["entree"] = null;
if (!isset($_POST["dessert"])) $_POST["dessert"] = null;
if(SELF::opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
$htmlMsg = "<p class='success'>Thank you for your opinion.</p>";
/*
$con is a MySQLI object
$con->query("insert into table ........");
$new_post_id = $con->insert_id;
*/
return array('post_id' => $new_post_id, 'htmlMsg' => $htmlMsg );
} else {
return array('post_id' => null , 'htmlMsg' => "");
}
}
}
echo RunForm::handle_food_form()['htmlMsg'];
The client side
You should use encodeURIComponent() to encode the paramters of the URL to prevent something like this dessert=cheesecake&pancake from corrupting the URL, or pass an object of the parameters as the data to ajax function and jquery will do the encoding for you internally
jQuery.ajax({
url: "handler.php",
data: {
appetizer: $("#appetizer").val(),
entree: $("#entree").val(),
dessert: $("#dessert").val()
},
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
Separate the variables with commas.
In jQuery.ajax, do as like:
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val(),
"entree=" + $("#entree").val(),
"dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});

Pass null variable to MVC Controller

I want to pass a value (1) to my controller as you can see :
<input id="myButton2" type="button" value="Call Controller Method" onclick="myff('1');" />
Script:
function myff(re) {
$.getJSON('#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})', function (data) {
refid = re;
});
}
Here is my controller
public JsonResult MyControllerMethod(string refid) {
return Json("Controller Method call", JsonRequestBehavior.AllowGet);
}
But when I clicked the button the action is fired but the refid in my action is null why ?
Instead of $.getJSON(), try this code:
function myff(re) {
$.ajax({
dataType: "json",
url: '#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})',
data: {refid : re}
});
Note: Although $.getJSON() calls internally $.ajax() but the latter one gives you more flexibility- http://api.jquery.com/jQuery.getJSON/
You need to pass the value in the 2nd argument of $.getJSON()
var url = '#Url.Action("MyControllerMethod","Reception",new { area ="Admin"})';
$.getJSON(url, { refid: re }, function (data) {
console.log(data); // returns "Controller Method call"
});
I also recommend you use Unobtrusive Javascript rather than polluting markup with behavior
<input id="myButton2" type="button" data-x="1" value="Call Controller Method" />
$('#myButton2.click(function) {
var re = $(this).data('x');
$.getJSON(.....
});

how can i modify a freemarker variable value inside a success block in jQuery AJAX

how can i change a value of a freemarker variable inside a success block in jQuery AJAX, i have two controllers for my page the first one returns me a simple string with the name of the view with a GET method, the second one is the one that process the data using a json with a POST method
here they are
#RequestMapping(value = "myform", method = RequestMethod.GET)
public String formmethod(Model model) {
model.addAttribute("successMessage", "i'm in the firts controller");
return "forms/myform";
}
my second controller
#RequestMapping(value = "myform", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User userMapped= mapper.readValue(json, User.class);
User person = new Usuario();
person.setName("new name");
person.setLastName("new lastname");
model.addAttribute("successMessage", person.getName());
return toJson(userMapped);
}
my to Json method
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
and my page myform.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name= $('#name').val();
var lastName = $('#lastName ').val();
var json = {"name" : name, "lastName " : lastName };
console.log(json);
var FreeMarkervariable = "${successMessage}";
//this brings me the value that i put in the firts controller
$.ajax(
{
type: "POST",
url: "myform",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//HERE I WANT TO CHANGE THE VALUE OF MY FREEMARKER VARIABLE SO I CAN
//PRINT A SUCCESS MESSAGE IN A DIV
<#assign successMessage = "success">
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
<!-- NEW WIDGET START -->
<article class="col-sm-12">
<div class="alert alert-warning fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-warning"></i>
<strong>${successMessage} I WANT TO PRINT A SUCCESS MESSAGE HERE </strong>
</div>
</article>
<!-- WIDGET END -->
<fieldset>
<legend>Name in view</legend>
<form name="myform">
Name in view: <input type="text" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
</fieldset>
<br>
so far my freemarker variable gets the value that i put inside the success block but it appears "success" before i press my submit button, i believed that the succes block was executed after i hit the submit button so i dont know why it have the value even before i press the button it should have "i'm in the firts controller" before i press the submit button
Freemarker generates it's output on the server and this is then sent to the browser. The browser never sees any of the freemarker 'code'. You need to update the strong element using javascript/jQuery.
So instead of your <#assign...> use something like this
$("strong").text("Success");

call controller action from .cshtml page with jquery

I am trying to call a controller action from a jquery UI dialog.
What I have currently is this:
.html("<p><textarea name=\"TextMessage\" id=\"textItems\" rows=\"10\" cols=\"72\" /><br /><br /><input type=\"button\" style=\"float:right;\" id=\"submitData\" onclick=\"Test()\" value=\"Submit\" /></p>");
The script I am using to call the controller action is this one:
<script type="text/javascript">
function Test() {
$ajax({
url: '<%= Url.Action("GetData", "Report") %>',
success: function (data) {
alert(data);
}
});
};
</script>
And the controller action is this:
[HttpGet]
public JsonResult GetData()
{
return Json("success", JsonRequestBehavior.AllowGet);
}
I would like to know if I am doing something wrong, I am trying to get this to work but without any success. When I am trying directly to start the controller via http://localhost:1322/Report/GetData it works fine, so that means that the script is not setup properly.
You should try:
url:'#Url.Action("GetData", "Report")'
MVC will automatically add "Controller" to the end of the second parameter when it is looking for the controller.
Edit:
This code may work:
function Test() {
$.ajax({
type: "GET",
dataType: "json",
url: '#Url.Action("GetData", "Report")',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
alert(error);
}
});
}
Edit 2:
Changed to use Razor syntax so that this code will work with Razor/MVC3.
You are using MVC-2 syntax on Url.Action. This should work:
function Test() {
$.ajax(
{
url: '#Url.Action("GetData", "Report")',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (x, err, desc) {
alert(desc);
}
}
);
};
Because you are calling an action method that is returning a json object you can use the jQuery.getJSON() method.
<script type="text/javascript">
function Test() {
$.getJSON(
'#this.Url.Action("GetData", "Report")',
function (data) {
alert(data);
}
});
};
</script>
You may try jsaction too:
http://jsaction.codeplex.com
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '#Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detail click here

Categories

Resources