unable to execute javascript jquery function - javascript

I have a Jquery autocomplete function through callback method. However it doesn't seem to run.
Here is my code:
At Client-Side:
<script type="text/javascript">
$(document).ready(function() {
alert("hi");
$("#Text1").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'BlissMaker.aspx/GetNames',
data: "{ 'sname':'" + request.term + "' }",
dataType: "json",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Id
}
}))
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
},
focus: function (event, ui) {
$("#Text1").val(ui.item.label);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><img src='" + item.icon + "' width='32' height='32' /> " + item.Name + "</a>")
.appendTo(ul);
};
}
</script>
At Code-Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<States> GetNames(string sname)
{
List<States> sbStates = new List<States>();
con = new SqlConnection("Data Source=PRATEEK\\SQLEXPRESS;Initial Catalog=BD;Integrated Security=True;Pooling=False");
con.Open();
Me mee = (Me)Session["Me"];
qr = "SELECT FBFriends.FB_Id2, ActiveInfo.Name, ActiveInfo.Profile_Pic, ActiveInfo.Gender FROM [FBFriends],[ActiveInfo] WHERE FBFriends.FB_Id1='" + mee.Id + "' AND ActiveInfo.FB_Id=FBFriends.FB_Id2";
ds = new DataSet(qr);
da = new SqlDataAdapter(qr, con);
da.Fill(ds);
ds.Tables[0].Select(ds.Tables[0].Columns[1].ColumnName + " Like '%" + sname + "%' and " + ds.Tables[0].Columns[3].ColumnName + " = 'Female'");
foreach (DataRow row in ds.Tables[0].Rows)
{
States st = new States();
st.Id = row.ItemArray[0].ToString();
st.Name = row.ItemArray[1].ToString();
st.Value = row.ItemArray[1].ToString();
st.Icon = row.ItemArray[2].ToString();
sbStates.Add(st);
}
return sbStates;
}
It seems that autocomplete function is not getting called as well as Alert()..
Any suggestions on how to call it?
ADDED:
After checking the stack trace, it gives me an error
Unknown Method name GetNames
Any suggestions?

You forgot one closing at the end ")";
$(document).ready(function() {
})
After fixing that part check the response and request in console of firebug or such.

Try cleaning up the code errors and run it again:
Problem at line 19 character 43: Missing semicolon.
}
Problem at line 20 character 41: Missing semicolon.
}))
Problem at line 39 character 13: Expected ')' and instead saw ''.
}
Problem at line 39 character 13: Missing semicolon.
}

Is $(document).ready() getting called at all? If not, is you javascript in a separate file? If so, maybe the file itself is not reachable and the ready() function isn't even being called. Check the <script src=""></script> tags for including the JQuery files and your javascript file.

I'm not sure if this is causing your problem or not, but I noticed in your JQuery $.ajax call you had this line here:
data: "{ 'sname':'" + request.term + "' }",
I've found ajax calls to fail if I concat variables and strings in the data: field of the $.ajax call.
Try this:
declare a variable outside the call like this:
var dataToSend = "{ 'sname':'" + request.term + "' }";
then change the data: field to this:
data: dataToSend,
This may or may not solve your problem, but it looks nicer! Try it anyways!

Thank You everyone. I finally got my mistake.
The Web Method needed to be Static in order to call it and also ScriptManager included in the form must be EnablePageMethods=true
My code is working all fine now. Thanks a lot :)

Related

AJAX call fails with SyntaxError: Unexpected end of JSON input

Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify

Jquery-ajax doesn't succeed

I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).

How to make ajax call and get results back while typing in input text

