Can not make ajax call to server - javascript

I've tried to use ajax in Spring MVC App but it seems not working I searched for that and found many resources but as I'm not a pro I could not understand any of those, finally I found this tutorial as a grace and tried in Controller as
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
and javascript is
$(document).ready(function() {
$(function() {
$("#bar-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getBars",
type: "POST",
data: { term: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
});
and finally my view.jsp is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="initial-scale=1.0, width=device-width" name="viewport">
<title>Ask Question</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"/></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="/app/resources/js/autoComplete.js"></script>
<script>
if (window.jQuery) {
alert('jQuery is loaded');
} else {
alert('jQuery is not loaded');
}
</script>
<!-- css -->
<link href="/app/resources/css/base.css" rel="stylesheet">
<!-- favicon -->
<!-- ... -->
<!-- ie -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="login-username">Bars</label>
<input id="bar-search" name="bars" class="form-control" type="text" value=""/>
</div>
</div>
</div>
<script src="/crazy/resources/js/base.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/webfont.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/jquery.autocomplete.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
</body>
</html>
every thing is ok when app starts but when I write some text down in input I get error
can any one solve this error for me or tell me where am I wrong.
sorry if my English is incorrect.

Ok... the first thing is that your service is configured wrongly.
Your service wants a #RequestParam, but in your ajax you are sending a json object which means you should be accepting a #RequestBody.
Also, if you are looking for a #RequestParam, you need to pass the value as part of the url like...
$.ajax({
url: "/app/getBars?bar=" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam(value = "bar", defaultValue = "abc", required = false) String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
or
$.ajax({
url: "/app/getBars/" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars/{bar}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#PathVariable String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
For a post.
First create a bean.
public class MyRequestBean implements Serializable{
private static final long serialVersionUID = 1L;
private String bar;
public void setBar(String bar){
this.bar = bar;
}
public void getBar(){
return this.bar;
}
}
and then write your service like this...
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestBody MyRequestBean bean, HttpServletResponse response) {
return barService.findBarByName(bean.getBar());
}
$.ajax({
url: "/app/getBars/,
type: "POST",
data: JSON.stringify({bar : request.term})
( ... )
});
NOTE: never have the verbs defining your service.
For example, /getBars can be changed to just /bars and let the HTTP protocol (GET, POST, PUT or DELETE etc..) descide which operation you are trying to perform.

Related

Setting the viewbag value from the javascript function and accessing it from another js funnction

I am having an MVC application. In the application I am calling a controller method from the javascript function using the below code:
function settingViewBagData(e) {
$.ajax({
type: "GET",
url: "/Home1/SetViewBag",
success: function (result) {
alert("Success");
},
error: function (req, status, error) {
alert("Error");
}
});
Below is the controller method:
public void SetViewBag()
{
ViewBag.data = "Test";
}
Now I want to access this viewbag data on another javascript function called on button click, which will be fired after the first function. Below is the javascript function for accessing the viewbag data:
function accessVal()
{
var variable3 = '#ViewBag.data';
alert(variable3);
}
But I am getting blank in the alert box. Please help me to fix the issue.
Thanks
You are not returning View, so it will not show VIewBag. Do this:
public class Home1Controller : Controller
{
// GET: Home1
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult SetViewBag()
{
return Json(new { Msg = "Test" }, JsonRequestBehavior.AllowGet);
}
}
The above is controller. Below is the index view:
//View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
settingViewBagData();
});
function settingViewBagData() {
$.ajax({
type: "GET",
url: "/Home1/SetViewBag",
dataType: "json",
success: function (result) {
alert(result.Msg);
},
error: function (req, status, error) {
alert("Error");
}
})
};
</script>
</body>
</html>
Now it will work.

Unable to get property 'length' of undefined or null reference for textbox autocomplete

I am trying to search company names using jquery. If search parameter does not exists in employee list, it should returns all companies. When I put breakpoint to GetCompanyList, it could not hit. But I am getting JavaScript runtime error: Unable to get property 'length' of undefined or null reference
How can I solve this error? By the way I have no idea Javascript. I have just used it for my project. Thanks your help
Demo.aspx.cs
public partial class Demo : System.Web.UI.Page
{
static List<string> allCompanyName = new List<string>() { "ankara", "adana", "istanbul" };
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetCompanyName(string pre)
{
var response = allCompanyName.Any(i => i.StartsWith(pre));
return allCompanyName;
}
}
Demo.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Demo.aspx.cs" Inherits="Demo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
$('#<%=txtCompanyName.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
url: "Demo.aspx/GetCompanyName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Auto Complete Textbox without using Web Service</h3>
<table>
<tr>
<td>Type Company Name: </td>
<td>
<div class="ui-widget" style="text-align:left">
<asp:TextBox ID="txtCompanyName" runat="server" Width="350px" CssClass="textboxAuto" Font-Size="12px" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

ASP.NET MVC 6 API and Jquery ajax problems

I made an easy service to sort a list of integers for a class using ASP MVC 6.
My ajax post request to the API on a different local host is not working correctly. The HTML/Javascript is here.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-2.0.0.min.js"></script>
<script src="Scripts/bootstrap.js"></script>
<link rel="stylesheet" href="Content/bootstrap.css" />
</head>
<body>
<form>
<input type="text" id="arr" />
<button class="btn btn-lg" id="arrbtn">Push Me</button>
<script type="text/javascript">
$("#arrbtn").click(function () {
var thing = $("#arr").val().split(' ').map(Number);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://localhost:58453/api/sort",
data: JSON.stringify({ arr: thing }),//have also tried this without stringify, encoding as string, hardcoding a json with and without stringify
}).done(function (data) {
alert("plx");
}).error(function () { alert("error");});
});
</script>
</form>
</body>
</html>
When I run this on localhost, fiddler shows me that there is no header for "Content-type application/json", and the body of the request is blank.
If I remove the contentType and dataType fields from the request, data is sent, but the header now has
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
My API promptly passes null into my action and returns a bad request.
I know my API is working correctly as I can make a fiddler post and get a proper response back.
Edit 1: Action Method on request. Here is the whole controller
Edit 2: Changed the string to array of numbers.
[Route("api/[controller]")]
public class SortController : Controller
{
[FromServices]
public ISortRepository sortArray { get; set; }
// POST api/sort
[HttpPost]
public IActionResult Submit([FromBody]SortItem item)
{
if (item == null)
{
return HttpBadRequest();
}
//sortArray.stringToInts(item);
sortArray.sort(item);
return new ObjectResult(item);
}
}

Knockout JS Script works in Chrome but not in IE9

I have a web page that works great in Chrome but not in IE9. The error that comes on the console from this error is
SCRIPT5022: Unable to parse bindings.
Message: [object Error];
Bindings value: foreach: statlist.
HTML is below:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="statsarea" data-bind="foreach: statlist">
<p> TypeCount: <strong data-bind="text: TypeCount"></strong>, Priority: <strong data-bind="text: SentDate"></strong>
<br/>
</p>
</div>
<script src="js/jquery-1.9.0.js" type="text/javascript"></script>
<script src="js/knockout-2.2.1.js" type="text/javascript"></script>
<script src="models/messagecount.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function MessageCountDataModel() {
var self = this;
var allCounts = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist = data;
}
});
})();
}
ko.applyBindings(new MessageCountDataModel());
One more piece of info is that that the json that comes out of the API looks something like this. I'm not sure if it's because the TypeCount is not a string?
[
{
"TypeCount": 102,
"SentDate": "2014-08-18T00:00:00.000Z"
}
]
It's not a good idea to use async: false. Maybe this is the problem because you don't initialize statlist as attribute in yout ViewModel. Better solution will be to make statlist to be an observable array, then make a async call and when it is ready to set the data.
Example:
function MessageCountDataModel() {
var self = this;
self.statlist = ko.observableArray();
self.loadData = function() {
$.ajax({
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist(data);
}
});
};
self.loadData();
}
ko.applyBindings(new MessageCountDataModel());

