Cross-domain bypass? - javascript

I am currently trying to obtain this JSON array from
http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US
However, which ever I use, it does not seem to work.
Using
$.ajax({
type: 'GET',
url: 'http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US',
cache : false,
dataType : 'json',
success: function(data){
alert('got it!');
}
}
And also tried
$.getJSON("http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US, function(data) {
});
As well as looking into a bypass for cross domain, and I tried using a proxy, not did not work, Maybe I am implementing it wrong? I can not seem to properly obtain the data (nothing return to data).
EDITED
I used this bypass php proxy to try and bypass the missing CORS and JSONP, and it does not seem to return the data correctly either (I followed an example). The php is within my directory.
$(document).ready(function() {
$("#tickBox").on("input", function(e) {
'use strict';
var tick = document.getElementById("tickBox").value;
$.ajax({
type: 'GET',
url: 'http://d.yimg.com/aq/autoc?query=goo&region=US&lang=en-US',
crossOrigin : true,
//dataType : 'json',
context: {},
success: function(data){
alert(data.ResultSet.Result[0].name);
}
});
});
});

Related

JQuery ajax get json data

how to get image url from "https://api.qwant.com/api/search/images?count=10&offset=1&q=cars" api using jquery. i'm unable to do it. bellow i've attached my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
url:"https://api.qwant.com/api/search/images?count=10&offset=1&q=cars",
type:"GET",
crossDomain : true,
async: false,
dataType: "jsonp",
jsonpCallback: "myJsonMethod",
success: function(json) {
$.parseJson(json)
},
error: function(e) {
console.log(e);
}
});
function myJsonMethod(response)
{
console.log(response);
}
</script>
Your request isn't working because of CORS, which is enabled on the API server. You need a proxy server to workaround this. For development purposes you could use a free online proxy server, your code then simplifies:
$.ajax({
url:"<PROXY:SERVER>https://api.qwant.com/api/search/images?count=10&offset=1&q=cars",
success: function(json) {
// Do stuff with data
},
error: function(e) {
console.log(e);
}
});
As an example check out this working fiddle.
Try this
$.ajax({
url:"https://api.qwant.com/api/search/images?count=10&offset=1&q=cars",
type:"GET",
crossDomain : true,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
jsonpCallback: "myJsonMethod",
success: function(json) {
$.parseJson(json)
},
error: function(e) {
console.log(e);
}
});
This is a CORS thing, so you can server all this up from a web server, like http-server, and I think certain browsers like Firefox allow this to occur locally.
There are some flags with Chrome that'd allow it to work locally like this too, I believe.
Cheers

Using AJAX call in MVC5

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>

Post data don't send using jQuery Ajax request

how to send large base64 data Array using jQuery Ajax. Here is my code :
$.ajax({
type: "POST",
url: "addPhoto.php",
data:{photosArray:photosArray},
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});
photosArray contains between 3 and 12 very long strings like :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0...
Is there any limit for POST data size in Ajax?
Open your php.ini file and find the line stating upload_max_filesize. The default it set to 2M, which is 2MB. Try increasing it to 3MB and see if you are still receiving the error.
And use
"cache": false
Is your data properly declared ? It can be either String, object or array. try following
$.ajax({
type: "POST",
url: "addPhoto.php",
data:"{photosArray:photosArray}",
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});

IE8: Access denied

I am trying to access and API using jquery/post but its not working in IE8. Its throwing Access denied error in IE8 only.
js code:
var url = 'http://somecomp.cartodb.com:80/api/v1/map?map_key=xxxxxxxxxxxxxxxxxxxx&stat_tag=API';
var data = //some long data of length greater than 3000
$.ajax({
crossOrigin: !0,
type: "POST",
method: "POST",
dataType: "json",
contentType: "application/json",
url: url,
data: JSON.stringify(data),
success: function(a) {
console.log('success');
},
error: function(a) {
console.log('error');
}
})
If I add ?callback=? at the end of url, it still fires the error callback but with statusText: 'success' and code: 200
here is full code: http://textuploader.com/ato0w
Change dataType to jsonp will allow you to make cross-domiain requests. This will work only with GET requests.
If you're using CORS for accessing cross-origin resource, try to add the following line:
$.ajax({
crossDomain: true, // replace "crossOrigin: !0;"
});
If this not working for you, try to add the following line above $.ajax() call.
jQuery.support.cors = true;

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Categories