I want to implement some functionality which is when I enter some text in
<input path="tags" id="input-search"/>
there should appear a list of suggested tags just like
after making ajax call. I have database query
public interface TagRepository extends JpaRepository<Tag, Integer> {
#Query("SELECT t FROM Tag t WHERE name LIKE CONCAT('%', :name, '%')")
List<Tag> findTagByName(#Param("name") String name);
}
and the controller code is
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Tag> getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return tagService.findTagByName(tag.getName());
}
javascript for ajax is
$(document).ready(function() {
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({tag : request.term}),
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="login-username">Tags</label>
<form:input path="tags" cssClass="form-control" id="tag-search"/>
</div>
when I run the app I see this javaScript error in Developers Tools
Important
I'm using Daemonite/material for my front-end & jQuery-Autocomplete, finally a good thing is that the latest version of App is on GitHub
can any one tell me how can I get rid of that error any response is welcome.
for the problem above i mostly use select2 jquery plugin. it's has a lot of build in feature, so no need of reinventing the wheel. check this link out for a demo - http://select2.github.io/select2/#infinite
screen shot:
code sample:
$("#e7").select2({
placeholder: "Search for a repository",
minimumInputLength: 3,
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
quietMillis: 250,
data: function (term, page) { // page is the one-based page number tracked by Select2
return {
q: term, //search term
page: page // page number
};
},
results: function (data, page) {
var more = (page * 30) < data.total_count; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.items, more: more };
}
},
formatResult: repoFormatResult, // omitted for brevity, see the source of this page
formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
now layout is not exactly same as screenshot you provided, but check if this layout work for you.
Update:
function repoFormatResult(repo) {
var markup = '<div class="row-fluid">' +
'<div class="span2"><img src="' + repo.owner.avatar_url + '" /></div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="span6">' + repo.full_name + '</div>' +
'<div class="span3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="span3"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function repoFormatSelection(repo) {
return repo.full_name;
}
Another approach:
Hi if above solution not fit for your problem then you can use this one instead. it's called typeahead.js a JavaScript library provide by twitter. you can find examples here.
Check jquery vendor library is loaded properly or not.
To cross check:
<script>
if (window.jQuery) {
alert('jQuery is loaded');
} else {
alert('jQuery is not loaded');
}
</script>
It simply means that you are getting HTML instead of JSON in response.
"Unexpected <" is referring to the first character of your request's response.
in chrome console you can go to network tab and click on your request and in the right side see what exactly your server is returning back to client.
You missed jquery.js. Add it and you'll get it working.
I am adding the codes here so that it would be better readable;
Write a new method to parse json on Java side before returning to jquery. Current code returns Java list as output for Ajax and this would possibly throw Uncaught syntax error : Unexpected token.
public static String toJSON(Object object)
{
if ( object == null ){
return "{}";
}
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
catch (Exception e) {
e.printStackTrace();
}
return "{}";
}
for the above piece of code you need to include 3 jars jackson-core-2.2.3.jar, jackson-annotations-2.2.3.jar and jackson-databind-2.2.3.jar.
Change you controller as following;
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return toJSON(tagService.findTagByName(tag.getName()));
}
$(document).ready(function() {
var autoCompleteResult = '';
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({tag : request.term}),
dataType: "json",
success: function(data) {
autoCompleteResult = jQuery.parseJSON(data);
response($.map(autoCompleteResult, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
Please share your results after trying this.
Try this:
https://github.com/tanwaniniranjan/autosuggest
It's a plugin made for the same purpose. very less documentation, but i hope to put up the documentation soon.
Yu can read the comments in the js file to get an idea on the usage
Edit:
I now read your question more carefully,
what is happening is:
the response that you are getting from the server side is giving an error.
the error will usually start like sorry bro, 404
since you are trying to map the data, jQuery just cant parse it, and it gives you the error.
check your server side first. use the postman plugin to make requests, verify your response and then implement jQuery: https://chrome.google.com/webstore/detail/postman-launcher/igofndmniooofoabmmpfonmdnhgchoka?hl=en
As i see there could be a issue of 500 internal server error because you have a dataType: "json", in your ajax while at your controller you aren't returning any json.
#RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Tag> getTags(#RequestBody Tag tag, HttpServletResponse response) {
System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size()));
return tagService.findTagByName(tag.getName());
}
Here at your conroller this: produces = "application/json" says it will return json as output and with this: return tagService.findTagByName(tag.getName()); you can producing any json.
Just add below tag to your ajax call
contentType: 'application/json; charset=utf-8',
This is the type for requested data,in your case it simply text format that you type in text box
And remove below line from your ajax call if your response data is not json type
dataType: 'json',
This may remove Json Parsing Error in your code
Change your JavaScript as the below
$(document).ready(function() {
$("#tag-search").autocomplete({
source: function(request, response) {
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/app/getTags/",
type: "POST",
data: JSON.stringify({'tag' : "'"+request.term+"'"}),
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
console.log();
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});

Call ajax in file .js

i have a problem with this :
function inicioConsultar(){
$(function(){
$('#serviciosU').change(function(){
if ($('#serviciosU').val()!= "-1")
{
$.ajax({
url: "#Url.Action("ObtenerCapas")",
data: {urlServicioUsuario:$("#serviciosU :selected").val()},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#capas").html(items);
}
});
}
})
});
I put in my Index.cshtml "inicioConsultar()" and there is a problem with ajax, because if i delete the call ajax everything it is ok.
In loyout, i load jquery and the index it is inside layout.
Sorry for my english.
This is a syntax error:
"#Url.Action("ObtenerCapas")",
That isn't how strings work in JavaScript. You need to escape the inner double quotes, as they're terminating the string.
Try
"#Url.Action(\"ObtenerCapas\")",
However, that wont' solve your problem, unless #Url.Action(...) is a real URL on your server, or your AJAX set has some kind of ability to evaluate that string as a function call.

Parse JSON string to use in AJAX success call

I have code that generates a JSON string. An example string that is generated by that code is as follows. I have validated it through the JSON lint tool and it validates perfectly.
{"ShipToName" : "( ) CARPINTERIA CA", "ShipToAddress1" : "3785 SANTA CLAUS LANE", "ShipToAddress2" : "", "ShipToCity" : "CARPINTERIA", "ShipToState" : "CA", "ShipToZip" : "93013", "ShipVia" : "UPS", "Terms" : "01", "SalesRep" : "KV1" }
I then have some JQuery that is going to parse that string. Right now I am just trying to alert one of the parts of the string to be sure the code is working correctly. I have tried both of the following with no success:
Attempt #1: Alerts 'undefined'
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
Attempt #2: throws an error inside of a JQuery library object
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
Any ideas on how I can access each of the items in the JSON String?
Thanks!
since your code does not throw an undefined exception, then we can deduce 'msg' is not undefined.
Use a debugger to see what your msg really contains:
alert(msg.SalesRep);
console.log(msg);
note: contentType should be 'charset=utf-8', not 'character=utf-8'. also the string you're sending is not valid json. It should be double quoted instead of using single quotes.
So the answer was really simple once I checked the console log. I added this line of code and I was able to begin accessing everything in the JSON string:
var obj = $.parseJSON(msg.d);
This makes no sense:
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
It should just be
var strData = { strSoldToSelected: strValue, strShipToSelected: strShipToVal };

Categories