Send javascript array to server

I have an array who's content I would like to get on my server. I have been wading through internet pages trying to find how to do this without succeeding yet.
Let's imagine I have a server, and that I would like this array in my javascript to go into a file on my server, how would I do that?
I have been going through internet pages looking for how to do this and I have come up with the following code:
<html>
<!-- installs jquery and ajax. -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var arr = ["one","two","three"];
arr = JSON.stringify(arr);
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: {
myArray : arr
}
});
alert('hello');
</script>
</html>
That's an array, there's no need to stringify it, jQuery will convert the data to a valid querystring for you
var arr=["one","two","three"];
$.ajax({
url: "/urltoMyOwnSite.php",
type: "POST",
data: {myArray : arr}
});
PHP (if that's what you're using)
$array = $_POST['myArray'];
front end stuffs
<html>
<!-- installs jquery and ajax. -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function(){
var arr = ["one","two","three"];
arr = JSON.stringify(arr);
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: {
myArray : arr
}
}).done(function(data,text,jQxhr){
alert("success");
});
});
</script>
</html>
back end server (java b/c it's what I have open in dev atm)
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.json.simple.JSONObject;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.FileOutputStream;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException
{
JSONObject jsonObj = (JSONObject) org.json.simple.JSONValue.parse(request.getParameter("myArray"));
// write out your file IO.
JSONObject jsonObj = (JSONObject) org.json.simple.JSONValue.parse(request.getParameter("myArray"));
FileOutputStream file = new FileOutputStream(java.io.File.createTempFile("myArray-",Long.toString((new Date()).getTime())));
FileChannel fc = file.getChannel();
ByteBuffer sw = ByteBuffer.allocate(jsonObj.toJSONString().length());
sw.clear();
sw.put(jsonObj.toJSONString().getBytes());
sw.flip();
while(sw.hasRemaining()) {
fc.write(sw);
}
fc.close();
//because its much easier than a flat file, we can write it back in the server response.
org.json.simple.JSONValue.writeJSONString(jsonObj, response.getWriter());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException
{
doGet(request, response);
}
}
jQuery will stringify the array for you, so you are effectively encoding it twice in your example which is causing your problems. Try this:
var arr = ["one","two","three"];
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: { myArray : arr }
});

Categories