JQuery select in dialog does not have options appended - php

I am trying to use a JQuery dialog to act similar to an open file dialog, but instead of files I am using records from a database to populate the dialog.
The problem that I am having is that I cannot seem to get the html option data loaded into the html select in my dialog. I have used the Google Javascript debugger in Chrome and have stepped through my javascript code which is called from my PHP ajax. I see no errors and I see the data is there and formatted correctly when I put it into the append statement. I don't understand why it does not show up in my html select.
Thanks for your help.
below is my Ajax function which receives the data.
function doOpenAjax(filterStr)
{
$.get(
"contenteditServerAjax.php",
{filter: filterStr },
function(data) {
var optsArr = data.split('|~|');
var seloption = "";
$.each(optsArr, function(i) {
seloption += '<option value="' + optsArr[i] + '">' + optsArr[i] + '</option>';
});
$('#chooseArticleName2').find('option').remove().end();
$('#chooseArticleName2').append(seloption);
},
"html"
);
}
For reference this is part of my php which contains the jquery dialog:
<head>
<script>
$(document).ready(function() {
var dlg = $("#opendiv").dialog({modal:true, height:550, width:650,
hide:{ effect: 'drop', direction: "down" },
autoOpen:false,
maxHeight: 1200,
maxWidth: 1200,
minHeight: 250,
minWidth: 300,
buttons: { "Open": function() { $('#state').val('Open Doc'); $('#contentform').submit(); $(this).dialog("hide"); },
"Cancel": function() { $(this).dialog("close");}}
});
dlg.parent().appendTo($("#contentform"));
});
</script>
<div id="opendiv" name="opendiv" title="OPEN">
<p align="center">Enter Name to Open Article as:</p>
<p>
Filter:
<input name="docFilter2" id="docFilter2" type="text" value="$filter2" maxlen="64" size="28"/>
<input name="LoadTitles2" id="LoadTitles2" type="button" value="Load Available Titles"
onclick="doOpenAjax( $('#docFilter2').val() );"/>
</p>
<p>
<div id="ajaxOutput2">
<select name="chooseArticleName2" id="list2" size="8" style="min-width:92%"
onchange="
var mytext = $('#chooseArticleName2 :selected').text();
$('#textBoxArticleName2').val(mytext);">
</select>
</div>
</p>
<p>
Document:
<input type="text" id="textBoxArticleName2" name="textBoxArticleName2" size="56"/>
</p>
</div>

Just FYI, it would be more efficient to do this:
$('#chooseArticleName2').empty().html(seloption);
Than this:
$('#chooseArticleName2').find('option').remove().end();
$('#chooseArticleName2').append(seloption);

Related

Set value in select2 option by data from database

I want to make edit from. In this form contain input form control using select2 option. This select2 option input form can't display selected data that return from the database. I want to make the select2 option can be change too. I've tried this but still can display the selected data. Thank You :)
Here's my view
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<?php echo form_open('company2/do_update') ?>
<form>
<select id="Name" class="searching form-control" style="width:500px" name="company"></select>
<button type="submit" class="btn btn-info waves-effect waves-light">Save</button>
<?php echo form_close(); ?>
</form>
</body>
<script type="text/javascript">
$('.searching').select2({
placeholder: 'Masukkan Nama Company',
ajax:{
url: "<?php echo base_url('company2/select2'); ?>",
dataType: "json",
delay: 250,
processResults: function (param) {
return {
compClue: param.term,
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.Name,
text: item.Name,
value:item.Name
});
});
return{
results: results,
cache: true,
};
}
}
});
var response = {};
response.val = "<?php echo $row['Name'];?>";
$("#searching option[value='" + response.val +"']").attr("selected","selected");
I would just output the content you want for the select to a div using PHP and then get the div content and append somewhere using javascript if needed.
<div id="selectOptions">
<?php
foreach($option as $row){
$optionVal = $row->optionVal;
$optionLabel = $row->optionLabel;
echo "<option value='$optionVal'>$optionLabel</option>";
}
?>
</div>
Since you are already using jQuery you can then get the content of the div using:
var options = $('#selectOptions').html();

