How to use ajax with autocomplete in jquery - ajax

I have the following jquery with ajax call? My webservice returns dataset.
Here is the code:
$(document).ready(function(){
$('#ctl00_ContentMain_ddlRegions').change(function(){
region = $(this).val();
alert(region);
});
});
$('input[type="text"]').autocomplete({
$.ajax({
async: true,
type: "GET",
url: "~/EmailActivation/EmailActivation.asmx/GetIsoFromRegion",
data: "{'option':'" + region + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(data,status){
alert("success");
}
});
minLength: 4 });
});
Right now there is an error in my code so, I cannot even display alert to show region. Error is generated from autocomplete section.
When I remove autocomplete section, script works.
What do I need to change and how can I make my autocomplete work with the data coming from webservice?
Thank you

Related

AJAX with JSON fails to show up in Internet Explorer

I'm trying to display Wordpress blog posts on a different domain. It displays on all browsers except for IE.
Here's my code:
$.ajax({
url: 'www.whatevermywordpresswebsiteis.com/wp-json/wp/v2/posts?_embed&per_page=100',
crossDomain: true,
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: 'GET',
async: false,
data: { action : 'get_ajax_posts' },
success: function(data) {
$.each(data, function(i, _post) {
console.log(data);
});
}
});
I've tried to implement XDomainRequest as well but it still fails to work (Jquery $.ajax fails in IE on cross domain calls). I'm not sure what to do at this point.

.ajax JSONP parsererror

I'm trying to use an ajax call to bring back data from a web api. I wrote 2 similar functions and neither work. I can see the data come back through Fiddler, but it won't go to the success call, for both of the functions below. What am I doing wrong? The data comes back in both functions in Fiddler, it just doesn't go to success.
Here is attempt 1:
function PopulateDivisions()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert(data);
$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
},
error: function(xhrequest, ErrorText, thrownError) {
alert("Original: " + thrownError + " : " + ErrorText);
}
});
}
Error: jQuery19102671239298189216_1382022403977 was not called : parser error
Here is the data Fiddler is showing comes back:
[{"Id":1,"Description":"Executive","Name":"Executive "},{"Id":2,"Description":"ASD","Name":"Administrative Services Division "},{"Id":3,"Description":"COM","Name":"Communications "},{"Id":4,"Description":"CP","Name":"Contracts and Procurement "},{"Id":5,"Description":"PMD","Name":"Program Management Division "},{"Id":6,"Description":"RED","Name":"Research and Evaluation Division "},{"Id":7,"Description":"IT","Name":"Information Technology "}]
Here is attempt #2:
function PopulateDivisions2()
{
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisionsJsonP',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function(data) {
//data = JSON.parse(data):
alert(data);
$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
},
error: function(xhrequest, ErrorText, thrownError) {
alert("PopulateDivisions2: " + thrownError + " : " + ErrorText);
}
});
}
Error: myJsonMethod was not called : parsererror
Here is the data Fiddler shows is coming back:
"myJsonMethod([{\"Id\":1,\"Description\":\"Executive\",\"Name\":\"Executive \"},{\"Id\":2,\"Description\":\"ASD\",\"Name\":\"Administrative Services Division \"},{\"Id\":3,\"Description\":\"COM\",\"Name\":\"Communications \"},{\"Id\":4,\"Description\":\"CP\",\"Name\":\"Contracts and Procurement \"},{\"Id\":5,\"Description\":\"PMD\",\"Name\":\"Program Management Division \"},{\"Id\":6,\"Description\":\"RED\",\"Name\":\"Research and Evaluation Division \"},{\"Id\":7,\"Description\":\"IT\",\"Name\":\"Information Technology \"}]);"
contentType: 'application/json; charset=utf-8' Tells your server that you are sending JSON data, but you don't have any data you are sending. Try leaving that setting out.
If you were to brows to your url in the browser do you get json back?
I'm not sure if this would matter, but I would remove the error setting because it says in the jQuery Ajax documentation that This handler is not called for cross-domain script and cross-domain JSONP requests.
I would try to run this with the least amount of configuration like this:
$.ajax({
url:'http://IP/Service/api/DivisionSearch/GetAllDivisions',
dataType: 'jsonp',
success: function(data) { console.log(data); }
});
See if this works and then build on top of it. Without jsfiddle it's hard to debug what's going on.
Here is a link that should be a good resource for you: Basic example of using .ajax() with JSONP?
function PopulateDivisions2(){
$.support.cors=true;
$.ajax({
type:'GET',
url:'http://IP/Service/api/DivisionSearch/GetAllDivisionsJsonP?callback=?',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
jsonpCallback: "myJsonMethod" });
function myJsonMethod(data) {
//data = JSON.parse(data):
alert(data);$("#divisionSelect").append($('<option></option>').val("-99").html("Select One"));
$.each(data, function(i, item){
$("#divisionSelect").append($('<option></option>').val(item.Name).html(item.Name));
});
}}
Can you try the above code? I have removed the success callback and included callback in query string.

