jQuery submit form with AJAX problem - javascript

Here is my jQuery code:
<script type="text/javascript">
//<!--
$(document).ready(function() {
$('input[type="submit"]').click(function() {
$.ajax({
type: 'POST',
url: $('form').attr('action'),
success: function(data) {
//
}
});
return false;
});
}); //-->
</script>
What I want to do after the submit button is clicked is:
make an AJAX request to the page identified by form's action attribute (which happens to be the same php script with the form... so basically the form should submit to the same page).
replace the HTML of the whole page with the ajax request returned value.
However, I don't know how to do that. There is no html or body tag on the page with the form as the form is getting icnluded in another page with jQuery.
So how to replace the HTML of the page with the HTML ajax returns?
This is how the whole HTML looks like (this is evrything, there is no html or body tag):
<form enctype="application/x-www-form-urlencoded" method="post" action="editDocumentQuestion.php?iqid=-5">
<dl>
<dt>
<label for="questionBody">Otázka:</label>
</dt>
<dd style="margin-left: 0;">
<textarea name="questionBody" id="questionBody" rows="4" cols="95" style="border: 1px solid #2278B9; font-family: sans-serif;">Otazka</textarea>
</dd>
<dt style="padding-top: 1em;">
<label for="questionCorrectAnswer">Odpovede:</label>
</dt>
<dd style="margin-left: 0;">
<div class="pad-top">
<div style="margin-right: 1em; float: left;"><input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="1" checked="checked" />a)</div>
<div style="float: left;"><textarea name="questionAnswer1" id="questionAnswer1" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved a</textarea></div>
<div style="clear: both; height: 0; line-height: 0;"></div>
</div>
<div class="pad-top">
<div style="margin-right: 1em; float: left;"><input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="2" />b)</div>
<div style="float: left;"><textarea name="questionAnswer2" id="questionAnswer2" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved b</textarea></div>
<div style="clear: both; height: 0; line-height: 0;"></div>
</div>
<div class="pad-top">
<div style="margin-right: 1em; float: left;"><input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="3" />c)</div>
<div style="float: left;"><textarea name="questionAnswer3" id="questionAnswer3" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved c</textarea></div>
<div style="clear: both; height: 0; line-height: 0;"></div>
</div>
</dd>
<dt>
</dt>
<dd style="margin-left: 24.5em;">
<input type="submit" name="editovatDokumentovuOtazku" id="editovatDokumentovuOtazku" value="Ulož" style="width: 6em; padding: .3em 0;" />
</dd>
</dl>
</form>
<script type="text/javascript">
//<!--
$(document).ready(function() {
$('input[type="submit"]').click(function() {
$.ajax({
type: 'POST',
url: $('form').attr('action'),
success: function(data) {
//
}
});
return false;
});
}); //-->
</script>

Even though there is no body or html tag you should be able to replace it like this:
<script type="text/javascript">
//<!--
$(document).ready(function() {
$('input[type="submit"]').click(function() {
$.ajax({
type: 'POST',
url: $('form').attr('action'),
success: function(data) {
$('body').html(data);
}
});
return false;
});
}); //-->
</script>
Firefox 3.6.8, IE 8 and Chrome automatically inserts html and body tags if they are not present (those are the ones I have tested against)

replace the HTML of the whole page
with the ajax request returned value.
Try modifying your success handler like this:
success: function(data) {
$('form').after(data).end().remove();
}
What it does is that it inserts ajax data after your current form with .after(data) and end() is used to revert back to the form and finally remove() is used to remove the form.

Related

How to pass data to database using WYSIWYG HTML Javascript Editor with Django.