Jquery.Ajax not posting to PHP. Php returns nothing for $_POST[]

So I've got this small draggable item that I am able to drag and drop in the canvas I've created and that is working perfectly fine, however as I want to save the position of the draggable item when the item is dropped, I am using ajax to post to PHP where PHP will then store it in sessions.
However it is simply not posting. No error shows. The $_POST[] simply returns nothing.
Notice I have set value of the ajax data to 1. I am hardcoding atm for testing purpose.
page-online-tool.php
<div id="Canvas" class="col-xs-6">
<div class="col-xs-11" id="Purse_Background"></div>
<div class="col-xs-1">
<div id="FLOWER_Blue" class="draggable ui-widget-content">
<img src="imgs/blue_01.png" alt=""/>
</div>
<p id="pos_T" ></p>
<p id="pos_R" ></p>
<p id="pos_B" ></p>
<p id="pos_L" ></p>
<input type="text" id="id_input_01" name="name_input_01" value=""/>
<?php
if(isset($_POST['Blue_Top_Position'])) {
$Blue_Top_Position = $_POST['Blue_Top_Position'];
echo $Blue_Top_Position;
} else {
echo 'fail';
}
?>
</div>
</div>
<?php include 'footer.php'; ?>
JQUERY.JS
$(document).ready(function () {
$('#FLOWER_Blue').draggable({
containment: "#Canvas",
scroll: false,
drag: function(event, ui){
$BLUE_T = ui.position.top;
$BLUE_R = ui.position.right;
$BLUE_B = ui.position.bottom;
$BLUE_L = ui.position.left;
$('#pos_T').text('TOP: ' + $BLUE_T);
$('#pos_R').text('RIGHT: ' + $BLUE_R);
$('#pos_B').text('BOTTOM: ' + $BLUE_B);
$('#pos_L').text('LEFT: ' + $BLUE_L);
$('#id_input_01').val(ui.position.top)
},
stop: function(event, ui){
$.ajax({
url:'http://localhost/42_TEST/page-online-tool.php',
type: 'post',
data: {Blue_Top_Position : 1},
done: function(data) {
console.log('done');
}
}).fail (function() {
alert('error');
})
}
}
);
});

Database data in jquery dialog

Ok, i tried it with jquery ajax to achieve the same. But now the system always shows the first id. It doesn't matter at which edit_subscriber image i click. This is what i did:
Jquery code:
jQuery(".edit_subscriber").click( function() {
jQuery('.dialog-modal').dialog({
modal: true,
open: function ()
{
jQuery.ajax({
async: false,
type: 'get',
url: nieuwsbrief.editsubscriber,
data: 'ajax=&subscriber_id=' + jQuery('.edit_subscriber').prop('id'),
success: function(data) {
jQuery('.dialog-modal').html(data);
}
});
},
close: function ()
{
},
height: 400,
width: 600,
title: 'Ajax Page'
});
return false;
});
html code:
echo '<div class="dialog-modal" title="Basic modal dialog" style="display: none;"></div>';
edit_subcriber.php:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/www/wordpress/wp-config.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/www/wordpress/wp-load.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/www/wordpress/wp-includes/wp-db.php';
global $wpdb;
echo $_GET['subscriber_id'];
?>
The issue with the script is, you are using same id for all dialog-models, and when you are clicking on the edit_subscriber, it is picking the dialog form the id, and as you are picking form id, it will always get the first element with the id.
Multiple element with same id is not valid.
So you can try this.
Just replace this code
echo '<div id="dialog-modal" title="Basic modal dialog" style="display: none;">
Naam: <input type = "text" name = "subscriber_name" id = "'.$abonnee->subscriber_id.'" value = "'.$abonnee->subscriber_name.'"> <br />
</div>';
with this
echo '<div class="dialog-modal" title="Basic modal dialog" style="display: none;">
Naam: <input type = "text" name = "subscriber_name" id = "'.$abonnee->subscriber_id.'" value = "'.$abonnee->subscriber_name.'"> <br />
</div>';
and change js function to :
jQuery(".edit_subscriber").click( function() {
$(this).closest('tr').next().dialog({
modal: true,
open: function (){},
close: function (){},
height: 400,
width: 600,
title: 'Ajax Page'
});
});
As you are placing div after tr which is also not valid markup.

