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";
}
Related
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".
I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?
Form with id="surveyImage13"
<form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
Form with ID="surveyImage18"
<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
</div>
</div>
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
AJAX call
<script type="text/javascript">
$("#surveyImage13").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
</script>
<script type="text/javascript">
$("#surveyImage13").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage13').attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage13").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
</script>
Why not give your forms a common class
$('.myClass').validate({ ...
})
$('.myClass').submit(...
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.
<form id="surveyImage13">...</form>
<form id="surveyImage18">...</form>
$("#surveyImage").submit...
I think you may be able to resolve the issue by using a different query selector string.
$('#surveyImage13 #surveyImage18').submit...
or...
$('form[id^="surveyImage"]').submit...
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id
$(".btn").click(function(e) {
e.preventDefault();
var formId = '#'+ $(this).parents('form').attr('id');
var route=$(formId).attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $(formId).valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
Thanks for all answers but I found solution. Im working in LARAVEL therefore I used foreach loop based on which i was able to assign dynamic ID on HTML forms.
#foreach($questionnaire_by_images as $t)
<form id="surveyImage{{$t->id}}">...</form>
<form id="surveyImage{{$t->id}}">...</form>
#endforeach
script
#foreach($questionnaire_by_images as $t)
<script type="text/javascript">
$( document ).ready(function() {
$("#surveyImage{{$t->id}}").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
$("#surveyImage{{$t->id}}").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage{{$t->id}}').attr('action');
var survey_image_pivot = $("#survey_image_pivot{{$t->id}}").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline .radio{{$t->id}}').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage{{$t->id}}").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'survey_image_pivot': survey_image_pivot},
success: function(response){
$("#surveyImageForm{{$t->id}}").css("display", "none");
$("#surveyImageAjax{{$t->id}}").css("display", "block");
$('#SurveyTableAjaxColumn1{{$t->id}}').append(response[1]);
$('#SurveyTableAjaxColumn2{{$t->id}}').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
});
</script>
</script>
#endforeach
I am trying to catch an integer id with "onClick" function. And send it database with ajax. And display all related information to this id in alert box.
<button class="show">Show Popup</button>
<div class="Popup Confirm">
<input type="text" id="id" />
<button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>
</div>
<script>
$('.show').click(function(){
$(".Popup").show();
$("#id").val(4);
});
function getId(id = null) {
if(id) {
$.ajax({
url: 'abc.php',
type: 'post',
data: {id: id},
dataType: 'text',
success:function(response) {
alert(id);
}
});
}
else {
// error messages
alert("No id selected");
}
}
</script>
Instead of
<button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>
you should use:
<button type="button" onclick="getId(document.getElementById('id').value);">Get</button>
The input field value is available through the value property, not innerHTML.
Fiddle: https://jsfiddle.net/3cjh6bf0/
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);
});
I have an issue where I wanted to submit by form with javascript but obviously I have hit an issue when trying to do this and wondered if anyone could help me with the issue, more information can be found below on the issue and the code samples.
Hello. My form .submit function isn't calling when I submit my form that's added, can anyone help?
So first, the form is inside the modal:
<div class="modal fade" id="editPositionModal" role="dialog">
<div class="modal-dialog" style="width:460px;">
<!-- Modal content-->
<div class="modal-content" id="edit-position-content">
</div>
</div>
</div>
As you can see, the form has yet to be added, so I add it using a function:
function modifyPosition(businessId, positionId) {
$.ajax({
url: ajaxCallUrl + 'api/ajax/positions/' + positionId + '/get-edit-content',
type: "GET",
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...');
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data) {
lastModifiedPositionId = positionId;
$('#edit-position-content').html(data);
$('#editPositionModal').modal('show');
},
});
}
I call the above function on the button I click to open the modal with the form on.
Heres the modal content gotten by the ajax request:
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Creating a new position</h4>
</div>
<div class="modal-body">
<form id="save_edit_position" method="POST">
<label>Position Title</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_title }}">
<label>Position Pay</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_shift_wage }}">
<label>Position Type</label>
<select class="form-control" name="business_position_type" id="position_type_modify">
<option value="employee">Employee</option>
<option value="supervisor">Supervisor</option>
<option value="manager">Manager</option>
<option value="ownership">Ownership</option>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
</div>
<script>
var element = document.getElementById('position_type_modify');
element.value = '{{ $position->position_type }}';
</script>
And here is the javascript handler for the form submit, on the end of the page where the modal content is included on:
$("#save_edit_position").submit(function(e) {
alert('Submit Called...');
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
});
Delegate you submit event, your form is dynamically added to the page so you need event delegation to bind your event
$('body').on('submit',"#save_edit_position",function(e) {
....
or use a delegated click event
$('body').on('click',"#save_edit_position input[type='submit']",function(e) {
....
Note if you have multiple forms on the page with the same id then only the first form with the id will work ids must be unique
You should use a onSubmit="" function handler
onsubmit="functionhere();"
Your form is incorrectly structured
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
You cannot, legitimately, straddle the form tag like this and from previous experience this will likely cause problems.
You can also change your submit type to button like that and add an onclick event to a javascript function. If though your form generate dynamically, but I think this should work.
<div class="modal-footer">
<input class="btn btn-success" type="button" value="Save" onclick="_submitForm();"/>
</div>
And your js should be
function _submitForm(){
alert('Submit Called...');
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
}
Try
$("form.save_edit_position").submit(function(e) {...}
I have one more doubt, Can you please share exact location of javascript handler for the form submit in code!!
I've two forms on the same page. On clicking any one of the buttons, both queries of the buttons are being submitted as I've used the function IsPost like if(IsPost){ //run queries}
Since both the forms are on the same page, on submission of any button, both the events of the two buttons are triggered.
I want to run separate queries on submission of each of the buttons.
In php, we used if(isset($_REQUEST['buttonname'])){ //run queries }.
Is there any such way, I can achieve the same in cshtml?
Update
What if I already have passed a value in the buttons?
Like for eg:
<div class="btn-group pull-right">
#{
var followersearchcommand = "SELECT * from follow where follow_followerid = #0 and follow_followingid = #1";
var followsearch = db.Query(followersearchcommand, follower_id, row.student_id);
}
#if(followsearch.Count > 0){
<button class="btn btn-primary" type="submit" name="unfollow_followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="unfollow_button" value="unfollow" title="Follow">UnFollow</button>
}
else{
<button class="btn btn-primary" type="submit" name="followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="follow_button" value="follow" title="Follow">Follow</button>
}
</div>
Assign to both buttons the same name and test their value:
#{
if (IsPost){
if(Request["button"] == "buttonA"){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="button" value="buttonA" />
<input type="submit" name="button" value="buttonB" />
</form>
Edited
If you want to have two distinct forms, you could use the IsEmpty() method:
#{
if (IsPost){
if(!Request["buttonA"].IsEmpty()){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="buttonA" value="buttonA" />
</form>
<form method="post">
<input type="submit" name="buttonB" value="buttonB" />
</form>
html:
<form id="a">
<button type="submit">Submit A</button>
</form>
<form id="b">
<button type="submit">Submit B</button>
</form>
javascript:
$(function(){
$("#a").submit(function(e){
e.preventDefault();
// Query A
alert('A');
});
$("#b").submit(function(e){
e.preventDefault();
// Query B
alert('B');
});
});
Demo
Edit:
You can make an ajax call to your controller's action:
$.ajax({
type: "POST",
url: "#Url.Action("actionName", "controllerName")",
data: { /* your data */ },
success: function (data, textStatus, jqXHR) {
// success
},
error: function (jqXHR, textStatus, errorThrown) {
// error
}
});
And in your controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult actionName(/* your data */)
{
var success = DoSomething();
if (!success)
{
throw new HttpException(500, "Server error!");
}
return Json("");
}
Something along those lines...
Hope this helps!