Unable to get the ID of the button - javascript

Please have a look at the following code
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
$word="";
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="<?php $enSpell ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
xxx($(this).attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
function xxx(id)
{
alert(id);
}
function increment()
{
$.ajax({
url: "http://localhost/cake2/flip2/correct",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
}
});
</script>
Please consider how those buttons are being generated inside the PHP loop.
I am trying to print the ID of a button using the below code.
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
xxx($(this).attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});
But the alert dialog is empty. What has gone wrong here?

You are using $(this) in the wrong place. Save id of button before ajax call and use in ajax call done() function.
$( ".btn-success" ).click(function(){
console.log("Red Button");
idOfButton = $(this).attr('id');
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
alert(idOfButton);
console.log( "The act has been done");
toclose.toggle();
});
});
You can also save the event source before ajax call and later use it to get the id of event source element.
$( ".btn-success" ).click(function(){
console.log("Red Button");
eventSourceButton = $(this);
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
alert(eventSourceButton.attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});

You need to specify a context parameter in your $.ajax call. The this keyword does not refer to your .btn.sucess but to the window object or to whatever it has been assigned to if a call function was used.
See this example from jQuery ajax docs :
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" ); // this refers to document.body
});
I hope that helps !

Related

How to submit HTML form data in Modal Box using PHP ajax?