jQueryUI Dialog with ajax-injected html selector

All code below is a stand-alone working example (greatly simplified) of what I am trying to do. If anyone copy/pastes the below code blocks into 3 separate files, the code is fully self-contained-- just remember to reference/include test5.js and the jquery libraries in script tags at top of document.
SUMMARY: HTML div injected via Ajax not opening in the jQuery UI dialog widget.
Objective: On document load, jquery-ajax injects an html form (ultimately, it will retrieve appropriate form values from DB which is the reason for ajax). A div with id="clickme" is injected with the html. Clicking the div should open the dialog.
Problem: The jQueryUI .dialog does not appear. I put an alert box inside the click event, and that fires. But the dialog remains elusive.
Therefore, problem appears to be the fact that the HTML is injected. What am I missing?
HTML: index.php
<div id="putit_here">
</div>
JAVASCRIPT/JQUERY: test5.js
$(function() {
var pih = $('#putit_here');
$.ajax({
type: "POST",
url: "ajax/ax_test5.php",
data: 'contact_id=1',
success:function(data){
pih.html(data);
var etc1 = $( "#editThisContact_1" );
/* *****************************************************************
Moving Dialog up >here< was correct answer.
********************************************************************
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
****************************************************************** */
}
}); //End ajax
/* **** This is where I had it previously ***** */
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
$(document).on('click', '#clickme', function(event) {
alert('HereIAm...');
$( "#editThisContact_1" ).dialog( "open" );
}); //End #clickme.click
}); //End document.ready
AJAX - ax_test5.php
$rrow = array();
$rrow['contact_id'] = 1;
$rrow['first_name'] = 'Peter';
$rrow['last_name'] = 'Rabbit';
$rrow['email1'] = 'peter.rabbit#thewarren.nimh.com';
$rrow['cell_phone'] = '+1.250.555.1212';
$r = '
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<p class="instructions">Edit contact information for <span class="editname"></span>.</p>
<form name="editForm" onsubmit="return false;">
<fieldset>
<span style="position:relative;left:-95px;">First Name:</span><span style="position:relative;left:10px;">Last Name:</span><br />
<input type="text" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'" name="fn_'.$rrow['contact_id'].'">
<input type="text" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'" name="ln_'.$rrow['contact_id'].'"><br /><br />
<span style="position:relative;left:-120px;">Email:</span><span style="position:relative;left:30px;">Cell Phone:</span><br />
<input type="text" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'" name="em_'.$rrow['contact_id'].'">
<input type="text" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'" name="cp_'.$rrow['contact_id'].'">
</fieldset>
</form>
</div>
';
echo $r;
EDIT:
Updated question to move dialog definition inside AJAX success callback. Did not completely solve problem, though. The dialog now appears if I change the autoOpen flag to true, but that is not how the script must work. The dialog still does not open upon clicking the (injected) #clickme div.
EDIT 2:
My bad. At first I thought it didn't work, but then found that my live test and posted SO question varied in one line: how the .dialog("open") was being called. In live code, it was still using the var: etc1.dialog("open") -- but in post above the selector was fully referenced: $('#editThisContact_1').dialog("open"). The posted syntax was correct. Thanks gents, and also itachi who got me to check chrome console.
You are trying to initialize a dialog on an element before the element exists. You need to initialize the dialog on "#editThisContact_1" after your ajax call comes back successfully.
Like this:
....
success:function(data){
pih.html(data);
//now your DIV is actually there so init the dialog
var etc1 = $( "#editThisContact_1" );
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
}

jquery cant get value of text box

i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.

Categories