After a lot of trial and error, I'm stuck. I am trying to create my own WYSIWYG editor with Django. I have created the WYSIWYG editor, I just can't seem to figure out how to incorporate my editor/HTML/Django form altogether. Here is my HTML:
<!DOCTYPE html>
{% extends "base1.html" %}
<title>{% block title %} Create Information {% endblock %}</title>
{% block body_block %}
<form method="POST" enctype="multipart/form-data" autocomplete=off>
<style>
div#textEditor{ margin: 0 auto; width: 750px; height: 300px; }
div#theRibbon{ border-bottom: none; padding: 10px; background-color: rgb(40,110,89); color: white; border-radius: 8px 8px 0px 0px; }
div#richTextArea{ border: 2px solid rgb(40,110,89); height: 100%; width: 746px; background-color: white; }
iframe#theWYSIWYG{ height: 100%; width: 100%; }
div#theRibbon > button { color: white; border: none; outline: none; background-color: transparent; cursor: pointer; }
div#theRibbon > button:hover{ background-color: rgb(20,90,70); transition: all 0.3s linear 0s; }
input[type="color"]{ border: none; outline: none; background-color: transparent; }
</style>
<script> window.addEventListener("load",function(){ var editor = theWYSIWYG.document; editor.designMode = "on"; boldButton.addEventListener("click", function(){ editor.execCommand("Bold", false, null); },false);
italicButton.addEventListener("click", function(){ editor.execCommand("Italic", false, null); },false);
supButton.addEventListener("click", function(){ editor.execCommand("Superscript", false, null); },false);
subButton.addEventListener("click", function(){ editor.execCommand("Subscript", false, null); },false);
strikeButton.addEventListener("click", function(){ editor.execCommand("Strikethrough", false, null); },false);
orderedListButton.addEventListener("click", function(){ editor.execCommand("InsertOrderedList", false, "newOL" + Math.round(Math.random() * 1000)); },false);
unorderedListButton.addEventListener("click", function(){ editor.execCommand("InsertUnorderedList", false, "newOL" + Math.round(Math.random() * 1000)); },false);
fontColorButton.addEventListener("change", function(event){ editor.execCommand("ForeColor", false, event.target.value); },false);
highlightButton.addEventListener("change", function(event){ editor.execCommand("BackColor", false, event.target.value); },false);
fontChanger.addEventListener("change", function(event){ editor.execCommand("FontName", false, event.target.value); },false);
fontSizeChanger.addEventListener("change",function(event){ editor.execCommand("FontSize",false,event.target.value); },false);
linkButton.addEventListener("click", function(){ var url = prompt("Enter a URL", "http://"); editor.execCommand("CreateLink", false, url); }, false);
unLinkButton.addEventListener("click",function(){ editor.execCommand("UnLink",false,null); },false);
undoButton.addEventListener("click",function(){ editor.execCommand("undo",false,null); },false);
redoButton.addEventListener("click",function(){ editor.execCommand("redo",false,null); },false);
submitButton.addEventListener("click",function(){ richText.value = theWYSIWYG.document.body.innerHTML; theForm.submit(); },false); },false);
</script>
{% csrf_token %}
<div class="box3">
<h2 class="title">Create New Information</h2>
<label class="label6">New Information</label>
<div id="textEditor">
<div id="theRibbon">
<button id="boldButton" title="Bold"><b>B</b></button>
<button id="italicButton" title="Italic"><em>I</em></button>
<button id="supButton" title="Superscript">X<sup>2</sup></button>
<button id="subButton" title="Subscript">X<sub>2</sub></button>
<button id="strikeButton" title="Strikethrough"><s>abc</s></button>
<button id="orderedListButton" title="Numbered list">(i)</button>
<button id="unorderedListButton" title="Bulleted list"">•</button>
<input type="color" id="fontColorButton" title="Change Font Color">
<input type="color" id="highlightButton" title="Highlight Text">
<select id="fontChanger">
<option value="Times New Roman">Times New Roman</option>
<option value="Consolas">Consolas</option>
<option value="Tahoma">Tahoma</option>
<option value="monospace">Monospace</option>
<option value="cursive">Cursive</option>
<option value="sans-serif">Sans-Serif</option>
<option value="Calibri">Calibri</option>
</select>
<select id="fontSizeChanger">
<script> for(var i = 1; i < 10; i++){ document.write("<option value='"+i+"'>"+i+"</option>"); }
</script>
</select>
<script> var fonts = document.querySelectorAll("select#fontChanger > option"); for(var i = 0; i < fonts.length; i++){ fonts[i].style.fontFamily = fonts[i].value; }
</script>
<button id="linkButton" title="Create Link">Link</button>
<button id="unLinkButton" title="Remove Link">Unlink</button>
<button id="undoButton" title="Undo the previous action">←</button>
<button id="redoButton" title="Redo">→</button>
</div>
<div id="richTextArea">
<iframe id="theWYSIWYG" name="theWYSIWYG" frameborder="0">
<textarea name="newinformation">{{ form.newinformation }}</textarea>
</iframe>
</div>
</div>
The form renders correctly, but ultimately I keep getting the following error
"null value in column "newinformation" violates not-null constraint when I submit the form. My model is defined correctly. Essentially the data that I am putting in the WYSIWYG is not being passed on to the database. I am using individual fields in my form, and I can't figure out how to essentially merge the WYSIWYG editor and my {{ form.newinformation }} field. I incorporated the form.newinformation in my code sample above to show what I've tried but that does not work.
Thanks in advance for any ideas.
your HTML is wrong.
your form does not closed and you put your input into an iFrame.
so when you POST your form content of iFrame does not post to server.

