Selectively send files through pseudo-Ajax calls - ajax

I already have the HTML and CSS set up for my form, and I have my Ajax call in place to submit it but I can't figure out how to send the images along. Here's my Ajax call:
$.ajax
({
type: "POST",
url: "/manage/processadditem",
data: $("#add_form").serialize(),
dataType: "html",
success: function( response, textStatus, XHR )
{
//Process return data
},
error: function(jqXHR, textStatus, errorThrown){
alert('An error occurred, please try again later.');
}
});
My problem is that there are 3 image inputs on the form, but I'll only use up to two of them at any given time, and one of the variables in the form tells me which ones I'm working with (gender=male/female/neutral).
In the success callback I would like to either examine that variable and decide which pictures to send along based on it, or send the variable along with the images to process in the back end, but looking through links on similar questions I haven't been able to find any examples of selectively sending files or sending additional information with them.

As far as i know you can not send files with a AJAX Post request.
i have tried myself.
It´s because the file data is not in the POST headers that is sent to the URL target.

Related

Not able to post JSON Data to MVC Action Method using $.AJAX but I get a Post 200 OK Response

I am trying to post some stringified data to an action method in my MVC controller. Below is the piece of JS Code
function SaveStateForGrid(pGridId, pIsAysnc) {
var grid = $('#' + pGridId).data("kendoGrid");
var tGridState = kendo.stringify(grid.getOptions());
$.ajax({
url: '/Home/SaveGridState',
type: 'POST',
dataType: 'json',
async: pIsAysnc,
data: { pGridState: tGridState, pGridName: pGridId },
success: function (data) {
console.log("Data Saved Successfully");
},
error: function (jqXHR, textStatus) {
console.log("Error while saving grid data " + pGridId);
}
});
}
I am trying to save gridstate info into the db and each grid in my app has different grid state info.
This works sometimes - as in, the post hits the controller method "SaveGridState" if I keep a breakpoint there and so on. On other occasions the breakpoint is not hit and the data is not saved in DB but the code does flow to "success" AJAX callback - no errors and I get a 200POST OK response in the network tab of chrome debugger.
I looked up the data being sent and figured out that on the occasions it fails, there is something about the data being posted which is causing it. Specifically the first param - "tGridState" - a stringified KendoGrid config data. If I replace this data from other successful calls, there is no issue. I have compared the data on different viewing tools and am not able to understand what in the data is breaking this.
Attaching a link to the zip file which contains both "Valid" and "Invalid" data. Any help pls ?
https://www.dropbox.com/s/whfglyk607bnd04/Downloads.zip?dl=0
Few months on from posting this - the module in question was on freeze.
I discovered that the stringified gridstate information (grid config data) included JS functions for grid related events which was causing issues in the stringified data. In fact stringification strips such functions from an object.
Somehow this was preventing me from hitting the breakpoint on the server side even if the data was posted "apparently".
So I wrote a JS function to strip all unnecessary data from my gridstate config data before stringification - and then the post works perfectly.
Voila !

Cross-domain AJAX - not getting the desired result

I am trying to ajax a form to a different domain using the jquery.xdomainajax.js plugin and having issue getting the desired HTML back (follow up to this question: Display form result in same page with only client-side script possible?)
The destination script checks the user id against the membership database, and redirects to an error page if the user has already submitted the form, or redirect to a thank you page if the entry is valid.
Using the script below, I get back the HTML of the ORIGINAL page on which the form is displayed, not the error page or the thank you page. If I change the dataType from "text" or "html" to "jsonp", I get a parse error as expected, but the associated HTML is actually desired HTML. I am not quite sure why.
Any help would be much appreciated!
PS: I do not have control over anything in the remote server.
$.ajax({
type: settings.postType, //GET
url: settings.tourl,
data: aForm.serialize(),
dataType: settings.type, //text or HTML
crossDomain: true,
success: function(data, textStatus, jqXHR){
alert(data.responseText);
settings.success(data);
},
error: function (jqXHR, textStatus, errorThrown){
//alert(errorThrown);
console.log(textStatus);
settings.error();
}
});
Should your request type be a POST instead of a GET? Generally form info will be sent with a POST.

jQuery Cross Domain Request to get JSON Response without Callback

I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.

why Ajax get Request failed

The response of my request is a java script code. When I put the url in browser, I can see the whole generated java script code on the page. Format of url passed to $.ajax is as below:
http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345
When I put the above URL I can see the request is successful. Now, I am using below Ajax request for this url using jQuery.
var finalUrl = "http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345";
var req = $.ajax({
type:"GET",
url:finalUrl,
type:"script",
data:"",
success: function(html){
alert('Requese sucessful.');
},
complete:function(jqXHR, textStatus) {
alert("request complete "+textStatus);
},
error: function(xhr, textStatus, errorThrown){
alert('request failed->'+textStatus);
}
});
Question 1:This gives the alert "request failed error'. Why this is so ?
Question 2:Is there any way to return success/failure code in above process?
In:
$.ajax({
type:"GET",
url:finalUrl,
type:"script",
(...)
You have two times the 'type' key in your object. So I think only the second one is taken ('script'). Obviously 'script' is not a valid HTTP method (as HEAD,GET,PUT,POST, etc). The keyword your were looking at for 'script' is maybe dataType which may be one of xml, json, jsonp, text, script, or html.
Do not forget to look at jsonp, it's usually a nice way to return a script content and to call it.
I am not sure why, but I can give your some tips how to debug or find out issues:
1) install fiddler to look at HTTP request.
2) type:"script", why the type is script? try to use "text/html".
3) use complete(jqXHR, textStatus) you can look at HTTP status. more info about $.ajax
var finalUrl=http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345;
is pretty invalid javascript. You probably meant passing the url as a string:
var finalUrl = 'http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345';

Ajax with JQuery: 200 ok, but not "success"

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!

Resources