In Ajax Image Upload, ev.preventDefault(); not working - html

It uploads the image but it redirects to UploadImage.cshtml. So apparently ev.preventDefault isn't working. Is there a solution to this without having me to go through blueimp or xhtml stuffs coz I am not ready to touch those stuffs.
HTML
<form method="post" action="UploadImage.cshtml" id="imgUploadForm" class="imgUpload" enctype="multipart/form-data">
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag: false,
uploadText:"Upload")
<input type="submit" name="buttonUpload2" value="Upload" />
</form>
Jquery
$(function () {
$('.imgUpload').submit(function (ev) {
var frm = $(this);
Upload(frm);
ev.preventDefault();
});
});
function Upload(frm) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: new FormData(frm),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
}

Solved with following Jquery code. Thanks
$(document).ready(function (e) {
$('.imgUpload').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert('success');
},
error: function (data) {
alert('error');
}
});
}));
})

Related

AJAX success function not being called even though HTTP 200 is returned

When a user clicks 'buy now', I want the transaction to happen and the div to eventually be faded out and removed once being processed by the controller. Everything in the controller works as it should, but when I put the function in the success, it isn't called. However it works when the function is placed outside the success. Additionally, a window.alert() somehow works when there's a success.
Here is my script, everything works in regards to the controller etc
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
$(this).closest('.product').fadeOut("normal", function() {
$(this).closest('.product').remove();
});
}
});
}));
});
Everything above in the controller works fine as well, here is what it returns:
return response()->json(['ok' => 'ok']);
You cannot use this under success function because this is out scope . Just change your code like below :
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).attr("id");
var element=this;//getting current element click in variable
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'json',
success: function () {
window.alert("THIS ALERT COMMAND WORKS BUT THE FUNCTION DOESN'T!");
//passing variable
$(element).closest('.product').fadeOut("normal", function() {
$(element).closest('.product').remove();
});
}
});
}));

how to pass primary key value from JsonResponse to dynamic url in Django?

I face the problem to pass primary key value to the dynamic url using Ajax in Django. Thanks for any helps...
below is the JS code for click button's function:
$(function () {
$(".js-create-book").click(function () {
$.ajax({
url: '/supplier/**<int:pk>**/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
the views.py got the function new_stok() as follows:
def new_stok(request, pk):
supplier = get_object_or_404(Supplier, pk=pk)
form = NewStokForm()
context = {'pk': supplier.pk, 'form': form}
html_form = render_to_string('includes/partial_stok_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})
You can use HTML5 data attributes:
<button class="js-create-book" data-id="{{ supplier.pk }}">Add new</button>
Then in javascript retrieve the attribute:
$(function () {
$(".js-create-book").click(function () {
var data_id = $(this).attr("data-id");
$.ajax({
url: '/supplier/' + data_id + '/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});

How to add new browser tab

It won't go to a new browser tab, is my code wrong?
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
$(location).attr('href', a)
a.preventDefault();
},
error: function (err) {
}
});
}
What you're looking for might be:
window.open('http://stackoverflow.com/', '_blank');
And in your code:
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
var win = window.open('http://stackoverflow.com/', '_blank')
if(win) {
win.focus(); /if tab is open, change focus there.
}
},
error: function (err) {
// do stuff here
}
});
}

HTTP GET not getting

Trying this but getting nothig
function getWeather() {
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
On clicking button it should return the JSON
<body>
<button onclick="getWeather();">Get Weather</button>
</body>
Expected example JSON:
{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5168,"message":0.0287,"country":"GB","sunrise":1415603442,"sunset":1415636293},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":284.99,"pressure":1003,"humidity":76,"temp_min":283.75,"temp_max":286.15},"wind":{"speed":5.1,"deg":210},"clouds":{"all":75},"dt":1415624678,"id":2643743,"name":"London","cod":200}
I am not getting the mistake I have done.
EDIT
Tried with this from snippets given here:
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="javascript" type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
//alert(JSON.stringify(data));
data_Json = data;
//alert("Weather Report: "+data_Json);
},
error: function(e) {
alert(e.message);
}
});
return data_Json;
}
function temp() {
//getWeather();
var obj = JSON.stringify(getWeather());
//alert("Got"+JSON.stringify(obj));
//alert(JSON.stringify(getWeather()));
//document.getElementById("temp").innerHTML = obj.main.temp;
alert("Temp : "+obj);
}
</script>
</body>
<body>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
</html>
It returned {}
Not returned the JSON (the return defined in getWeather)
Not the temperature (in get element by id part)
Remove contentType from your request and it will work fine.
Since this is a cross origin request, you cannot set contentType.
Following is the error you will see in your console -
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/weather?q=London. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Also the statement return data; will fail as variable data is not available in that context.
You can use the below code for your purpose -
function getWeather() {
weatherJson = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
weatherJson = data;
},
error: function(e) {
alert(e.message);
}
});
return weatherJson;
}
You can try this solution
function getWeather() {
data_Json = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
dataType: 'JSONP',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
data_Json = data;
},
error: function(e) {
alert(e.message);
}
});
return data_Json; }
For Edit Part:-
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function (data) {
data_Json = JSON.stringify(data);
},
error: function (e) {
alert(e.message);
}
});
alert(data_Json);
return data_Json;
}
function temp() {
var obj = getWeather();
alert("Temp : " +obj);
}
</script>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
Hi See this,
function getWeather() {
var returnData="";
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
returnData=data;
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
Do you actually have an element with id="jsonp-results" in your html?
Some hints to simplify:
You don't need to specify a jsonp callback if you are not using jsonp
Synchronous calls are not nice because they block, you should avoid that and they aren't even supported for cross-domain calls (which your case is)
Simplified example:
function getWeather() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e) {
alert(e.message);
}
});
}
<body>
<button onclick="getWeather();">Get Weather</button>
<div id="jsonp-results"></div>
</body>
After your comment: It certainly works:
http://codepen.io/anon/pen/MYgXzd
You must have something wrong in your setup.

jquery.ajax is not calling the onsuccess method in CHROME. Same code works fine in IE

Code below works fine in IE, but onsuccess(...) method is not getting called in Chrome. Does any one know the solution?
$(document).ready(
function (e) {
$.support.cors = true;
$.ajax({
dataType: "JSON",
type: "GET",
crossDomain: true,
url: "http://localhost:36730/home/GETaaa",
success: function (data) {
//console.log(data);
alert(data);
},
Error: function (xhr, error, message) {
alert(xhr);
}
});
}
)