forcing iframe submit to open in parent window

I am trying to embed a form on my wix website. The idea is that when someone submits the form, a "thank you" page will be displayed instead of the original parent page. Right now, the way the code is written, the "thank you" page is displayed upon submit, but is shown within the iframe, with scrolls up/down and to the sides. I want to force the "thank you" page to be displayed out of the iframe.
I'm a novice to coding, so I would really appreciate it if you could tell me what code I should enter and where in the code it should go. I've included the original code of the form.
Thanks in advance,
Anat
<!-- AT Popup Beta 2017 BEGIN -->
<link href="//cdn-media.web-view.net/popups/style/v1/main_combined.css" rel="stylesheet" type="text/css" />
<div id="_atPopupSU" class="shown"><div class="bl-template row-fluid bl-content-removable popup-dir-ltr" id="template-body" data-page-width="383" data-new-from-template="false"> <!-- BEGIN TEMPLATE OUTER --> <div class="bl-template-main-wrapper span12" id="bl_0" valign="top"> <!-- BEGIN TEMPLATE MARGIN (Outside Margin - Padding) --> <div class="bl-template-margin span12" id="bl_1" valign="top"> <!-- BEGIN TEMPLATE WRAPPER (Background) --> <div class="template-main-table bl-template-background span12" id="bl_2" valign="top"> <!-- BEGIN TEMPLATE CONTAINER (Border, Inner Padding) --> <div class="bl-template-border span12" id="bl_3" valign="top"> <!-- BEGIN ZONES CONTAINER --> <!--zone-marked--> <div class="bl-zone bl-zone-dropable bl-zone-body row-fluid" id="bl_4" style="margin-top: 0px !important; background-color: transparent;" name="BodyZone" valign="top" height=""> <div class="bl-block bl-block-signuptextpage" id="bl_5" blocktype="signuptextpage" name="signuptextpage" style="width: 383px;"><div class="bl-block-content" contenteditable="false"> <div> <div class="bl-block-content-table bl-block-dir-ltr span12"> <div class="bl-block-content-row bl-block-content-first-row bl-block-content-last-row span12" style="border-radius: 10px;"> <div class="bl-block-content-row-inner span12" style="padding: 50px 20px 18px;"><div class="bl-block-content-column bl-block-content-new-column span12"><div class="bl-padding-columns bl-content-wrapper span12"> <div class="bl-signup-container pull-left span12" at-form-width="12" style="border: 0px solid #191919; border-radius: 5px; padding: 8px 10px; background-color: transparent;"> <div class="bl-block-content-item bl-block-content-item-signupfieldpage bl-content-item-unremovable fields-left" style="text-align: center; margin-bottom: 14px;" data-is-auto-fill="true"><input type="text" maxlength="50" class="signup-field span12 input-ltr first-input" readonly="readonly" data-field-type="email" data-field-source="Email" data-mandatory="true" placeholder="Email " data-field-validation-msg="This is not a valid email" style="font-size: 12px; margin-bottom: 14px; height: 30px; line-height: 12px; font-family: arial, helvetica, sans-serif; text-align: left;" data-custom-values="" data-input-type="text"><input type="text" maxlength="50" class="signup-field span12 input-ltr" readonly="readonly" data-field-type="text" data-field-source="Ext1" data-mandatory="false" placeholder="Full Name" data-field-validation-msg="This is not a valid full name" style="font-size: 12px; margin-bottom: 14px; height: 30px; line-height: 12px; font-family: arial, helvetica, sans-serif; text-align: left;" data-custom-values="" data-input-type="text"><div class="confirm-emails" data-field-validation-msg="Please approve in order to receive our emails" style="font-family: arial, helvetica, sans-serif;"> <div class="checkbox ltr"> <label style="cursor: auto;"> <input type="checkbox" disabled="disabled" style="text-align: left;"><label class="confirm-label dir-label" style="font-family: arial, helvetica, sans-serif; text-align: left; cursor: auto; font-size: 11px; color: #000000;">I approve receiving emails</label></label></div> </div></div> <div class="bl-padding-columns bl-content-wrapper-columns" style="text-align: center;"> <div class="bl-block-button-content-wrapper" style="display: block; border-radius: 5px; background-color: #4ea3a3;"> <div class="bl-block-button-content-item-wrapper" style="font-size: 16px; padding: 9px;"> <div class="bl-block-content-item bl-block-content-item-button bl-content-item-unremovable" style="min-width: 1px; min-height: 16px; display: block; text-align: center; text-decoration: none;"><span style="font-size:14px;"><strong><span style="color:#FFFFFF;"><span style="font-family:arial,helvetica,sans-serif;">Sign Up Now</span></span></strong></span></div> </div> </div> </div> </div> </div></div></div> </div> </div> </div> </div></div> </div> <!-- END ZONES CONTAINER --> </div> <!-- END TEMPLATE CONTAINER --> </div> <!-- END TEMPLATE WRAPPER --> </div> <!-- END TEMPLATE MARGIN --> </div> <!-- END TEMPLATE OUTER --></div></div>
<script type='text/javascript'>
(function () {
var _atpopq = window._atpopq || (window._atpopq = []);
window._atpopobj = {};
if (!_atpopq.loaded) {
var atpopjs = document.createElement('script');
atpopjs.type = 'text/javascript';
atpopjs.async = true;
atpopjs.src = '//cdn-media.web-view.net/popups/lib/v1/loader.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(atpopjs, s);
_atpopq.loaded = true;
}
_atpopq.push(['UserId', 'zzae3adduwau']);
_atpopq.push(['PopupId', 'z3zdad']);
_atpopq.push(['IsraelCode', '104']);
_atpopq.push(['CountryCode', '226']);
_atpopq.push(['IsEmbed', true]);
_atpopq.push(['IgnoreMainCss', true]);
_atpopq.push(['OnEventCallback', 'handleATPopupEvent']);
})();
</script>
<script type="text/javascript">
//Sample event handler function
function handleATPopupEvent(ev,args){
switch(ev){
case 'display':
//Do this when the popup is displayed
break;
case 'close':
//Do this when the popup gets closed by the user
break;
case 'submit':
//Do this when popup gets submitted and the user doesn't get redirected to a URL
break;
}
}
</script>
<!-- AT Popup Beta END -->
As I understand this part of code, you should just place the code line:
window.top.location.href = "http://www.yourthankyoupage.com";
in case of 'submit'.