Ajax post parameters ASP.NET MVC 3

Hello guys i have the next ajax call for login. I serialize the form and send the data to server and return redirect url link. My problem is that my url after post is like
http://localhost:50802/?username=&password= and not http://localhost:50802/Home
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
alert(result.link);
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
It looks like you wrote this $.ajax call in the .click event of a submit button or in the .submit event of a form without canceling the default action by returning false from the callback or by calling preventDefault on the argument. Here's how your code should look like:
$('#id_of_your_form').submit(function(e) {
e.preventdefault(); // <-- That's what I am talking about and what you forgot
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
});
Also async: false,????? You know what this does, do you? That's not AJAX. That's a blocking synchronous call to your webserver during which the client browser would be frozen like during the Ice Age 2 ruining all user experience.
Try returning false at the end of your submit function
$('#id_of_your_form').submit(function(e) {
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
return false; });
Another option would of course be to return the correct redirectlink from the controller instead of overriding it in the java script.

In MVC calling webservice with ajax call not working give error code 404?

In my .net framework with MVC calling webmethod like. webservice1.asmx/helloWorld
with Ajax give error 404 not found..In my another server same code working. Is there
anything missing to call ?? and physical path give me same webserive and webmthod in my .net project.. please help me ..
EDIT
code to call the web service
$.ajax({
type: "POST",
url: "/WebServices/WebService1.asmx/HelloWorld",
data:"{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
var data = msg.d;
},
error: function(msg) {
alert(msg);
}
});
I suspect that you have hardcoded the url to the web service in your javascript call instead of using an url helper to generate it. So try like this:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "#Url.Content("~/WebServices/WebService1.asmx/HelloWorld")",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(msg) {
var data = msg.d;
},
error: function(msg) {
alert(msg);
}
});
</script>
Notice how the url to the web service is no longer /WebServices/... but it is generated with an url helper. So if for example you deploy your application in a virtual directory in IIS the helper will take into account this virtual directory.

AJAX on click not calling/loading as it should

I have been learning AJAX for the best part of 2 hours, trying to get my head around how to get this to work, it seems it is calling the function as if I put an alert in, it all works fine.
I tried using another method and it seemed to call the function on it's own and it would load what the .php page is echoing.
What am I doing wrong in order for it to not work at all?
<script type="text/javascript">
$('a.fire').click(call_ajax);
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
</script>
Edit: I have also just tried
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
Which also does not work.
EDIT: I have now got code that GET's the php file I wanted, but for some reason does it on it's own
<script type="text/javascript">
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$('a.fire').click(call_ajax());
});
});
The issue with this code is that it fires on it's own
EDIT: Now have new code, that is attempting to fire according to Firebug console but I get the alert ERROR: error, so I don't have a clue what is happening in order for it to fail, I have also tried many different URL's with no working solution
$('a.fire').click(function () {
$.ajax({
type: "GET",
url: "/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
},
error:function(xhr, text, error){
alert("Error: " + text);
}
});
});
SOLVED: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page
ajax will only work if it's the same domain. This means that if you execute jQuery from domain x to domain y, it won't work. This is for safety-reasons to prevent websites from loading from another website. Does your jQuery-ajax call work if you remove the 127.0.0.1 from your url?
Furthermore I guess you should add the click-function inside your $(document).ready(); function, like this:
$(document).ready(function(){
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
});
for testing purposes, you can also use the complete function inside your ajax and alert your data. firebug can be helpful too to find your problem :)

Resources