Unable to submit form data using ajax() post - javascript

I submit a form data using $.ajax() method, data contains image files.
while submitting I encountered with below issues:
form is not getting submitted in IE10,11
though it is submitting in chrome and FF, ajax() executing both success and error methods
I am able to submit the data in chrome and FF but it is displaying only error message
data is submitted to DB from Chrome and FF
Below is the code I am using to submit the data
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var senddata = JSON.stringify($('form').serializeObject());
$('#result').text(senddata);
var form_data = new FormData($(this)[0]);
form_data.append('jsonString', senddata);
var settings = {
"async": true,
"crossDomain": true,
"url": "google.com",//sample url
"method": "POST",
"processData": false,
"contentType": false,
"headers": {
"Access-Control-Allow-Origin": "*",
"cache-control": "no-cache"
},
"mimeType": "multipart/form-data",
"cache": false,
"data": form_data//,
//"dataType": "jsonp"
};
$.ajax(settings).done(function (data) {
console.log(data);
})
.success(function (data) {
alert("submitted");
})
.error(function (data){
alert("failed");
console.log(data);
});
return false;
});
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
<input type="hidden" name="profileTypeId" value="112" maxlength="36" size="12"/>
First Name:<input type="text" name="firstName" value="Hydtest" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="lastName" value="3SparrowTest" maxlength="36" size="12"/> <br/>
email:<input type="text" name="emailId" value="jackSparrow#testmail.com" maxlength="36" size="12"/> <br/>
Address1:<input type="text" name="address1" value="PiratesTest" maxlength="36" size="12"/> <br/>
<input type="hidden" name="address2" value="PiratesTest" maxlength="36" size="12"/>
<input type="hidden" name="city" value="caribbean" maxlength="36" size="12"/>
Profile Image: <input name="file" type="file" /><br />
<p><input type="submit" /></p>
</form>
<!-- end snippet -->

I think the form is not submitting because of images. Could you try base64 encoding the images before submitting them to the server.
Here is a reference to base64 encode images using javascript:
https://davidwalsh.name/convert-image-data-uri-javascript

Related

How to submit two forms with their Ajax with one button

I have two forms one with product details like price, description and name. And the other with images, they both have different Ajax but they send data to the same route. I want to submit them with one button. So if I click a submit button it should submit all data at once which are price, name, image etc. How can I do this if possible?
Blade file
//Form1
<form id="form1">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name"
placeholder="Enter product name">
<label for="price">Price</label>
<input type="text" class="form-control" name="price" id="price"
placeholder="Enter product price">
</form>
//Form2
<form id="file_form" method="post" enctype="multipart/form-data">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="images">Choose Images</label>
<input id="files" type="file" class="" name="files[]" multiple />
</form>
//Submit Button
<input type='button' class="btn btn-primary" value="Submit" id="btn"/>
Javascript
//Form1 javascript
var token = $("#token").val();
$(document).ready(function(){
$("#btn").click(function(){
var url = '{{ route('product.store') }}';
var form = $('form')[0];
var formData = new FormData(form);
formData.append('_token', token);
$.ajax({
url: url,
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("Product has been added successfull");
$("#msg").fadeOut(3000);
}
}
});
});
//Form 2 Javascript
$("#btn").click(function (e) {
e.preventDefault();
file_area = $('.file-area');
progressbar = $('.progress-bar');
status_bar = $('#status');
image_list = $(".image-list");
status_bar.css('display', 'block');
status_bar.html('<div class="fa-3x">' +
'<i class="fas fa-spinner fa-pulse"></i>' +
'</div>');
if (selected_files.length < 1) {
status_bar.html('<li class="error">Please select file</li>')
} else {
var data = new FormData();
data.append('_token', token);
for (var i = 0, len = selected_files.length; i < len; i++) {
data.append('files[]', selected_files[i]);
}
fiel_feild = $('#files');
$.ajax({
url: '{{ route('product.store') }}',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
success: function (response) {
result = JSON.parse(response);
if (result['status'] == 'error') {
status_bar.html(result['error']);
} else if (result['status'] == 'success') {
selected_files = [];
image_list.html('');
file_area.css('display', 'none');
status_bar.html('<li class="success">File uploaded successfully.</li>');
}
}
});
return false;
}
});

