I need some help. I have a page where I display database records as a bootstrap button pill in a display div. I also have an Ajax Submit input that saves new records to the database and dynamically creates a button pill for the new record using the db record id for the button id. The jQuery below allows me to click on the new dynamically created button but it always displays ID = 1 and not the ID shown in view source.
Can someone please explain what I am doing wrong here?
Code of Button Pills created from PHP:
<div class="row">
<div class="col-md-8 col-sm-10 mx-auto mb-3">
<div class="decision-box">
<div class="decision-icon bg-orange-grad"><img src="../assets/img/logos/Sparck-Logo-Icon-Lg-White.png" alt="Sparck-Logo-Icon-Lg" width="40" height="40" /></div>
<div class="decision-text">
<form id="accolorform">
<input type="hidden" name="action" value="colorsave">
<input type="hidden" name="interesttype" value="Favorite Color">
<input type="hidden" name="userid" value="<?php echo $_SESSION['userid']; ?>">
Favorite Color:
<input type="text" class="form-control-inline col-auto no-border no-shadow" id="ac_color" name="interest" placeholder="Type something" autocomplete="off" style="min-width: 200px;">
<span class="float-right" style="margin-right: 15px;">
<button type="submit" class="btn btn-light" id="colorbtn">Add</button>
</span>
</form>
</div>
</div>
<div id="color_pills">
<?php if(!empty($resultlist) && isset($resultlist)){
foreach($resultlist as $r){
if($r['interesttype'] = "Favorite Color"){ ?>
<button id="btn<?php echo $r['id']; ?>" class="btnpill" title="Are you sure you want to delete <?php echo $r['interest']; ?>?"><?php echo $r['interest']; ?> <i id="<?php echo $r['id']; ?>" class="fal fa-minus-circle delete"></i></button>
<?php }
}
}?>
</div>
</div>
</div>
Code of jQuery aJax that creates dynamic button
$("#accolorform").validate({
rules: {
ac_color: {
required: true
}
},
messages: {
ac_color: {
required: 'Please select a Color'
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $(form).serialize(),
success: function(id){
//alert("Color Added");
var name = $("#ac_color").val();
var newpill = '<button id="btn'+id+'" class="btnpill" title="Are you sure you want to delete '+name+'?">'+name+' <i id="'+id+'" class="fal fa-minus-circle delete"></i></button>';
$("#color_pills").append(newpill);
$("#accolorform")[0].reset();
},
error: function(){
alert("Error");
}
});
}
});
Code of Ajax Delete where I am trying to grab dynamic button id:
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var title = $('#btn'+id).attr('title');
var string = 'source=interests&id='+ id ;
if (confirm(title)) {
$.ajax({
type: "POST",
url: "ajaxdelete.php",
data: string,
cache: false,
success: function(){
$('#btn'+id).remove();
}
});
}
return false;
});
The above code looks like it should work and view source shows a button tag that is formatted like the ones created by PHP that work perfectly.
I appreciate any help!
Related
I create survey poll in wordpress plugin to display questions i use ajax to display it
this is my html code
<div id="my_poll">
<button class="start" id="start"><b><?php _e('Start poll questions'); ?></b></button>
<div id="poll" class="container mt-sm-5 my-1">
<form>
<?php
if ($ques->have_posts()) {
while ($ques->have_posts()) {
$ques->the_post();
global $post;
$ID = $post->ID;
$option = get_post_meta($ID, "op1", true);
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id=' . $ID . '&nonce=' . $nonce);
$ques_id = 'Q-' . $ID;
?>
<div id="<?php echo $ques_id ?>" class="questions">
<div class="question ml-sm-5 pl-sm-5 pt-2">
<h3><b><?php _e('Poll Survey'); ?></b></h3>
<div class="py-2 h5"><b class="msg"><?php the_title() ?></b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options">
<label class="options"><?php _e($option['op1']['op1']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op1']['op1']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op2']['op2']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op2']['op2']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op3']['op3']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op3']['op3']) ?>"> <span class="checkmark"></span> </label>
</div>
<div class="d-flex align-items-center pt-3">
<div class="ml-auto mr-sm-5">
<button class="btn btn-success">
<?php
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $ID . '" href="' . $link . '">submit</a>';
?>
</button>
</div>
</div>
</div>
</div>
<?php
}
}
?>
</form>
</div>
</div>
and this is my ajax to show and hide elements
jQuery(document).ready(function() {
jQuery("#poll").hide();
var count = 0;
jQuery(".start").click(function(e) {
jQuery("#poll").show();
jQuery(".start").hide();
});
jQuery(".user_vote").click(function(e) {
e.preventDefault();
option = jQuery('input[name="framework"]:checked').val();
post_id = jQuery(this).attr("data-post_id");
nonce = jQuery(this).attr("data-nonce");
var idArr = [];
jQuery(".questions").each(function() {
idArr.push(jQuery(this).attr("id"));
});
jQuery.ajax({
type: "post",
dataType: "json",
url: myAjax.ajaxurl,
data: {
action: "my_user_vote",
post_id: post_id,
nonce: nonce,
option: option,
},
success: function(response) {
if (response.type == "success") {
count++;
if (count < idArr.length) {
jQuery(".questions").hide();
jQuery("#" + idArr[count]).show();
} else {
jQuery("#my_poll").hide();
alert('Thank you for your time.')
}
} else {
alert("Your vote could not be added");
}
},
});
});
});
in this jquery ajax whene i click start button i display all questoins divs.
but i want display the first question div.
Does anyone have any solutions?
Change the on click event function like below;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery("#poll:first").show(); // id selector!
});
Better way, wirte "poll" word into the class attribute, dont use same id more than one time. If you change the id and class of the elements, your code must be like this;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery(".poll:first").show(); // class selector
});
Also, you can use $ character instead of Jquery;
jQuery("div") EQUAL $("div")
Another way to find first element;
$(".start").click(function(e) {
$(".start").hide();
$(".poll").eq(0).show(); // class selector
});
I have a list product's category and want to edit.
when i click on edit button of particular category open a Bootstrap modal for click ID to update content.
Popup is coming but view is not loading on it.
List of data:
<?php if (is_array($category_list)) {
foreach ($category_list as $item): ?>
<tr>
<td>
<?=$item->category_name?></td>
<td>
<a href="#" class="btn btn-small z-depth-0" data-toggle="modal" data-target="#categoryModal" id="category_modal" data-id="<?=$item->cat_id?>" data-url="<?php $this->config->base_url();?>admin_panel/get_category/<?=$item->cat_id?>">
<i class="mdi mdi-editor-mode-edit"></i>
</a>
</td>
</tr>
<?php endforeach;}
?>
Javascript Function :
<script type="text/javascript">
$(document).on("click", "#category_modal", function () {
var url = $(this).data('url');
alert(url);
jQuery.ajax({
url: url,
success: function(response)
{
alert(response);
jQuery('#categoryModal .modal-content').html(response);
jQuery('#categoryModal').modal('show', {
});
}
});
});
</script>
Controller Function :
public function get_category() {
$cat_id = $this->uri->segment(3);
$data['category'] = $this->admin_model->get_category($cat_id);
$this->load->view('backend/category_popup', $data);
}
category_popup.php View:
<?php
if (is_array($category)) {
foreach ($category as $item) {
$cat_id = $item->cat_id;
$cat_name = $item->category_name;
}
} else {
$cat_id = '';
$cat_name = '';
}
?>
<form action="#" method="post" name="form" style="margin-top: -200px;width: 100%;height: 100%" class="z-depth-4">
<div class="card-panel">
<div class="card-panel cyan lighten-3">
<h4 style="text-align: center">Update Category - <strong><?=$cat_name?></strong></h4>
</div>
<div class="row">
<div class="col l6 s12">
<label for="subcat_name">Category Name</label>
<div class="input-field">
<input id="cat_names" name="cat_name" type="text" class="validate" value="<?=$cat_name?>">
</div>
</div>
</div>
<div class="row">
<div class="col l4 s12">
<button class="btn" type="button" name="action" onclick="update_cat()">Update</button>
</div>
</div>
</div>
</form>
append to ajax the data attribute:
$('#category_modal').on('show.bs.modal', function(e) {
var url = $(this).data('url');
alert(url);
jQuery.ajax({
url: url,
data:{data_id:$(this).attr('data_id')},
success: function(response)
{
alert(response);
jQuery('#categoryModal .modal-content').html(response);
}
});
});
and your controller change:
$cat_id = $this->input->get('data_id');
I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}
In my PHP app I have some content generated by AJAX with form having file input.
This form is located in Bootstrap Modal. I write some data into inputs and upload file using jQuery File Upload Plugin 5.26 and it works fine.
I close modal and load the same content asynchronously by clicking on another list element.
I do the same as before and I have error: 4;
No file was uploaded.
I used the same action, the same modal and form, only difference is that I render it twice using AJAX. Could anyone explain me how to fix this error and how to upload second file?
I would like to add that data from text inputs has changed, but $_FILES is empty array.
Another info is that when I render view first I can upload file, close modal and upload second file.
Problem is when I render this view second time and try to upload file.
AJAX sending POST and getting view:
$.ajax({
type: "POST",
url: "/ksiazka/pobierz-partial",
dataType : 'json',
data: {
id: idObiektu,
template: template,
typ: typObiektu,
fmodel: fmodel
},
success: function(data)
{
$('#ksiazka-tresc').html(data.html);
}
});
Rendering view:
public function pobierzPartialAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$id = $request->getPost('id');
$templatka = $request->getPost('template');
$typ = $request->getPost('typ');
$fmodel = $request->getPost('fmodel');
/* #var $wartosciDoTemplatki \Obiekty\Model\Ommost */
$wartosciDoTemplatki = $this->pobierzWartosciDoTemplatki($templatka, $id, $typ, $fmodel);
$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('template/' . $templatka)
->setVariables(array(
'wartosci' => $wartosciDoTemplatki
));
$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);
$jsonObject = \Zend\Json\Json::encode(array(
'html' => $htmlOutput
), true);
echo $jsonObject;
return $this->response;
}
}
View:
<div class="row" style="padding-bottom: 5px">
<div class="col-sm-6" id="ksiazka-save-table-alert">
<div class="alert alert-success text-center" role="alert" style="padding: 4px; margin-bottom: 0; display: none">Pomyślnie zapisano</div>
</div>
<div class="col-sm-6 text-right">
<img src="/img/30-load.gif" alt="spinner" class="ksiazka-table-spinner" style="display: none">
<div class="btn-group btn-group-sm" role="group">
<a class="btn btn-primary ksiazka-add-photo" data-toggle="tooltip" data-placement="top" title="Dodaj rekord"><i class="fa fa-plus"></i></a>
<a class="btn btn-danger karta-delete-row" data-toggle="tooltip" data-placement="top" title="Usuń rekord"><i class="fa fa-minus"></i></a>
<a class="btn btn-success karta-save-row" data-toggle="tooltip" data-placement="top" title="Zapisz zmiany"><i class="fa fa-check"></i></a>
</div>
</div>
Modal:
<div class="modal fade bs-example-modal-lg" tabindex="-1" aria-hidden="true" id="ksiazkaFileUpload"><div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Dodawanie zdjęcia</h4>
</div>
<div class="modal-body" style="min-height: 450px" id="hide-spinner">
<div class="row">
<div class="col-sm-12">
<form id="upload" method="post" action="/ksiazka/upload-file" enctype="multipart/form-data">
<input type="hidden" name="model" value="<?php echo $wartosci['model-pliki'] ?>" />
<input type="hidden" name="tabela" value="<?php echo $wartosci['tabela-pliki'] ?>" />
<input type="hidden" name="MASTER_ID" />
<?php if(isset($wartosci['OM_ID'])): ?>
<input type="hidden" name="OM_ID" value="<?php echo $wartosci['OM_ID'] ?>" />
<?php endif ?>
<label for="NR">NR</label>
<input type="text" class="form-control" name="NR" />
<label for="OPIS">Opis</label>
<input type="text" class="form-control" name="OPIS" />
<div id="drop" style="margin-top: 10px">
<input type="file" name="upl" />
<i class="fa fa-plus"></i> Dodaj
</div>
<ul style="margin-top: 20px">
The file uploads will be shown here
</ul>
</form>
</div>
</div>
</div>
</div>
Upload file action:
public function uploadFileAction()
{
$allowed = array('png', 'jpg', 'gif','zip', 'txt', 'rtf');
var_dump($_FILES, $_POST);
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0)
{
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
$file = file_get_contents($_FILES['upl']['tmp_name']);
$idTypu = 2;
$values = $_POST;
$model = $values['model'];
$tabela = $values['tabela'];
$values['ID_TYPU_PLIKU'] = $idTypu;
$values['PLIK'] = 'empty_blob()';
$values['OPIS'] = "'". $values['OPIS'] . "'";
$values['NR'] = "'". $values['NR'] . "'";
$values['NAZWA_PLIKU'] = "'". $_FILES['upl']['name'] . "'";
unset( $values['model']);
unset( $values['tabela']);
$session = new \Zend\Session\Container('namespace');
$zasobId = $session->item;
$zasob = $this->getZasobyTable()->zwrocSchematPoId($zasobId);
$fun = 'get' . $model . 'Table';
$this->$fun()->saveUploadedFile($file, $values, $tabela, $zasob);
echo 'ok';
exit;
}
echo '{"status":"error"}';
exit;
}
JS script:
var ul = $('#upload ul');
$('.file').click(function(e){
e.preventDefault();
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
pasteZone: $(document),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
var tpl = $('<li class="working"><input type="text" value="0" data-width="20" data-height="20"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<b>' + formatFileSize(data.files[0].size) + '</b>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
},
done: function (e, data) {
}
});
We don't have any code yet but the most common mistake in ajax transfers are how they define the data in the call. I upload files like this: (try it)
$.ajax({
type: 'post',
url: 'upload.php',
data: new FormData($('form')[0]),
processData: false,
contentType: false,
success: function (result) {
//show a success message or something else
}
});
I am trying to add a voting/poll panel in sidebar of my HTML/PHP/MySQL website.
Scenario
I have list of plans for separate places in MySQL Database Table, when some one search for the place they will also see list of plans decided for that place. They can vote for what plan to be executed next in that place.
What I have worked so far?
I am able to fetch plans for specific places when viewers search for any place.
Code used:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Vote next plan
</h3>
</div>
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios">';
echo $planvote['plan_name'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
</div>
Screenshot
Now, I have a database table with columns
|sn|plan_name|poll|
|1 |Path way |0 |
How can I add/change value of poll in some on selects radio button on the voting form and clicks vote.
P.S. You can answer ideas or help me with code if you want to.
You could add a value to you radio button:
echo '<input type="radio" name="optionsRadios">';
After you did this, you could make an ajax call where you update the results by getting the value of the radiobutton. Make sure to add an id to your button:
<button id='vote_button' type="button" class="btn btn-primary btn-sm">
Ajax call:
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
}
});
}
});
In your ajax call you can update the voting system by using some PHP code and an SQL like where $val = the passed value to your ajax:
UPDATE your_table SET poll = poll + 1 WHERE sn = $val
But you will probably have to add way more coding than this, else people can just spam the voting system..
Solution
JS/Ajax Script
<script src="js/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
console.log(html);
$('.notice').html(html);
},
error: function(err) {
console.log(err);
}
});
}
});
HTML/ PHP
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios" value="'.$planvote['sn'].'">';
echo $planvote['vdc_PlName'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button id="vote_button" type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
Finally it update the value of poll in database table.