I have a problem posting file via ajax jQuery function. I have something like this:
$('#my_form').submit(function() {
var serialized = $(this).formSerialize();
var sUrl = "xxx";
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
success: function(data) {
$(".main_container").html(data);
}
})
return false; // THIS return statment blocks sending file content
});
When I remove return false statement everything is okey, server side gets the file content and etc, but when it's there (i monitor with firebug) that this posting sends only file name. What can be wrong?
P.S. - I need this return false statement, because I want to manipulate return data myself.
First stop — the manual.
Data from file select elements is not serialized.
From http://api.jquery.com/serialize/
You can't read local files with JS, so you can't submit them using XMLHttpRequest.
jQuery - receiving the $_FILES array using $.post lists a number of alternative approaches.
Related
Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async
Attaching .done .fail and .always to ajax calls is now doable for me - it is "easy" when the script is at the bottom of the html page.
Now I want to create generalized ajax functions that I can use just by including a js file in the header. I've been successful with ajax functions that read data from server (.done always works). I'm having problems when I just write or update data to the server (no return of data). Here are the specifics-
Standard ajax add/update call that always works - in script tags at bottom of page.
$.ajax({
type: 'POST',
url: 'supdateajaxfunctiontestbackend.php',
data: {localid: localid,
firstname: firstname,
lastname: lastname}
}).done(function(){ alert('Done with Add/Update!'); });
If I create a function at the bottom of the page, or add the function to a js file, this add/update always works.
function generalWriteAjax(filetocall, datatosend) {
$.ajax({
type: 'POST',
url: filetocall,
data: datatosend
}).done(function(){ alert('Done with Add/Update!'); });
}
I would like to detach the .done from the function, and call the .done when attached to a separate function/object. The following code works fine WHEN THERE IS DATA RETURNED FROM THE SERVER. (a separate generalReadAjax function that asks for server data). The done is attached to an object that is returned from the server (This concept I found here on Stackoverflow).
backenddata = generalReadAjax('readtesttablebackend.php');
displayData(backenddata);
backenddata.done(function(){ alert("Done with read!"); });
});
I have tried all of the following with the WRITE/UPDATE only function, and none of them work.
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).when(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).then(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update);
createdonealert = generalWriteAjax(filetocall4update, datatosend4update);
createdonealert.done(function(){ alert('Done function'); });
createdonealert.when(function(){ alert('Done function'); });
createdonealert.then(function(){ alert('Done function'); });
So obviously, there is a difference in the way the promise is handled between a "go get me data" and "here is data, please store it".
I even put an echo "Done"; at the bottom of the update php file just to return something, and still no luck.
I've searched this site and google with combinations of:
ajax .done attach add update not working promise
and have found nothing that deals with my specific example.
Can someone give me some guidance?
I thank you in advance.
Well, no one has responded, and I've learned a bit by hacking on this for the last day. Here are some things I THINK I've learned:
If you create a general callable function using ajax, it does not act the same as an "inline" ajax - you do not get the same callback actions as you do when the ajax code is at the bottom of an HTML page between script tags.
If you return something from the server, the ajax function acts similarly to when it is between script tags.
If you DO NOT return data from the server, the ajax function does NOT act the same as when it is inline.
So what I've done is on all php files that are "write/update" only (no data returned), I add a little code to the bottom of each php file that returns a small amount of json "junk". With this "junk" the ajax function acts like a regular ajax call between script tags at the bottom of the page.
It's a kludge, but it works. Here is the code at the bottom of a read/update php file that normally would NOT return anything. It now returns a json array regarding "John":
$json = array('firstname' => 'John');
echo json_encode($json);
Here is the function in the attached js file:
function generalWriteAjax( filetocall, datatosend ) {
return $.ajax({
type: 'POST',
url: filetocall,
data: datatosend,
dataType: 'json'
});
}
Here is the code on the page that calls the .js function:
$("#clicktoupdate").click(function(e) {
var localid = $('#idnumber').val();
var firstname = $('#updatefirstname').val();
var lastname = $('#updatelastname').val();
var filetocall4update = 'supdateajaxfunctiontestbackend.php';
var datatosend4update = {localid: localid, firstname: firstname, lastname: lastname};
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done inline'); });
});//end of update click
I wish I understood the details, but this is an empiric solution that works.
Comments from the experts would be nice.
Thanks for looking!
I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.
I am about to do my head in over this problem. I am using very simple jQuery ajax calls to get values from a database and populate a few select elements with the values, all returned as JSON. It works seamlessly for me on most browsers, however the client is reporting that neither them nor their clients are seeing the result.
I added some Console.log() commands along the way to make sure the code was executing, and it was. Sometimes the ajax GET to the URL in question works, other times is STILL returns 200 OK but the code simply does not execute further, and NO ajax error messages are shown in the error callback.
Here is the code I am using, can someone spot something obvious that may result in some browsers choking? If so, I'd be grateful if you could point it out:
var $j = jQuery.noConflict(true);
$j(document).ready(function(){
//console.log("jQuery has loaded");
//console.log("attempting to load country list via AJAX call now");
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=countries&rand='+Math.random(),
success: function(data){
//console.log("Successfully got country list, going to populate the dropdown now");
if(data.length){
$j("#country").children("option:not(:first)").remove();
$j("#country").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.country).val(result.country);
$j("#country").append(o);
})
//console.log("Country list should be populated now?");
}
},
error: function (xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText);
console.log(thrownError);
},
dataType: 'json',
cache: false
})
$j("#country").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#province").attr("disabled", "disabled");
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#province").children("option:not(:first)").remove();
$j("#province").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.province).val(result.province);
$j("#province").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
$j("#province").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=towns&p='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#town").children("option:not(:first)").remove();
$j("#town").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.town).val(result.town);
$j("#town").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
})
I have commented out the Consol.log commands for the pure fact that the client was receiving error messages on IE as there is no console.
EDIT: I failed to mention that this a same domain request and therefore obeys the Same Origin Policy
The full site is here: http://www.topplaces.co.za/
On the right is a dynamic select group that starts with country and initiates AJAX calls until a Province is selected. The issue, a lot of people say that Country is no loading for them...
Kind regards,
Simon
Check if your server application always returns valid JSON object, otherwise it will not be accepted because you set dataType: 'json'. In this case, error function will be executed instead of success.
Remove dataType parameter and see what happens, try to parse incoming data with $.parseJSON() - it will throw an exception if you JSON is invalid.
I tried your site but no province is loading. The Json is empty. I tried accesing the php directly and it returns empty as well. Did you check your script?
URL Called
http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c=Zambia&rand=0.12686952343210578&_=1335360594228
This are the params is see:
q:provinces
c:Zambia
rand:0.12686952343210578
_:1335360594228
Json Result:
[]
It's really random so I bet it's the php script not returning the json.
I also experienced this browser issue with json returned from an ajax call. The problem was that I had to look at different parts of the returned data in Firefox compared to IE. For Firefox, data.text was undefined so I had to use data.documentElement.firstChild to find the json:
var list = typeof data.text === 'undefined' ? jQuery.parseJSON(jQuery(data.documentElement.firstChild).text()) : jQuery.parseJSON(data.text);
I am trying to use jQuery ajax to get some values from the database and then return them in an array.
I have used the same code several times before but this time, no response is being returned. Although the post values are the correct values that I would expect. Here is the javascript code that I am using:
$.ajax({ url: '/BlogArchive.asmx/ChangePost'
, type: 'POST'
, contentType: 'application/json; charset=utf-8'
, data: '{FileName:"' + FileName + '"}'
, dataType: 'json'
, success: function (data)
{
var arrayList = data.d;
var BlogPostTitle = $(".BlogPostTitle")[0];
var BlogPostDate = $(".BlogPostDate")[0];
var BlogPostContent = $(".BlogPostContent")[0];
$(BlogPostTitle).html(arrayList[0]);
$(BlogPostDate).html(arrayList[1]);
$(BlogPostContent).html(arrayList[2]);
}
// , error: function (XMLHttpRequest, textStatus, errorThrown)
// {
// //There was an error
// alert('dfd');
// }
});
The only javascript error that I am receiving is that data is null, which I would expect as the response is blank.
It seems that the name of the web method that I am calling from my javascript is not even being read, because if I changed 'ChangePost' to 'ChangePost1' for example, it still returns a blank response, although I would expect an error message saying that the web method can't be found.
It seems that it does recognise that the BlogArchive.asmx web service exists because if I put something that would create an error in the VB code, the error appears as the response.
I am sure this must be something simple that I am doing wrong. Any help would be appreciated.
, data: '{FileName:"' + FileName + '"}'
Seems odd. You probably meant:
, data: {FileName: FileName}
(or 'FileName=' + FileName)
Furthermore, did you inspect the request (and response) via FireBug or similar?
You should try using jQuery getJSON with the minimal arguments.
Another thing, when you are using JSON with jQuery, if the answer data are not wellformed
(like a space before / after the starting JSON string) could lead to a blank answer from
jQuery.
Be sure using traditionnal AJAX with jQuery that your answered data are correct.