How can I display value of a div with a button click? - php

I am currently working with a wmd editor and jQuery-UI tabs. I have created an ajax/js function that will submit (when next button is clicked) the wmd-preview value and then php echo the result in tab 2. The problem is that I am not getting any results displayed. I am not looking for the textarea value but the div #wmd-preview value. How can I display the value of the div wmd-preview through my ajax/function?
JS
<script>
$(function () {
var $tabs = $('#tabs').tabs({
disabled: [0, 1],
select: function () {
$.ajax({
type: "POST",
url: "post_tabs.php",
data: {
"wmd": $("#wmd-preview").val(),
},
success: function (result) {
$("#tab-2").html(result);
}
});
}
});
$(".ui-tabs-panel").each(function (i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab').click(function () {
var currentTab = $('#tabs').tabs('option', 'selected');
if (
(
currentTab == 0 && /*(B)*/
$.trim($('#wmd-input').val()).length > 0
)
) {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
} else {
switch (currentTab) {
case 0:
alert('Please fill out all the required fields.', 'Alert Dialog');
break;
}
}
console.log("preventing default");
return false;
});
$('.prev-tab').click(function () {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
return false;
});
});
</script>
PHP
<?
if (isset($_POST['wmd'])){
$wmd = $_POST['wmd'];
echo ('<div id="text_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$wmd.'</span></div>');
}
?>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input" cols="92" rows="15" tabindex="6"></textarea>
<div id="wmd-preview"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>

PHP code should start with <?php , yours start with <? which is incorrect.
When you see PHP code presented as text - it should tell you it is not running, this is why you keep getting output like '.$wmd.''); } ?> instead of real PHP echo output.
The other comment still stands as well - you should either use $("#wmd-preview").html() or $("#wmd-input").val() but you cannot use val on divs, it does not work.
In this scenario $("#wmd-input").val() is the better choice just because this is the reason input fields exist - to get input.
Let me know if there are more questions I can help with.

Related

Suggestion box not showing for nearest input

I cannot seem to get my suggestion box to show for the nearest input after adding more inputs dynamically.
The below code is where I am currently, I can see the suggestion box for a new input and add to that new input but if I go back to edit the input data the suggestion box fails to show.
<div id="tester"></div>
<button id="add_test">ADD</button>
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$(".flavour-name-input").css("background","#FFF no-repeat 165px");
$(".suggestion-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
$('.flavhey input').closest('flavourInput input').next('.suggestion-box').show();
$('.flavhey input').next('.suggestion-box').html(data);
$(".suggestion-box").css("background","#FFF");
}
});
return false;
});
$(document).on("click",".search-flavour",function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li class="search-flavour"><b>'.$con['flavour_name'].'</b> - <i>'.$con['flavour_company_name'].'</i></li>';
}
$html .= '</ul>';
echo $html;
}
}
Ok short version:
Use var box = $(e.target).next(".suggestion-box"); to aquire a reference to the correct suggestion box in the success handler of the ajax request.
Long version:
I replaced the php parts with static placeholders to get a runnable example.
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e) {
var token = "[token]";
var search = $(this).val();
var box = $(e.target).next(".suggestion-box");
box.show();
box.html("TestData");
box.css("background", "#FFF");
return false;
});
$(document).on("click", ".search-flavour", function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester"></div>
<button id="add_test">ADD</button>
<ul>
<li class="search-flavour">
<b>flavour_name_1</b> - <i>flavour_company_name_1</i>
</li>
<li class="search-flavour">
<b>flavour_name_2</b> - <i>flavour_company_name_2</i>
</li>
<li class="search-flavour">
<b>flavour_name_3</b> - <i>flavour_company_name_3</i>
</li>
</ul>
Now being able to execute your code I was able to reproduce the described error. Please try to provide a runnable example next time.
I realized that your box was only appearing once because the call to .show() wasn't working at all. It was visible from the beginning just without any content so you couldn't see it, then after setting html() it had content and it looked like the call to show() worked as intended.
Afer you clicked on a .search-flavour all boxes were correctly hidden and thus never appeared again.
So to fix this, replace the success handler of the ajax request with this:
success: function(data){
// e.target is the currently active input element
var box = $(e.target).next(".suggestion-box");
box.show()
.html(data)
.css("background", "#FFF");
}

Javascript events - send values to database

I am having trouble sending data to the database. The values are being sent, but they are all going into the first drop zone field. And I need each dropzone value to go into the correct field in the database.
I've tried putting in different listeners & if statements in the javascript but it won't work for me.
the html:
<ul id="images">
<li><a id="img1" draggable="true"><img src="images/1.jpg"></a></li>
<li><a id="img2" draggable="true"><img src="images/2.jpg"></a></li>
<li><a id="img3" draggable="true"><img src="images/3.jpg"></a></li>
</ul>
//dropzones
<div class="drop_zones">
<div class="drop_zone" id="drop_zone1" droppable="true">
</div>
<div class="drop_zone" id="drop_zone2" droppable="true">
</div>
<div class="drop_zone" id="drop_zone3" droppable="true">
</div>
</div>
<button id = "post" onClick="postdb();">Post info</button>
the javascript:
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () {
return fn.call(el, window.event);
});
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
var dragItems;
updateDataTransfer();
var dropAreas = document.querySelectorAll('[droppable=true]');
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
function updateDataTransfer() {
dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
event.dataTransfer.setData('obj_id', this.id);
return false;
});
}
}
addEvent(dropAreas, 'dragover', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#000";
return false;
});
addEvent(dropAreas, 'dragleave', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#ccc";
return false;
});
addEvent(dropAreas, 'dragenter', cancel);
// drop event handler
addEvent(dropAreas, 'drop', function (event) {
if (event.preventDefault)
event.preventDefault();
// get dropped object
var iObj = event.dataTransfer.getData('obj_id');
var oldObj = document.getElementById(iObj);
// get its image src
var oldSrc = oldObj.childNodes[0].src;
oldObj.className += 'hidden';
var oldThis = this;
setTimeout(function () {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
function postdb(){
if (document.querySelectorAll('[droppable=true]')){
var dropDetails = oldThis.id + '=' + iObj;
$.post("a-2.php", dropDetails);
}
oldThis.style.borderColor = "#ccc";
}, 500);
return false;
});
and my php:
$sql="INSERT INTO table_answers (drop_zone1, drop_zone2, drop_zone3) VALUES ('$_POST[drop_zone1]','$_POST[drop_zone2]','$_POST[drop_zone3]')";
Any idea please?
var u = $('drop_zone1');
if(u){
$.post("post.php", y);
};
(I'm assuming this is jQuery.)
Add the # to the beginning of the selector: $('#drop_zone1');.
The jQuery resultset always evaluates to a truthy value. It's not clear to me what condition you're trying to validate here...
In the PHP code, you're creating the query in $sql2 in the first if, as opposed to $sql in the other two.
Edit - now that we know what you're trying to do in setTimeout, this simplified function should work:
setTimeout(function() {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
/*
this part has been removed, see edit below
var dropDetails = oldThis.id + '=' + iObj;
// now dropDetails should look something like "drop_zone1=img1"
$.post("post.php", dropDetails);
*/
oldThis.style.borderColor = "#ccc";
}, 500);
One more edit, to submit all the dropped elements at once:
function postdb() {
var postDetails = {};
var dropZones = document.querySelectorAll('[droppable=true]');
var allZonesDropped = true;
for(var ix = 0; ix < dropZones.length; ++ix) {
var zone = dropZones[ix];
var dropped = zone.querySelector('[draggable=true]');
if(dropped) {
var dropTag = dropped.id;
postDetails[zone.id] = dropTag;
} else {
allZonesDropped = false;
}
}
if(allZonesDropped) {
$.post("a-2.php", dropDetails);
} else {
alert('Not all targets have elements in them');
}
return false;
});
Just be careful where you place this function - your edited question has it in the middle of the setTimeout call, where it's definitely not going to work.
Regarding your PHP code: You should really learn about PDO or MySQLi and use prepared statements instead of blindly inserting user input into the query. If you care to learn, here is a quite good PDO-related tutorial.

Why is jQuery autocomplete updating all elements on my cloned form?

I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.

Google+ Button not appearing

Following is the code:-
<script type="text/javascript">
var timer = 150;
var currentWindow;
$(document).ready(function()
{
$("#creditme").button({
icons: { primary: "ui-icon-check" }
}).hide();
$("#viewad").button({
icons: { primary: "ui-icon-play" }
}).hide();
$("#progressbar").progressbar({value: 0}).hide();
var time;
var id;
var title;
var url;
$('.googlep-advertisement').bind('click', function()
{
id = $(this).attr('id');
title = $(this).text();
url = $('#yturl-'+id).text();
timer = $('#ytime-'+id).text();
$("#dialog-message").dialog({
modal: true,
width: 700,
title: title,
resizable: false,
draggable: false,
beforeClose: function() { clearAd(); }
});
if (!$("#progressbar").is(":visible") && !$("#creditme").is(":visible"))
{
$("#viewad").show();
}
});
$("#viewad").bind('click',function() {
$.get("googlep_credit.php" + '?start=' + id);
$("#viewad").hide();
$("#progressbar").progressbar('value', 0).show();
currentWindow = window.open(url, 'videoad', 'height=480,width=640', false);
window.blur();
window.focus();
progresscount(timer);
});
$("#creditme").click(function() {
$.get("googlep_credit.php" + '?id=' + id);
$("#creditme").hide();
$("#dialog-message").dialog('close');
$("#"+id).parent().parent('tr').fadeOut('slow');
});
function progresscount(time)
{
if(time == 0)
{
if(isWindowClosed() == true)
{
alert('You closed the popup before timer reached zero or you are using popup-blocking software.');
$("#dialog-message").dialog('close');
}
else
{
$("#creditme").html('<g:plusone callback="plusone_vote" href="'+url'"></g:plusone>');
$("#creditme").show();
}
$("#progressbar").hide();
}
else
{
time--;
$("#progressbar").progressbar('value', parseInt((timer - time) * 100 / timer));
setTimeout(function() { progresscount(time) }, 100);
}
}
});
function isWindowClosed()
{
if (!currentWindow || typeof currentWindow == 'undefined' || currentWindow && currentWindow.closed)
{
return true;
}
else
{
return false;
}
}
function clearAd()
{
}
</script>
<style>
.dialog-message {
}
</style>
<div id="dialog-message" class="dialog-message" title="View Video" style="display:none">
<p>
<center>
<button id="viewad" style="ui-helper-hidden">Click here to view the video</button>
<div id="progressbar"></div>
<button id="creditme" style="ui-helper-hidden">Test</button>
</center>
</p>
</div>
Nothing wrong with the code.
The problem is:-
http://dl.dropbox.com/u/14384295/70.jpeg
When checked with google chrome inspect element,
The code appears as
http://dl.dropbox.com/u/14384295/71.jpeg
Correctly working will appear as > http://dl.dropbox.com/u/14384295/72.jpeg
It seems that the code is not being converted by the google js which is in the portion. I am sorry if i have been confusing.
I may probably be doing the addition of 'url' var incorrectly
I'm pretty sure your problem lies in this line:
$("#creditme").html('<g:plusone callback="plusone_vote"></g:plusone>');
You are dynamically adding the <g:plusone> element after the Google +1 script has been run, so nothing happens.
To solve it, simply put the +1 markup in the html from the beginning so the +1 script can find it and render it, and only call $("#creditme").show(); when you need to show it.
<button id="creditme" style="ui-helper-hidden">
<g:plusone callback="plusone_vote"></g:plusone>
</button>
If you want to dynamically change the URL after page load, check out the examples from the Google documentation. It will allow you to load the button explicitly.

Jquery tabify with form (Multiple Instances problem ?)

I'm using jquery tabify with 4 tabs and each content same form calling via ajax.(assume form.php)
1st tab everything works fine with the form.
2nd,3rd and 4th tab failed to get input type="text" value
tabify field with (4 tabs here actually I make it short as the code is long):
$(document).ready(function () {
$('#general_information_tab').tabify();
});
function recp(refer,id,plan){
if(plan == 0)
{
$('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&T_REFERID=' + refer );
}else{
$('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&T_ID=' + refer);
}
<div id="general_tab_content">
<ul id="general_information_tab" class="general_information_tab">
<li class="active"><a href="#one" onClick="recp('1','<?php echo $plan_id; ?>','0')" >Immediate Response Steps</a></li>
<div id="one" class="content_gi">
<div class="stg1">
<img src="images/task/add.ico" height="10px" width="10px" /> Add Task
<div class="stgcontent">
<script type="text/javascript">
recp('1','<?php echo $plan_id; ?>','0');
</script>
</div>
</div>
</div>
in new_taskstg.php
$(function(){
$(".newTaskSubmitBtn").click(function(){
var T_CONTENT = $(".task_name").val();
var T_REFERID = $(".refer").val();
var SAVE_PLAN = $(".plan").val();
var V_ID = $(".vendor").val();
var dataString='T_CONTENT=' + T_CONTENT + '&T_REFERID=' + T_REFERID + '&SAVE_PLAN=' + SAVE_PLAN + '&V_ID=' + V_ID;
alert(T_CONTENT + T_REFERID + SAVE_PLAN + V_ID);
if(T_CONTENT=='' || T_REFERID=='' || SAVE_PLAN=='' || V_ID=='')
{
//ERROR MESSAGE
$(".fail").show();
$(".success").hide();
}
else
{
$.ajax({
type: "POST",
url: "stage/insert.php",
data: dataString,
success: function(data){
//SUCCESS MESSAGE
$(".success").show();
$(".fail").hide();
}
});
}
return false;
});
});
form field code:
<input type="text" name="task_name" class="form_input task_name" />
TEST I DID :
As above var T_CONTENT = $(".task_name").val(); and prompt like this alert(T_CONTENT); what it shows on 1st tab it able to capture it while the 2nd 3rd and 4th tab failed...
Was suspecting multiple instances problem...
Problem Solved. Mian point is to avoid from multiple instances since tabify couldn't differentiate which tab the form is and it takes 4 tabs together. So to solve my case I just use unique id in 4 forms.

Categories