Avoid React Ajax + FileUpload + FormData to refresh page after success - ajax

I don't know why but after an AjaxCall with formData+files_upload, the entire page is reloaded.
This doesn't happen with normal Ajax Call.
I have no FORM tag or something as you know if you use REACT.
I have an inline file-upload component to load async file.
<FlatButton label="Upload File" onClick = { (e) => this.commonUploadFile(e) } />
The trigger is simple.
The method:
e.preventDefault(); // Let's stop this event.
e.stopPropagation(); // Really this time.
let formData = new FormData();
const file = files[0]; //passed by wrapping method
formData.append('uploading_file', file);
formData.append('file_name',this.state.file_name);
formData.append('original_filename',this.state.original_filename);
formData.append('userToken',window.userToken);
formData.append('file_path',this.props.attributes.dirname);
$.ajax({
method: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
async : true,
url: process.env.REACT_APP_FILE_UPLOAD,
complete: function(result){
result = JSON.parse(result.responseText);
this.setState({upload_result : result.success});
}.bind(this),
});
return false;
The call end successfully and the state of component are changed properly but after that, the entire site refresh and I don't know why.

I've finally find out the problem.
When using a developing server (npm start) any filesystem change will launch a page refresh and a file upload change the file system.
So pay attention.

Related

Uploading image file with ajax and receiving it with in the asp.net core mvc controller

I have tried all possible ways mentioned in this Solution, however didn't have any progress. Please help.
So my ajax request is as below:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("file", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: { image: formData }, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
The ajax post request gets received by the controller's action, however the IFormFile image is always null.
[HttpPost]
public async Task<IActionResult> ChangeProfilePicture(IFormFile image)
{
// I do save here the image in the folder, but problem is that image==null
}
The ajax post request gets received by the controller's action,
however the IFormFile image is always null.
When the file is uploaded by formData append, the name at this time should be the same as "image" of the receiving parameter in action:
formData.append("image", files[0]);
And because you only need to pass the IFormFile to the action, in the data parameter of ajax, you only need to put the formData which appends the file named Image to it:
data: formData,
Change your js as follow:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("image", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: formData, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
Here is the test result:
I had this same issue and even after updating the changes as suggested in previous answer, it didn't work for me.
Finally found the solution :
formData.append("fileInfo", fileInfo, "uploadedfile"); // uploadedfile is file name which at compile time converts to FormFile in Action method

ajax pager on views page load by ajax

I load a vieschs views_embed_vesch using Ajax.
This views included Ajax PAGER. It does not work.
Drupal.attachBehaviors does not work too.
I think in Drupal.settings need added data from views.
(function($){
Drupal.behaviors.ajax_views = {
attach: function (context, settings) {
//alert('dddd');
$('a.views-link').click(function(){
// alert('sfsdfsd')
var relArr = $(this).attr('rel').split(' ');
$.ajax({
type: "POST",
url: Drupal.settings.basePath + 'ajax-views/'+relArr[0]+'/'+relArr[1],
dataType: 'json',
success: function (datad){
alert(datad.seet.views);
// Drupal.settings.views = datad.seet.views ;
$('div#block-system-main > div.content').append(datad.view);
},
});
return false;
});
}
};
})(jQuery);
Try this module to load content via ajax. It will automatically attach behaviour with the ajax loaded content.
https://drupal.org/project/ajax_links_api

jquery live() appending click events causing multiple clicks

I have some strange behaviour going on with the jQuery ajax functionality in my asp.net MVC3 application.
I have several boxes of data each containing a link to open a popup and change the data in each box. To do this I've added a jquery live() click event to process the data via a jQuery ajax call. In the "success" method of the ajax call, i take the return data and open a UI Dialog popup (a partial view) which contains a list of radio buttons. I select a different radio button and press 'close' - the close button fires another live() click event, processes that new data via an ajax call which refreshes the data in the box on the main page.
This works perfectly first time. If you then click to change it again, the popup opens, allows you to select a new value, but this time pressing close on the popup triggers two click events which throws an null error in my MVC controller.
If you repeat this process it triggers 3 click events, so it's clear that live() is appending these events somewhere.
I've tried using on() and click(), but the page itself is made up of panels loaded in via ajax so I used live() to automatically bind the events.
Here is the code I'm using:
HTML
<p><!--Data to update goes here--></p>
Update Data
First Click event calling popup with Partial View
$('a.adjust').live('click', function (e) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true
}
});
}
});
e.preventDefault();
});
Second click event the takes the new info to return updated partial view
$('a#close').live('click', function (event) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
$('#box-' + #column).html(response); //this refreshes the box on the main page
},
error: function () {
}
});
$('#ModalDialog').dialog('close');
event.preventDefault();
});
Anybody know what might be happening here, and how I could resolve it?
Use namespaces to unbind previous click binds like this:
$('a.adjust').unbind('click.adjustclick');
Then bind the click action to a.adjust:
$('a.adjust').bind('click.adjustclick', function(){
//your code here
//note the return false, this prevents the browser from visiting the URL in the href attribute
return false;
});
If i understand you correctly, you try to run the second click action when the dialog is closed. Therefor I would use the build in close function for the dialog like this:
$('a.adjust').bind('click.adjustclick', function(){
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true,
close: function(){
var jsonData2 = getJsonString(n[1]);
var url2 = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url2,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData2,
success: function (response2) {
$('#box-' + #column).html(response2); //this refreshes the box on the main page
},
error: function () {
}
});
}
}
});
}
});
});
If you are using your own button a#close, bind a click event to it to close the dialog, it will automatically fire the close function for the dialog.
$('a#close').unbind('click.closedialog');
$('a#close').bind('click.closedialog', function () {
$('#ModalDialog').dialog('close');
return false;
}
Try this:
$('a#close').unbind('click').bind('click', function (event) {
//Your Code
});

can you do a jquery mobile popup on ajax response event?

Was hoping to use the popup and I am pretty sure I am trying to use it incorrectly. Any ideas on how this should work? Can you use the popup in this manner?
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
data = $.trim(data);
//$("#notification").text(data);
$("#notification").popup(data); }
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "sendmsg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
I'm assuming you are trying to use the JQM popup widget, first your missing the closing } from your onError function. Second to use the popup widget you can first set the data
$("#myPopupContent").text(data)
Then to display you use the open method
$("#myPopup").popup("open")

How do I use data passed back in the response from ajax jQuery?

I am trying to use the response from a jQuery ajax request to set the innerHTML of a div with a certain id. This is the code I am using:
$(".show_comments").click(function(){
var articleName = $(this).closest("article").find(".articlename").attr('id')
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(this).closest("article").find(".comments").html(response);
}
});
however it doesn't seem to be doing anything at all, I've tried googling around, but everything I can find says to do it the way I am doing it... I have tested in Firebug and the ajax request is giving me the exact response I want it too... But I just cant access this to set the innerHTML of the div to the response!
In your ajax success handler there is another scope and this points to not what you think. So change your code to:
var articleName = $(this).closest("article").find(".articlename").attr('id'),
that = this;
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(that).closest("article").find(".comments").html(response);
}
});
What I've changed: I added that variable that points to this instance and use it in the success handler instead.
How would you debug it yourself: if you tried to output console.log(this) and console.log($(this).closest("article").find(".comments")); you would see that it returns a wrong object (in first case) and nothing in second.

Resources