I want to add state name in my state mysql table in database using PHP and Ajax but the modal box is not submitting the information. I posted all my code for single button submission in model box and are as follows:
My directory structure is:
test.html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="./model.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js">
</script>
</head>
<body>
<button id="add_state">Add State</button>
<div>
<?php
include('server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select name='StateName'>";
echo "<option>select</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value=$row[StateName]> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
<div id="add_state_model" class="add_state_model">
<div class="add_state_model_content">
<span class="state_model_close">×</span>
<form id="state_submit_form" method="post" action="">
<label>Enter State:</label>
<input type="text" name="state">
<input type="submit" name="state_submit">
</form>
<div class="message_box" style="margin-left: 60px;"></div>
</div>
</div>
<script src="./model.js"></script>
</body>
</html>
and for backend i am using javascript and PHP
model.js
var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];
add_state_button.onclick = function(){
add_state_model.style.display = "block";
}
add_state_span.onclick = function(){
add_state_model.style.display = "none";
}
window.onclick = function(event) {
if (event.target == add_state_model) {
add_state_model.style.display = "none";
}
}
$(document).ready(function(){
var delay = 1000;
$('[name="state_submit"]').click(function(e){
e.preventDefault();
var state = $('#state_submit_form').find('[name="state"]').val();
if(state === ''){
$('.message_box').html(
'<p><span style="color:red;">Please enter state name!</span></p>'
);
$('[name="state"]').focus();
return false;
}
console.log(state);
$.ajax({
type: "POST",
url: "server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="./tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
});
});
And also there is server page addstate.php
<?php
if ( ($_POST['state']!="") ){
$state = $_POST['state'];
include('connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";
if ($conn->query($insertSql) === TRUE) {
echo "<span style='color:green;'>
<p>State added to dropdown</p>
</span>";
}else{
printf("Error: %s\n", $conn->error);
}
}
?>
and connection.php file
<?php
// set the timezone first
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}
$conn = new mysqli('localhost', 'root', '');
//check connection
if($conn->connect_error){
die("Connection Failed".$conn->connect_error);
}
//connect database
mysqli_select_db($conn, 'crm');
?>
and the css file model.css, it is used for Model Box pop up
.add_state_model {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.add_state_model_content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 30%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.state_model_close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.state_model_close:hover,
.state_model_close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
I am getting this below error:
Make me correct if I am not wrong
You can visit this URL this will help you to solve your problem How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?
Or try to change URL path
I have tried on my end it's working for me
url: "http://localhost/CRM/server/addstate.php",
to
url: "server/addstate.php"
If any help feel free to ask me
in your ajax request
data object accept only json object and you have passed query string
try this code
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
and second thing settimeout accept delay in miliseconds which i have specified 1 second

AJAX - No Refresh , loading auto refresh to another page

My only problem is the page does not load auto refresh, tho it is loading when i refresh the page.. P.S Im loading the page to another page
here is my html and ajax code with its database.
My Trigger Button
<?php
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '
<button class="btn btn-danger nav-link delannouncement" id="delannouncement">Resume System</button>';
$dataid = $row['id'];
}
}else{
echo '<button class="btn btn-primary nav-link announcement" id="announcement">Passenger Announcement</button>';
}
?>
Fetching the Data in Database
Here is where I call the data in mysql from ajax to here.
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '<div id="myModal" class="modal" style="position:fixed; display: none; padding-top: 100px;
left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.9); ">
<div class="container" style="width: 100%">
<div class="card col-12" style="background-color: red; color: white;">
<div class="card-header">
<p><h3 class="text-center">Announcement</h3></p>
</div>
<div class="card-body text-center">
<h5>'.$row['additional_info'].'</h5>
<p>Please click refresh button to resume after the announcement</p>
</div>
</div>
</div>
<img class="modal-content" id="img01">
</div>';
$dataid = $row['id'];
}
}
?>
</div>
<script>
document.getElementById('myModal').style.display='block';
My AJAX code
This is my AJAX code, here is where I got the problem the modal will not load right after I clicked the button, before it will work, I need to refresh the page how to fix this problem
$('.announcement').on("click", function () {
$.confirm({
title: 'Announcement',
content: '' +
'<form action="" class="formName">' +
'<div class="form-group">' +
'<label>Announcement Info</label>' +
'<input type="text" placeholder="Enter announcement here" class="add-info form-control" required />' +
'</div>' +
'</form>',
buttons: {
formSubmit: {
text: 'Submit',
btnClass: 'btn-blue',
action: function () {
var addInfo = this.$content.find('.add-info').val();
$.confirm({
type: 'red',
theme: 'material',
title: 'Are you sure you want to make an announcement?',
content:'<strong>Announcement Info:</strong> ' + addInfo,
buttons: {
Yes: {
btnClass: 'btn-green',
action: function () {
$.ajax({
type: "POST",
url: "announcement.php",
data: {
addInfo: addInfo
},
dataType: "text",
success: function (data) {
window.location.replace("change-password.php");
},
error: function (err) {
console.log(err);
}
});
}
},
No: {
text: 'No', // With spaces and symbols
action: function () {
$.alert('Announcement Cancelled');
}
}
}
});
}
},
cancel: function () {
//close
},
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
});
I am new to ajax coding and syntax help me to finish this project please.
Do not get into this much complex solution, just return data in json(or xml) format form your API, and then render whatever html you want on frontend(i.e. do not return html form Backend)

AJAX Auto Refresh / Page without refresh after submitting Button - HTML / PHP

My only problem is the page does not load auto refresh, tho it is loading when i refresh the page..
here is my html and ajax code with its database.
My Trigger Button
<?php
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '
<button class="btn btn-danger nav-link delannouncement" id="delannouncement">Resume System</button>';
$dataid = $row['id'];
}
}else{
echo '<button class="btn btn-primary nav-link announcement" id="announcement">Passenger Announcement</button>';
}
?>
Fetching the Data in Database
Here is where I call the data in mysql from ajax to here.
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '<div id="myModal" class="modal" style="position:fixed; display: none; padding-top: 100px;
left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.9); ">
<div class="container" style="width: 100%">
<div class="card col-12" style="background-color: red; color: white;">
<div class="card-header">
<p><h3 class="text-center">Announcement</h3></p>
</div>
<div class="card-body text-center">
<h5>'.$row['additional_info'].'</h5>
<p>Please click refresh button to resume after the announcement</p>
</div>
</div>
</div>
<img class="modal-content" id="img01">
</div>';
$dataid = $row['id'];
}
}
?>
</div>
<script>
document.getElementById('myModal').style.display='block';
My AJAX code
This is my AJAX code, here is where I got the problem the modal will not load right after I clicked the button, before it will work, I need to refresh the page how to fix this problem
$('.announcement').on("click", function () {
$.confirm({
title: 'Announcement',
content: '' +
'<form action="" class="formName">' +
'<div class="form-group">' +
'<label>Announcement Info</label>' +
'<input type="text" placeholder="Enter announcement here" class="add-info form-control" required />' +
'</div>' +
'</form>',
buttons: {
formSubmit: {
text: 'Submit',
btnClass: 'btn-blue',
action: function () {
var addInfo = this.$content.find('.add-info').val();
$.confirm({
type: 'red',
theme: 'material',
title: 'Are you sure you want to make an announcement?',
content:'<strong>Announcement Info:</strong> ' + addInfo,
buttons: {
Yes: {
btnClass: 'btn-green',
action: function () {
$.ajax({
type: "POST",
url: "announcement.php",
data: {
addInfo: addInfo
},
dataType: "text",
success: function (data) {
window.location.replace("change-password.php");
},
error: function (err) {
console.log(err);
}
});
}
},
No: {
text: 'No', // With spaces and symbols
action: function () {
$.alert('Announcement Cancelled');
}
}
}
});
}
},
cancel: function () {
//close
},
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
});
I am new to ajax coding and syntax help me to finish this project please.
$('.announcement').on("click", function () {
$.confirm({
///YOUR LONG CODE
});
//ALL YOU NEED
return false;
});
just return false as firing an event when you submit a button inside a form.. :)

Calling PHP code with Ajax [duplicate]

This question already has answers here:
How to access a model method with javascript
(2 answers)
Closed 8 years ago.
Please have a loook at the following code
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
//$this->requestAction('/flip2/correctAnswer')
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="acertei" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="Errei" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
$("#acertei").on("click", function() {
$.ajax({
url: "/flip2/correctAnswer",
success: function(data) {
// Do whatever you need to do with the response here.
},
});
});
});
</script>
This is the View of a CakePHP page. $this->requestAction('/flip2/correctAnswer') will call the correctAnswer() method in Controller.
Here If I call the $this->requestAction('/flip2/correctAnswer') on page load, this works fine. I need to call this when the Acertei button is clicked, so I added it to the Ajax as proposed by a fellow SO user. However, it didn't work, the function do not get called. Why is this?
I would recommend first giving your Acertei button a unique ID like "acertei" for example (it currently shares the ID of "2" with its sibling button). Then with jQuery you can do the following:
$("#acertei").on("click", function() {
$.ajax({
url: "/flip2/correctAnswer",
success: function(data) {
// Do whatever you need to do with the response here.
},
});
});
This adds a click event to the Acertei button that will start an AJAX request to the 'flip2/correctAnswer' URL.

