AJAX not Working in FF, works well in Chrome - javascript

I am uploading a document to the server, using PHP and AJAX with JS on button click. I collect the form data make its object append the file data and pass it via AJAX to the function upload.php. The code works completely well in Chrome but fails to give the same effect in FF. Code is attached Further. What is the possible solution to the problem ?
$(document).on('click', '#uploadDocument', function()
{
var formData = new FormData();
formData.append('fileToUpload', $("#fileToUpload").prop("files")[0]);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (status){
if(status == 'File Uploaded')
{
$('#listTable').load('showList.php');
}
else
{}
}
});
});

this is likely because of the default action of the form, you need to prevent that. pass in event to your onclick function and then use event.preventDefault(); on the first line in the function

Related

AJAX jQuery new version about "Insert into database without page load"

I'm new to AJAX, I'm using old code:
$.ajax({
type: 'POST',
url: 'phppath/sucms.php',
data: $('#formid').serialize(),
success: function(response){
$('#success').html(response);
}
});
It works, but not perfectly, everything is good but when I try to upload an image it has "CLEAR VALUE".
I'm trying make new code like this:
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'phppath/sucms.php',
data: formData ,
success: function(response){
$('#success').html(response);
}
});
but it reloads the page and opens sucms.php clear window.
If you want to upload files using ajax, you need to set contentType and processData as false in your ajax config.
var formData = new FormData();
formData.append(<KEY>, <FILE>);
$.ajax({
type: 'POST',
contentType: false,
processData: false,
url: 'phppath/sucms.php',
data: formData ,
success: function(response){
$('#success').html(response);
}
});
On the other hand, if the page is being reload or opened in a new window. It is probably because the type of your button is submit. You should change the button type to button or use event.preventDefault() to prevent the action being execute in the traditional form submit approach.

Loading HTML in the Ajax Response

So I am dealing with this weird service when returns a html page as the ajax response which has a form and the form is triggered automatically by some scripts in the page (so when you render the page a post request will be sent to you). What I am trying to do is to load this page I am getting from the response.
Say this is my Ajax call:
var ajax_call_test = function() {
var formData = new FormData($('#documentForm')[0]);
console.log("doc form: " + formData);
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
$.ajax("/documents/upload/", {
type: 'POST',
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
dataType: 'html',
success: function(html){
// ?
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("failed: " + errorThrown);
}
});
}
So I tried to use .html to set the response to a hidden <div>. It sets the html but never triggers the form. I am guessing the javascript in that page is not loaded when I use .html.
I also cannot use jQuery.parseHTML() since the version of library I am using does not support that functionality. Any idea what should I do with response?
When ever you load new html into the DOM. The javascript does not know about it.
I have to re invoke my javascript to work with the new DOM.
Lets say I have some click events
$(function(){invokeClicks()}) // onload call
function invokeSomeAction(){
$("selector").off(); // disable previous events from old html
$("selector").on("event", function(){
// handle event
})
}
function invokeClicks(){
invokeSomeAction();
// ... etc
}
So when this JS loads, the invokeClicks() method gets called.
Now, if I replace the HTML through a $.ajax() call, all I have to do is call invokeClicks() again to clear the old events and now the new HTML will work with the javascript
$.ajax({
url: "somepath",
data: {id: 1},
method: "GET",
success: function(html){
$("container_selector").html(html);
invokeClicks(); // reinit
},
})

How to pass data in a jsp file to multiple servlet using javascript?

I have a jsp file which has a form. And the form has some text fields and image upload field.I need to send text data to one servlet and image to another servlet when I click the submit button. is this possible ?
Yes.. I think it is possible .. the way I know you have to use a javascript library like jquery. Below is how it happens
On form submit you prevent the post to servlet. Then you can use ajax like shown below to send 2 requests to 2 different servlets. Below shows one ajax call.. you can do another after that call. I trying to show you below
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var author = $("#author").val();
$.ajax({
url: 'fileUploadServletUrl',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
$.ajax({
url: 'textDataServletUrl',
type: 'POST',
data: {'author':author },
async: false,
cache: false,
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});

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>

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

Categories