I use java Servlets and cannot redirect to another page after submitting form and sending data in JSON format

I don't have a lot experience in web developing.
I want to sent form data in request body in JSON format. When server reсieve data it should register new user and redirect user to another page with user's data.
Deserializing and ragistration into database works good.
The main problem is that after sending form data to the server the page recieve response with new page(url and content), but just in headers and doesn't change.
How can I change the page after sending form data??
Here is Javascript handling and HTML code of form:
<script>
function makeJSON(form) {
var userData = {
"phone_number" : form.phone_number.value,
"country" : form.country.value,
"city" : form.city.value,
"date_of_birth" : form.date_of_birth.value,
"email" : form.email.value,
"sex" : form.sex.value,
"login" : form.login.value,
"password" : form.password.value
};
var requestString = JSON.stringify(userData);
var request = new XMLHttpRequest();
request.open("POST", "/registration");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(requestString);
}
<div id="topNavLine"></div>
<div class="regBody">
<div class="regFormTop"><h1>Registration form</h1></div>
<form id="registration" method="post" onsubmit="makeJSON(this);" enctype="application/x-www-form-urlencoded">
<fieldset>
<legend>Personal data</legend>
<p><label>Phone:</label><input name="phone_number" type="text" form="registration"></p>
<p><label>Country:</label><input name="country" type="text" form="registration"></p>
<p><label>City:</label><input name="city" type="text" form="registration"></p>
<p><label>Date:</label><input name="date_of_birth" type="date" form="registration"></p>
<p>
<Label>Email:</Label><input name="email" type="text" form="registration"></p>
<p><label>Sex:</label>
M<input type="radio" name="sex" value="male">
F<input type="radio" name="sex" value="female">
</p>
</fieldset>
<fieldset>
<legend>Login data</legend>
<p><label>Login:</label><input name="login" type="text" form="registration"></p>
<p><label>Password:</label><input name="password" type="password" form="registration"></p>
<p><label>Confirm password:</label><input name="passwordValidation" type="password" form="registration"></p>
</fieldset>
<div class="regButton">
<button class="regButton" type="submit" form="registration">Register</button>
</div>
</form>
</div>
Here is doPost servlet method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String str = request.getReader().lines().collect(Collectors.joining());
System.out.println(str);
UserRegData userRegData = new ObjectMapper().readValue(str,UserRegData.class);
long tmpId = new Random().nextLong();
if (tmpId < 0) {
tmpId *= -1;
}
userRegData.setId(tmpId);
userRegData.printUser();
try (Connection connection = ConnectionWithDB.connectToDB()) {
ManagingData.setRegistrationData(userRegData, connection);
} catch (SQLException e) {
e.printStackTrace();
}
response.setStatus(201);
response.sendRedirect("/page_of_user");
}
The whole approach is a bit wrong IMHO. The response should be handle by a callback function in javascript. If there are validation errors for example you can show them in the same form.
If all is succesful then in javascript you call 'page_of_user'.
Here is JQuery in action:
$.ajax({
type: "POST",
url: "/registration",
data: userData ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ document.location.href='/page_of_user'; },
failure: function(errMsg) {
alert(errMsg);
}
});

JSON form data as dynamic submit

