I want to send the data I received by Ajax to the RestController with POST method and process it there. Then I want to return the list that will be created as a result of the transaction to Ajax.
Controller
#Controller
public class AjaxController {
#GetMapping("/web")
public String web()
{
return "fake";
}
}
Fake.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
$(function () {
$("#ajaxselect1").on('change', function () {
var selectedValue1 = $("select[name=ajaxselect1]").val();
$.ajax({
type : "POST",
url : "/ajaxrest",
data: {item: selectedValue1},
success : function(data){
}
});
});
});
});
</script>
</head>
<body>
<h1>AJAX TESTING</h1>
<div class="row">
<div class="col">
<select name="ajaxselect1" id="ajaxselect1" class="form-control" >
<option value="Chose" selected>Chose</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
</body>
</html>
RestController
#RestController
public class AjaxRest {
#PostMapping("/ajaxrest")
public String testAjaxPost(#RequestParam("item") String item) {
if(item.equals("1")){
List<String> cars = new ArrayList<>();
cars.add("bugatti");
cars.add("ferrari");
cars.add("honda");
cars.add("mercedes");
}
}catch (Exception e){
}
return "hello-world!";
}
}
When I'm not sending any data, Chrome Console returns this information to me:
Chrome Console Error
jquery.min.js:2 POST http://localhost:7070/ajaxrest 404
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # web:26
dispatch # jquery.min.js:2
y.handle # jquery.min.js:2
ListPicker._handleWindowTouchEnd
POST method does not work. How do I run it with POST method? How do I send data between Ajax and RestController?
What exact AJAX error you are getting ? As your if loop looks good, but this might help,
#RestController
public class AjaxRest {
#PostMapping("/ajaxrest")
public Object testAjaxPost(#RequestBody String item) {
if(item.equals("1")){
//If the incoming data is 1, I want to send this list to Ajax.
List<String> cars = new ArrayList<>();
cars.add("bugatti");
cars.add("ferrari");
cars.add("honda");
cars.add("mercedes");
// Send list of cars
return cars;
}
else{
// Your business logic
return "your_value";
}
}
}
Related
I am creating an ASP.NET Core 6 MVC application.
In my _Layout.cshtml I have a menu that the option calls a method in the controller that renders a View in #RenderBody()
Simplifying, the menu is like this
<li><a class="nav-link link-light" asp-controller="Employer" asp-action="Index">Employer Setup</a></li>
The controller is like this
public IActionResult Index()
{
var sessionValue = HttpContext.Session.GetString("Header");
HeaderViewModel header = JsonSerializer.Deserialize<HeaderViewModel>(sessionValue);
return View("Index", header);
}
Under certain circumstances, I also need to call this action by Ajax. I have define this in my _Layout.cshtml:
<div>
<main id="main" role="main" class="pb-3">
#RenderBody()
</main>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax(
{
type:"POST",
url: '#Url.Action("Index", "Employer")',
success:function(result){
$("#main").html(result);
},
}
);
</script>
The problem I have is that the controller returns a view, so the entire layout is rendered again in the body section, instead of rendering only the new view. So I have to return a partial view instead of a view.
I do not want to duplicate the method to retrieve the same data.
Is there a way to return a view?
in view
<script type="text/jscript">
$(document).ready(function () {
$("#partialviews").load('/controller/actionmethod');
});
in controller
public PartialViewResult ActionMethod()
{
return PartialView("_partialviewname");
}
return View("Index", header);
Because you return view, so the the entire layout is rendered again in the body section.
You can create a new action to display the content.
HomeController:
public IActionResult Index()
{
return View();
}
public ContentResult TestData(string header)
{
header = "sss";
return Content(header, "text/plain");
}
Layout:
<div>
<main id="main" role="main" class="pb-3">
#RenderBody()
</main>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '/home/TestData/',
success: function (result) {
$('#main').html(result);
}
});
});
</script>
Result:
I try to make an autocompletion search to my laravel application , but i get an error when i inspect my browser i get " b.toLowerCase is not a function "
Here my controller for Autocomplete :
public function autocomplete(Request $request){
$data = Licencies::select("lb_nom")->where("lb_nom","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
}
Here my view Input :
#section('content')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
Here my script :
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>
Someone knows why i get
b.toLowerCase is not a function
Many thanks in advance
Try this:
$data = Licencies::select("lb_nom as name")
I wrote the below code; when I select India/America in the dropdown related text files with some contents, has to be read and displayed inside a div element, but am getting an error in the line xhr.send()
can anyone explain why??
<html>
<head>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
after searching the internet I was unable to find an answer as to why my AJAX code is not working. My assignment is to retrieve a text file and display it to the browser using AJAX but the ready state stops at 1. an example file is canada.txt and is located in the directory http://157.201.194.254/~ercanbracks. The .html and .js files are below:
HTML file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js file:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}
I wrote this code in javascript to disply information in this page (Normal_Info.php),
but unfortunately it did not work. If anyone can help me I will be grateful
<html>
<head>
<script language="javascript">
function ajaxFunction()
{
return window.XMLHttpRequest ?
new window.XMLHttpRequest :
new ActiveXObject("Microsoft.XMLHTTP");
}
function Go_there()
{
var httpObj = ajaxFunction();
httpObj.open("GET","Normal_Info.php", true);
httpObj.send();
httpObj.onreadystatechange = ChangedState()
{
if (httpObj.readyState == 4 && httpObj.status == 200)
{
document.getElementById("result").innerHTML=httpObj.responseText;
}
}
}
</script>
</head>
<body>
<form id=ff>
<input type=button value=Hi OnClick=Go_there() />
</form>
<div id=result>
</div>
</body>
</html>
i suggest using jquery http://jquery.com/
<script src="jquery.js"></script>
<script language="javascript">
$('#ff').submit(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('#result').html(data);
// alert('Load was performed.');
}
});
});
</script>
no need to click event