JQuery Ajax Request returns no data - javascript

I am trying out JQuery Ajax methods. I wrote a simple Ajax request to fetch certain 'tagged' photos from Flickr. Following is the snippet I am using:
function startSearch() {
$(function() {
var tagValue = $("#tagInput").attr("value");
alert(tagValue);
$.ajax({
url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tagValue + "&tagmode=any&format=json&jsoncallback",
dataType: 'json',
async: false,
success: function(data) {
alert("Success");
$.each(data.items, function(i, item) {
var pic = item.media.m;
$("<img/>").attr("src", pic).appendTo("#images");
});
},
error: function(data, error) {
alert("Error " + error);
}
}); });
'startSearch' is associated with a Search button. User is supposed to input a 'tag' to search and on click this function gets called.
Problem is that I am not receiving any 'data' in response. Hence no images gets displayed.
What am I doing wrong here?
Thanks & Regards,
Keya

I think the problem is that you're trying to make a cross-site request, which doesn't work because of security concern. You could use JSONP instead, e.g. as described in http://www.viget.com/inspire/pulling-your-flickr-feed-with-jquery/
You can also try searching for "cross site ajax" on this site, there's plenty of discussion about it.

Related

is that possible to make ajax call to external web page?

is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}

Jsonresult is failing with parameter in my Ajax Call. Why is it happening?

That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.

Get content of paginated pages via ajax, filter it and append it to current page

I would like to load more functionality on my blog. I now have paginated pages, which is not what I want. I thought it would be easy to get the contents of these paginated pages via ajax, filter it, and append it to a div.
I'm not really sure if this is the way to go. This is what I tried:
$("a.next").on("click", function(e){
e.preventDefault();
var nextLink = $(this).attr("href");
console.log(nextLink);
$.ajax ({
url: "http://localhost:8888/" + nextLink,
datatype: 'html',
type: "GET",
success: function(data) {
var response = data;
$(".blogItems .holder").append(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Can you guys point me in the right direction?
Your solution would work, providing that you'd detect the ajax call in the back end, and instead of the entire page, return just the parts where you are interested in (use Director::is_ajax() for that, and follow the hints in the comment of #micmania). If you would rather not make your controllers more complex and you don't mind the extra data being sent, you could also just retrieve the entire page (as you are doing now), and pick just the parts that you want to append to your existing document:
$.ajax ({
url: "http://localhost:8888/" + nextLink,
datatype: 'html',
type: "GET",
success: function(data) {
var response= $("#theDivIWant", data); //<- Here (untested, but should do the trick
$(".blogItems .holder").append(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
This solution also degrades nicely for people not using javascript, although I'm not exactlye sure if that's of any added value these days :-)

Client Side Ajax with jQuery reading a JSON

I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});​
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
​
Fiddle
Also I've set a charset accordingly to service documentation.

asp.net mvc how to save data from jquery control

I am using the TinyMCE control in a MVC page, and now I want to save the content of the control (hopefully with ajax so the page is not rendered again)... I have some javascript that looks like this:
mysave = function() {
var ed = tinyMCE.get('content');
// Do you ajax call here, window.setTimeout fakes ajax call
ed.setProgressState(1); // Show progress
window.setTimeout(function() {
ed.setProgressState(0); // Hide progress
alert(ed.getContent());
}, 3000);
};
What is the best way to pass the content back to the controller, save it, and return back to the same page?
well, use jQuery.ajax. http://docs.jquery.com/Ajax. I suggest you to use POST request so you can transfer arbitrary long texts.
How do you plan to save the text? Do you use any database engine? we need more information.
$.ajax({
url: "/controller/savetext",
cache: false,
type: "POST",
data: { text: ed.getContent() },
success: function(msg) {
alert("text saved!");
},
error: function(request, status, error) {
alert("an error occurred: " + error);
}
})
and on server side something like this:
string text = Request.Form["text"]

Categories