I have this form
<form action="" method="post" enctype="multipart/form-data" onsubmit="submit()">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>
Uploaded file: <a target="blank" href="<?php echo $fileurl;?>"><?php echo $fileurl;?></a>
and I have this script
<script>
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
</script>
I want to submit the form without the page reloading but isn't working for me.
Your function takes event property, on which you can invoke preventDefault()
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
<script>
$('#yourFormData').submit(function(e){
e.preventDefault();
var formData = new FormData($('#yourFormData')[0]);
url ="your route" ;
$.ajax({
url : url,
type : "post",
data : formData,
contentType:false,
processData:false,
success : function(data)
{
// success
},
error : function(y)
{
console.log(error );
}
});
})
See this check function to stop page reloding
As you have requested I have given the full code
function check(event) {
event.preventDefault();
console.log("stopped form submit");
}
<form onSubmit="check(event)">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>
</form>
Related
Here is a simple PHP form with a button..
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){
$("#btnnew1").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
$.ajax({
url: 'test.php',
success: function(data) {
$("p").text(data);
}
});
}
});
});
And the test.php is as follows,
<?php
echo 'Button1 clicked'
?>
My question is how to modify my test.php if I have multiple buttons.
As an example,
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked);
If btnnew2 clicks--->echo("Button2 clicked);
If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex:
If btnnew1 clicks--->
sleep(5)
echo("Button1 clicked);
If btnnew2 clicks--->
sleep(15)
echo("Button2 clicked by user);
If btnnew3 clicks--->
sleep(35)
echo("Button3 clicked by user);
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don't like you may neglect it...
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box...
$(document).ready(function(){
$('.button').click(function(){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
var clickBtnValue = $(this).attr('name');
var fetchdata= 'testme.php',
data = {'action': clickBtnValue};
$.post(fetchdata, data, function (response) {
// Response div goes here.
alert("Updated successfully -"+response);
});
}
});
});
Finally change your testme.php as follows,
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'fcn1':
fcn1();
break;
case 'fcn2':
fcn2();
break;
}
}
function fcn1() {
echo 'Button1 clicked';
exit;
}
function fcn2() {
sleep(5);
echo 'Button2 clicked';
exit;
}
Set the name to each button:
Button 1
Send data using ajax:
Get button text using e.target.text and send using POST method.
$.ajax({
type: 'POST',
url: 'test.php',
data: { buttonTitle: e.target.name},
success: function(data) {
$("p").text(data);
}
});
php:
Inside php use $_GET to get the data which we send from the frontend.
if(isset($_POST['buttonTitle'])) {
$buttonTitle = $_POST['buttonTitle'];
echo $buttonTitle . " clicked";
}
I need to submit form using through Ajax call but I'm having trouble selecting the form. I don't want to use form ID because I'm having multiple forms and I need to setup one code for all
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
//$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card" >
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
No need to add form submit code because you are preventing submit, so when will you click just fetch data from the form and call your AJAX service.
I added one console log where you can see your form data.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
var formData = $(form).serialize();
console.log(formData);
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
This will help you to reduce duplicating the code..
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
Var action = $(this).action;
Var method = $(this).method;
Var data = $(this).serialize();
// perform ajax operation here with data, action and method
});
});
Happy coding :)
Your code is creating submit handler everytime the button is clicked, all you want is to send ajax call onclick, so just do that part.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
// below code is creating submit handler everytime the button is clicked
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
});
});
Also .find returns jQuery object, no need to make it Jquery object again, simple form will do instead of $(form).. rather declare like var $form = $(this).closest(".card-body").find("form")
Something like below, try
$(".pay").on("click",function(){
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
function submitForm(formData){
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
}
I've created below sample to refer
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
console.log(formData)
submitForm(formData);
});
function submitForm(formData) {
alert("submitting form with " + formData)
$.ajax({
type: 'POST',
url: "php/pay.php",
data: formData
})
.done(function(response) {})
}
});
.card {
width: 50%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h1>YYY</h1>
</div>
<div class="card-body">
<form>
<input name="user2" value="mat2" type="hidden">
<input name="id2" value="122" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay2</button>
<button class="btn btn-danger decline" value="decline">decline2</button>
</div>
</div>
Erm.. Why not just put the two buttons inside the form, to avoid any confusion or off-chance that the script might trigger another one of the "multiple forms" and refer to the nameless form through the parent element instead, like?
html:
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</form>
script:
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).parent();
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
Apparently in the DOM have changed the values, even changed the ID of the form with the idea that the script no longer has effect but when you click Publish, nothing happens. Searching I tried to use "prop" instead of "attr" but it still does not work. I think it's because of the "e.preventDefault ()". But I do not know how to disable it. This is my code.
As you can see once the request is sent, the input and the "send" button are deactivated and when the values are received, they change the id of the form, the id and name of the button and it is renamed "Publish".
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-search"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
});
</script>
Here my html
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<button id="search" name="search" class="btn btn-success boton">Search</button>
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
Here a fiddle showing that happened (check DOM).
JSFiddle.net
//var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
// when the action is plugin url.
$(document).on('submit','[id^="form-search"]', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
// when the action point to publish.php === This is what you need
$(document).on('submit','[id^="form-publish"]', function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type : 'POST',
url : url,
data : $(this).serialize(),
cache: false,
beforeSend: function(){
// do your pre-processing
}
}).done(function(data) {
// do your post processing.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<input type ="submit" id="search" name="search" class="btn btn-success boton">Search</button>
<!-- change the button type to submit type -->
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>
I want to submit a form using ajax in the background. I tried:
<div class="form-horizontal" id="form">
<label for="name" class="control-label">Username</label>
<div class="controls">
<span id="name_input"><input type="text" name="name" id="medium" class='input-medium input-square'></span>
<span class="help-inline" id = "ajax_load"></span>
</div>
<div class="form-actions">
<button class="btn btn-red5" onclick="resolve()">Login</button>
<input type="reset" class='btn btn-danger' value="Reset">
</div>
</div>
And the Javascript:
<script type="text/javascript">
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url : 'plugin.php?plugin=test',
type : 'post',
data: $("#form").serialize(),
success : function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
};
</script>
I get an alert, but there is no form submit. I checked that with Live http headers.
Why does it not submit the form?
If it doesn't submit the form, because, the #form is not a form.
Change:
<div class="form-horizontal" id="form">
To:
<form class="form-horizontal" id="form">
You need to replace the resp.ajax_success with resp. Let us also know the response of the plugin.php?plugin=test URL.
If you don't want the <form> to get submitted on clicking on the Submit button, add a return false; at the end of the resolve function this way:
var resolve = function () {
jAlert('test', 'test');
$('#ajax_load').html('<img src="templates/img/ajax-loader.gif" alt="">');
$.ajax( {
url: 'plugin.php?plugin=test',
type: 'post',
data: $("#form").serialize(),
success: function( resp ) {
if(resp.ajax_success == false) {
} else {
jAlert('test', 'test');
}
}
});
return false;
};
its because you haven't used the form you are serializing the data from div
<div class="form-horizontal" id="form">
not form the form
should be
<form class="form-horizontal" id="form">