Drop-down list closes at unwanted time

I want to create search-input with drop-down list. The list must close when i have focused or clicked anywhere except search-input.
I added listClose() to "blur"-Listener. But now I can`t catch click-event from drop-down elements. Which is the event-listener I really need? Or I need the another realization?
Please, run snippet below. I tried to write it the most clear.
document.addEventListener("DOMContentLoaded", function() {
var inputElement = document.getElementById("input_word-search");
var listElement = document.getElementById("dd-menu_search-input");
// Input will focused when document is ready.
inputElement.focus();
listOpen = function() {
listElement.classList.add('dd-open');
};
listClose = function() {
listElement.classList.remove('dd-open');
};
inputElement.addEventListener("focus", function(e) {
listOpen();
});
inputElement.addEventListener("blur", function(e) {
listClose();
});
})
.dd-menu {
padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
position: absolute;
display: none;
}
.dd-suggestion {
cursor: pointer;
text-align: left;
padding: 3px 20px;
line-height: 24px;
}
.dd-suggestion:hover {
color: #fff;
background-color: #697981;
}
.dd-open {
display: block;
}
.dd-empty {
display: none;
}
#dd-menu_search-input {
width: 74%;
}
<body>
<div id="input-group">
<input id="input_word-search" class="input_search suggest__field" type="search" autocomplete="off" name="q" placeholder="Seach">
<div id="dd-menu_search-input" class="dd-menu dd-open">
<div class="dd-dataset">
<div class="dd-suggestion" onclick="alert('Click!')">
suggestion-1
</div>
<div class="dd-suggestion" onclick="alert('Click!')">
suggestion-2
</div>
<div class="dd-suggestion" onclick="alert('Click!')">
suggestion-3
</div>
<div class="dd-suggestion" onclick="alert('Click!')">
suggestion-4
</div>
<div class="dd-suggestion" onclick="alert('Click!')">
suggestion-5
</div>
</div>
</div>
</div>
</body>
A solution (or may I say workaround) is to use onmousedown instead of onclick, so it will look like this (Note that I'm also removing the alert() and using a console.log() instead)
<body>
<div id="input-group">
<input id="input_word-search" class="input_search suggest__field" type="search" autocomplete="off" name="q" placeholder="Seach">
<div id="dd-menu_search-input" class="dd-menu dd-open">
<div class="dd-dataset">
<div class="dd-suggestion" onmousedown="console.log('Click!')">
suggestion-1
</div>
<div class="dd-suggestion" onmousedown="console.log('Click!')">
suggestion-2
</div>
<div class="dd-suggestion" onmousedown="console.log('Click!')">
suggestion-3
</div>
<div class="dd-suggestion" onmousedown="console.log('Click!')">
suggestion-4
</div>
<div class="dd-suggestion" onmousedown="console.log('Click!')">
suggestion-5
</div>
</div>
</div>
</div>
</body>
The reason is when you focusout the textbox, it call blur function and the list immediately disapear. So you can't click on the list. You can walkaround by setTimeout to listClose() like this
listClose = function() {
setTimeout(()=>{
listElement.classList.remove('dd-open');
},100)
};
I added boolean-variable that indicates mousedown-event on drop-down list
var mousedownOnNodeCalee = false;
listElement.addEventListener("mousedown", function (e) {
mousedownOnNodeCalee = true;
});
inputElement.addEventListener("blur", function (e) {
if(!mousedownOnNodeCalee) {
listClose();
return;
}
inputElement.focus();
mousedownOnNodeCalee = false;
});

Display image using Jquery "find"

I am trying to display an image using jquery.I have a function which has ID & PATH as a parameter.The ID indicates the section(Each section is a html page which gets loaded on user action),Also there is a text area where I am displaying the text file content.Now in a same way i want to display image ,I tried different methods but it didn't work out.Below is my Java Script file & HTML file
HTML File:
<html>
<body>
<div id="tab1" name="tab" style="cursor: pointer; cursor: hand; width:90px;float: left;height: 22px ; margin-top: 0px;
background-color:lightgrey;font-size: 13px;text-align: center;border-bottom: none;display: table-cell;" onClick="tabs(1)">
<div style="margin-top: 3px" >TAB1</div>
</div>
<div id="tab2" name="tab" style="cursor: pointer; cursor: hand; width:90px;background-color:lightgrey;float: left;height: 20px; margin-top: 2px; font-size: 12px;text-align: center" onClick="tabs(2)">
<div style="margin-top: 3px">TAB2</div>
</div>
<div style="width:auto;height: 22px; border-bottom-color: white;border-bottom-style: solid;border-bottom-width: 1px"></div>
<div name="tab_content" style="display: block; margin-left:20px;" >
<br></br>
<br></br>
<div id="legendReport">
Notes 1:
</div>
<textarea name="textArea1" rows="4" value="" cols="50"></textarea>
<br></br>
<br></br>
<div id="legendRough">
Notes 2:
</div>
<textarea id="roughNotes_textArea" name="textArea2" rows="4" cols="50"></textarea>
</div>
<div name="tab_content" class="tab_content" style="display: none;margin-left:20px;">
<br></br>
<br></br>
<textarea name="textArea3" rows="4" cols="50" ></textarea>
<br></br>
<br></br>
<textarea name="textArea4" rows="4" cols="50"></textarea>
<br></br>
<br></br>
<br></br>
<br></br>
<!-- Schematic of selected analysis Point -->
<img id="myImage" src="" style="width:304px;height:228px;"></img>
</div>
</body>
</html>
JavaScript File:
//Displays the file content in text area
function displayTextfileData(textFilePath,ID){
readTextFile(textFilePath);
alert(textFileContent);
var sectionDIV = "#section" + ID;
alert(sectionDIV)
$(sectionDIV).find("[name=textArea3]").val(textFileContent);
$(sectionDIV).find("[name=textArea4]").val(textFileContent);
}
//This function display the image
function displayImage(imageFilePath,ID){
var sectionDIV = "#section" + ID;
alert("displayImageforDropdown():"+imageFilePath);
//$(sectionDIV).find("myImage").src = imageFilePath;
$(sectionDIV).getElementById("myImage").src = imageFilePath;
//document.getElementById("myImage").src = imageFilePath
//alert("displayImageforDropdown(): Assigned result: "+(document.getElementByName("displayImage").src = imageFilePath));
}
Display text file content is working fine,But i want the same on Image
Replace
$(sectionDIV).getElementById("myImage").src = imageFilePath;
with
$(sectionDIV).find("img#myImage").attr("src", imageFilePath);;
Try the following
$(sectionDIV)[0].getElementById("myImage").attr("src", imageFilePath);
or
$(sectionDIV).find("#myImage").attr("src", imageFilePath);
Try
$(sectionDIV).find("#myImage").attr("src", imageFilePath);
Or if you want to use getElementById use $(sectionDIV)[0] to get the HTML DOM Object from the jQuery Object. Something like,
$(sectionDIV)[0].getElementById("myImage").src = imageFilePath;
You can set the 'src' attribute as following:
$(sectionDIV).find("#myImage").prop("src", imageFilePath);
function displayImage(imageFilePath, ID) {
var sectionDIV = "#section" + ID;
//Change this line.....
$("#myImage",$(sectionDIV))[0].src = imageFilePath;
}

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.

Categories

Resources