I have a webpage that will submit a form and redirect to another page. Is there a way to do this through jQuery, and get the response page in a callback function? So that the page won't redirect and I can show a message from the server in the same page.
I have tried the following code but it doesn't work:
$('#reset-password-form').submit(function(data){
console.log(data);
return false;
});
Also I tried following code snippet, which also didn't work:
$('#reset-password-form').submit(function(data){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
return false;
});
Please advise.
Adding HTML Section:
<form id="reset-password-form">
<div data-message-bar="">
</div>
<input type="hidden" name="username" value="dummy">
<input type="hidden" name="validationToken" value="248gf293g2793g273f972">
<input required="" name="password" type="password">
<input required="" name="passwordconfirm" type="password">
<button data-action="reset-password">Reset Password</button>
</form>
you can use this
<button id="resetpass" data-action="reset-password">Reset Password</button>
$("#resetpass").on("click", function(event){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
})
Do not return anything, returning false ll quit form submission
<form onSubmit="formSubmit()" id="reset-password-form">
<div data-message-bar="">
</div>
<input type="hidden" name="username" value="dummy">
<input type="hidden" name="validationToken" value="248gf293g2793g273f972">
<input required="" name="password" type="password">
<input required="" name="passwordconfirm" type="password">
<button data-action="reset-password">Reset Password</button>
</form>
function formSubmit(){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
}
remove data from function and do not return false
$(document).on('submit', '#reset-password-form',function(e){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
})
.done(function(){
alert("Done");
$('#reset-password-form')[0].reset();
});
e.preventdefault(); // stop page refresh
});
Related
i have a ajax request to post data to api and get response. What i want to do is, how to pass a value from input field to the body data on ajax.
here my form
<input type="text" name="serial" />
<input type="submit" />
here my ajax request
$.ajax({ url: "http://www.example.com/api",
beforeSend: function(xhr)
{ xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); },
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: '{"serial":"252625"}',
success: function (data) { alert(JSON.stringify(data)); },
error: function(){
alert("Cannot get data"); }
});
I want to make the this part data: '{"serial":"252625"}' from a serial input filed programatically.
Thanks any suggestions,
Your form:
<input type="text" name="serial" id="serial" />
<input type="submit" id="submit" />
Javascript with Jquery:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
url: "http://www.example.com/api",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: {
serial: $('#serial').val()
},
success: function (data) {
alert(JSON.stringify(data));
},
error: function(error){
alert("Cannot get data");
console.log(error);
}
});
});
});
I use laravel and I want to upload gallery and I want to use ajax.
I created this code
$('#hello').on('submit', function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
method: "POST",
url: "{{ route('upload.store')}}",
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
success: function(done){
console.log(done)
},
error: function(error){
console.log(error);
}
});
});
This is ma the latest code. Could you help me?
$('#hello').on('submit', function(e){
e.preventDefault();
var formData = new FormData($("#hello")[0]);
$.ajax({
url: "{{ route('upload.store')}}",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function(done){
console.log(done)
},
error: function(error){
console.log(error);
}
});
});
How I to for send an image and form with a request ajax?
HTML
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
</form>
<button id="btnSave">Save</button>
JQuery - AJAX
$("#btnSave").click(function()
{
var Url = 'http://localhost/systemm/public/painel/client';
var Dados = $('#FormClient').serialize();
$.ajax({
type:Type,
url: Url,
dataType: 'JSON',
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
});
When I serialize the data and put in an alert to display I see that the image is not there, how do I send the image along with my form to my server/controller?
Use formData object:
HTML
<form enctype="multipart/form-data">
<input type="text" class="form-control" id="Name" name="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button id="btnSave">Save</button>
</form>
JS
$("#btnSave").click(function() {
var Url = 'http://localhost/systemm/public/painel/client';
var formData = new FormData(this.form);
$.ajax({
type:'post',
url: Url,
dataType: 'JSON',
data: formData,
...
});
});
Let's try following,
<form id="POST_FORM" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button type="submit" id="btnSave">Save</button>
</form>
$("#POST_FORM").submit(function(){
var data = new FormData(this);
addPOST(data);
return false;
});
function addPOST(formData){
$.ajax({
type:'POST',
url: Url,
data:formData,
dataType:"json",
cache:false,
contentType: false,
processData: false,
success:function(response){
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
Try to change content dataType. Set dataType='false'
$.ajax({
type:Type,
url: Url,
dataType: false,
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
Hope this helps
This is the way i have done it.
var obj = document.getElementById('my_form_id')
var data = new FormData(obj);
$.ajax({
type: 'post',
url: $(obj).parent().attr('action'),
processData: false,
contentType: false,
data: data,
success: function(result){
profile_app.user.foto_url = result.url
},
error: function(error){
console.log("error");
}
});
I have an object that contains parameters . I want to upload an image to a server but just using javascript.
how can I do that?
<input id="imgItem" type="file" class="form-control">
<input type="text" id="title">
<input type="text" id="description">
<button onclick="handle();">
<script>
function handle(){
var params={
title:document.getElementById('title').value,
desc: document.getElementById('description').value,
img://i don't know what I must do,
};
postItem(params, function(data){
alert(JSON.stringify(data));
});
}
function postItem(param, callbackFunction){
$.ajax({
url:myUrl,
data:param,
type:'POST',
contentType:'application/x-www-form-urlencoded',
xhrFields:{withCredentials: false},
success: function(response){
callbackFunction(response);
}
});
}
</script>
You can use FormData
var data = new FormData();
data.append('title', document.getElementById('title').value);
data.append('desc', document.getElementById('description').value);
$("input[type='file']").each(function (index) {
try {
data.append($(this).attr('name'), $(this)[0].files[0], $(this).attr('name'));
} catch (ignore) {}
});
$.ajax({
method: 'POST',
url: url,
data: data,
cache: false,
contentType: false,
processData: false
}).done(function () {
//your code here
}).fail(function (xhr, status, error) {
//your code here
}).always(function () {
//your code here
});
Or use it as regular form submission and fill in title and description values in submit event.
Currently using this:
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};
And it's sending my file perfectly, but I need to send 4 field values along with it. Could anyone let me know how I post:
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
Along with the file? Many thanks
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
data.append('x', $("#x").val());
data.append('y', $("#y").val());
data.append('w', $("#w").val());
data.append('h', $("#h").val());
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};