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/
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 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'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');
I have a login form that is working in a kinda same way I don't know why this won't work. When I press 'Criar' it does nothing, it doesn't even change the text of that Button to 'Loading ...' as I have stated on beforeSend function. I started using Jquery so sorry if it is a stupid mistake!
Form
<form id="criarSubCategoria-form" class="form-horizontal" role="form" action="criarCategoria.php" method="post">
<div class="col col-lg-4">
<label for="nome">Nome:</label>
<input type="text" class="form-control" id="nome" name="nome">
</div>
<br>
<div class="form-group margin-top-pq">
<div class="col-sm-12 controls">
<button type="button" class="btn btn-primary" name="btn-criarSubCategoria" id="btn-criarSubCategoria">
Criar
</button>
</div>
</div>
</form>
click Function
$('document').ready(function(){
$("#btn-login").click(function(){}); // this one is working so I didn't put all the code here
$("#btn-criarSubCategoria").click(function(){
var data = $("#criarSubCategoria-form").serialize();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
});
jQuery is not define. Or use jQuery instead of $ will works.
Change 1st line
jQuery(document).on("click", "#btn-criarSubCategoria", (function(e, $){
Try using this as your click function
$(document).on("click", "#btn-criarSubCategoria", (function(e){
var data = $("#criarSubCategoria-form").serialize();
e.preventDefault();
$.ajax({
type : 'POST',
url : '../functions/criarCategoria.php',
data : data,
dataType: 'json',
beforeSend: function()
{
$("#btn-criarSubCategoria").html('Loading ...');
},
success : function(response){
if(response.codigo == "1"){
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'none')
}else{
$("#btn-criarSubCategoria").html('Entrar');
$("#login-alert").css('display', 'block')
$("#mensagem").html('<strong>Erro! </strong>' + response.mensagem);
}
}
});
});
Hope this gets your work done.
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>