How to save the data from dialog box?

I have an accordion where the link of dialog box present, but when the dialog box open it didn't save the field and not redirecting, what's the issue? i tried a lot to figure out but didn't get any success.
This is my view :
<?php v_start($d);?>
<script>
$(function() {
var icons = {
header: "ui-icon-circle-arrow-e",
activeHeader: "ui-icon-circle-arrow-s"
};
$( "#accordion" ).accordion({
icons: icons
});
$( "#toggle" ).button().click(function() {
if ( $( "#accordion" ).accordion( "option", "icons" ) ) {
$( "#accordion" ).accordion( "option", "icons", null );
} else {
$( "#accordion" ).accordion( "option", "icons", icons );
}
});
});
$(function()
{
var $dialog = $("#view_dialog").dialog({
autoOpen: false,
title: 'Add Group',
height: 200,
width: 1200,
resizable: true,
modal: true,
buttons:
{
"Ok": function()
{
$(this).dialog("close");
}
}
});
$(".view_dialog").click(function()
{
$dialog.load($(this).attr('href'), function ()
{
$dialog.dialog('open');
});
return false;
});
});
</script>
<div class="inner-heading">
<div class="inner-heading-left">
<h1><?php echo __l('Manage Groups');?></h1>
</div>
</div>
<div id="accordion">
<div>
<h3 style="margin-right: 0PX; margin-left: 30px; font-size:20px;"><?php echo __l('User Define Group') ?></h3>
</div>
<div class="firsttable">
<div class="top-button">
//dialog link
<?php echo $this->Manager->hlink('Add Group', array('action' => 'add_define_group'), array('class' => 'view_dialog')); ?>
<?php echo $this->Manager->link('Add Group',array('action'=>'add_define_group')) ?>
</div>
</div>
<div>
<h3 style="margin-right: 0PX; margin-left: 30px; font-size:20px;"><?php echo __l('Mailing Group') ?></h3>
</div>
<div class="firsttable">
<div class="top-button">
<?php echo $this->Manager->link('Add Group',array('contoller'=>'ContactGroups','action'=>'add_define_group','mailing')) ?>
</div>
</div>
<div>
<h3 style="margin-right: 0PX; margin-left: 30px; font-size:20px;"><?php echo __l('Dynamic Group') ?></h3>
</div>
<div class="firsttable">
<div class="top-button">
<?php echo $this->Manager->link('Add Group',array('contoller'=>'ContactGroups','action'=>'add_define_dynamic_group')) ?>
</div>
</div>
<div id="view_dialog"></div>
</div>
<?php v_end();?>
Bascially i trying to open the dialog box in the accordion , dialogbox will save the data and redirect it, but it didn't save any data and didn't redirect, what can i do with that?
Any body's help will be appreciated, thanks a lot in advance.

Categories

Resources