The AJAX post works when passing the predefined data as follow:
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
But I am unable to pass the data dynamically from the form.
Please help me figure this out.
POST function
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#post").click(function() {
$("#dataIn").text(JSON.stringify($("form").serializeObject()));
$(function() {
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
var data = ("#dataIn");
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
//data: JSON.stringify(data),
contentType: "application/json",
});
});
});
});
The Form
<form action="" method="post" class="form-inline">
<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">
<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">
<button id="post" type="submit" type="button">Add </button>
</form>
<p >Json Result</p>
<pre id="dataIn" ></pre>
I am not sure if I have to serialize the form or if the JSON.stringify(data) can already do this.
Below code works perfectly:
Non dynamically, But working
$("#post1").click(function(){
var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: JSON.stringify(data),
contentType: "application/json",
});
console.log("Loaded");
});
Thank you.
The best solution I could think of at the moment:
$(function() {
$("#post").click(function() {
var data = JSON.stringify($("form").serializeObject());
$("#dataIn").text(data);
$(function() {
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: data,
contentType: "application/json",
});
});
});
});
You don't need to use JSON.stringify() twice, because you already did it on .serializeObject() returned value. Next you print it to your #dataIn container and send it via ajax request.
You can try this https://jsfiddle.net/sjc79b55/2/
Please update <button id="post" type="button">Add </button> line also
<form action="" method="post" class="form-inline">
<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">
<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">
<button id="post" type="button">Add </button>
</form>
<p >Json Result</p>
<pre id="dataIn" ></pre>
JS.......
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#post").click(function() {
var jsonData = JSON.stringify($(".form-inline").serializeObject());
$("#dataIn").text(jsonData);
$(function() {
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
// var data = $("#dataIn").text();
//alert(jsonData);
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: jsonData,
contentType: "application/json",
});
});
});
});

authentification using ajax/jsp in phonegap

<form method="POST" class="userform" id="loginForm">
<div data-role="content">
<h2> Login:</h2>
<div data-role="fieldcontain">
<input name="email" placeholder="put your name" type="email" data-mini="true">
</div>
<div data-role="fieldcontain">
<input name="password" placeholder="enter your password" type="password" data-mini="true">
</div>
<input type="submit" data-theme="a" value="submit" id="submitButton">
<h5 align="center">
Forget password?
</h5>
</div>
</form>
this is my login.js
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var $bro = $('#loginForm');
$('#submitButton').click(function(e) {
//console.log("submit button has been clicked");
e.preventDefault(); //cancel form submit
var jsObj = $bro.serializeObject()
, ajaxObj = {};
//console.log(jsObj);
ajaxObj = {
type: "POST",
url: "http://192.168.0.100:8080/AdvancedLibrarySystem/api/v1/login",
data: JSON.stringify(jsObj),
contentType:"application/json",
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error " + jqXHR.getAllResponseHeaders() + " " + errorThrown);
},
success: function(data) {
console.log(data);
if(data[0].status == '200') {
alert("Welcome!!!")
$('#div_ajaxResponse').text( data[0] );
$.mobile.changePage('home.html');
}
else{
alert("Incorret Username or Password!!!")
}
},
complete: function(XMLHttpRequest) {
//console.log( XMLHttpRequest.getAllResponseHeaders() );
},
dataType: "json" //request JSON
};
$.ajax(ajaxObj);
});
I'm trying to use an authentification in phonegap via ajax but if i'm trying to run that code in chrome console it works fine but when i'm using it in my phonegap application it's not giving response in the server... Anyone can help me out please...
I am not sure what you mean by 'not giving response in the server', but one thing worth checking out is the cross-domain options in the config.xml of your phonegap project. There should be an "access" tag in there that specifies what domains can be accessed. Try setting it to "*" and try again.

Send Ajax Variables with POST to PHP

I am trying to find the best way to send variables from Javascript to PHP without GET method. I found a way to send through POST method with AJAX:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
And I am trying to submit the form with jQuery:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
NOTE: the variable "position" has been declared before and works fine.
Result: I get "Internal Server Error" in the alert. Any ideas?
First of All - show us what is going on the server side.
And now about the files being sent:
You should use FormData element for file submit threw Ajax, its not supported by old browser, the browsers that would support this are : ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12.
Use something like this:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
As you can see I added console.log(data), try looking at the returned data to identify any other problems.

Categories