jQuery post from php variable - php

I'm in the process of creating a 'drag-and-drop' ordering list, and I grabbed some code for an existing one and I need to modify it to fit my needs. However I do not fully understand exactly what the code is doing in order to modify it correctly.
Basically I have a php variable '$draft_id' that I need to pass into my updateList.php. If I just define $draft_id=0 within updateList.php it works fine, but I need to be able to pass this value in.
The code looks like:
(index.php)
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
...
<?php
include("connect.php");
$draft_id='0';
$query = "SELECT id, text FROM sort WHERE draft_id =" . $draft_id . " ORDER BY listorder ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$id = stripslashes($row['id']);
$text = stripslashes($row['text']);
echo "<li id='arrayorder_" . $id . "'>" . $text;
echo "<div class='clear'></div>";
echo "</li>";
}
?>
(updateList.php)
<?php
include("connect.php");
$array = $_POST['arrayorder'];
if ($_POST['update'] == "update"){
$count = 1;
//------------------------------------
$draft_id=$_POST['draft_id'];
//------------------------------------
foreach ($array as $idval) {
$query = "UPDATE sort SET listorder = " . $count . " WHERE id = " . $idval . " AND draft_id=" . $draft_id;
mysql_query($query) or die('Error, insert query failed');
$count ++;
}
echo 'Draft Order Saved!';
}
?>
So basically in the 'updateList.php' I'd like 'draft_id' to be taken from the $_POST array, but I'm not sure how to pass it correctly. Any help would be appreciated.

After some research I've figured out how pass this how it needs to be passed, so I figured I'd share in case anyone else needs it in the future. So my main issue was that I did not understand exactly how the $_POST array was being set.
In the Javascript there is a $.post that is using a variable 'order' which is defined above it. This is where the $_POST array is being passed. So by adding an additional condition you can pass additional variables in the $_POST array.
So I changed:
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
to:
<?php //this will later be pulled from another page, but for now
$draft_id='0'; //I just set it up for testing purposes.
$_POST['draft_id']=$draft_id;
?>
<script type="text/javascript">
$(document).ready(function(){
function slideout(){
setTimeout(function(){
$("#response").slideUp("slow", function () {});
}, 2000);}
$("#response").hide();
$(function() {
$("#list ul").sortable({ opacity: 0.8, cursor: 'move', update:function() {
//we will add &draft_id='the php variable $draft_id to the order variable'
var order = $(this).sortable("serialize") + '&update=update' + '&draft_id=<?php echo $draft_id; ?>';
$.post("updateList.php", order, function(theResponse){
$("#response").html(theResponse);
$("#response").slideDown('slow');
slideout();
});
}
});
});
});
</script>
This fixed my issue, hopefully this can help someone out in the future if they run into this same issue.

Related

JQuery ignoring click() and change()

Advance note: I have already looked at and looked at and tried the solutions in the SO question: Jquery checkbox change and click event. Others on SO deal more with reading the values rather than the issue that the event is not firing.
I will admit that I am a relative newbie to JQuery.
I am trying to make two changes. One when a text field changes and one when a checkbox is toggled. Both are within a form. The idea is that if the text field changes a computation is done and the return value is written into the text after the checkbox. The checkbox toggles that text on and off.
Once finished the form can be submitted.
the code (as seen below) also uses php.
I've pulled the relevant code. I read several examples on line so there is are attempts using
<span id="foo"><input></span>
<input class='romanCheck' id='romanCheck' type='checkbox'>
Neither alert is being called. JSFiddle kinda barfed on the PHP. For the checkbox I've tried both .change() and .click()
The browsers I've tested on are all Mac (my dev environ)
Safari: 7.0.3 (9537.75.14)
Chrome: 33.0.1750.152
Firefox: 28.0
I've attached the relevant code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Not Working.php</title>
<link rel="stylesheet" href="jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css">
<script src="jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<script>
function romanize (num) {
return "(" + "roman for " + ")";
}
$(document).ready(function(){
$(".romanCheck").live("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$("span.iterationField input").live("change",function() {
alert("#iteration.change has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
</script>
<form action='EventValidateProcess.php' method='post'>
<?php
$doesShow = 1;
$isRoman = 1;
$iteration - 13;
print "<table>\n";
print "<tr>\n\t<td>Iteration</td>\n\t";
print "<td><span id='iterationField'><input type='text' name='iteration' value='" . $iteration . "'></span></td>\n\t";
print "<td><input type='checkbox' name='doesShow' value='1'";
if ($doesShow == 1) {
print " checked";
}
print "> visible | ";
print "\n<input class='romanCheck' id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print "> uses Roman numerals\n";
print "<span id='romanDisplay'>(XX)</span></td>\n</tr>\n";
?>
</table>
<button type='submit' name='process' value='update'>Update</button><br/>
</form>
</body>
.live() deprecated: 1.7, removed: 1.9
Use .on() as you are using jquery-1.10.2
Syntax
$( elements ).on( events, selector, data, handler );
$(document).on("change", "span.iterationField input" ,function() { //code here });
$(document).on("change", ".romanCheck" ,function() { //code here });
span.iterationField is not exist, instead span#iterationField,
and just use:
$(document).ready(function(){
$("input.romanCheck").on("change",function() {
alert("#romanCheck.click has been hit");
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $(this).val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
});
Note: make sure jquery library in imported
After a lot of finessing it seemed the answer that worked best was the following:
$(document).change("input.romanCheck", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
$(document).change("input.iterationField", function() {
var romanValue = "";
var roman = $("#romanCheck").is(':checked');
if ( roman ) {
var itValue = $("#iterationField").val();
romanValue="(" + romanize(itValue) +")";
}
$("#romanDisplay").text(romanValue);
});
Using:
print
"<input id='iterationField' type='text' name='iteration' value='";
print $iteration . "'/>";
print
"<input id='romanCheck' type='checkbox' name='isRoman' value='1'";
if ($isRoman == 1) {
print " checked";
}
print ">";
print "<span id='romanDisplay'>";
if ($isRoman == 1) {
print "(" . $romanIteration . ")";
}
print "</span>";
Im not sure what is your problem but try this.
function romanclick(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//your code romanclick
$('span.iterationField input').click(function(){
textchange();// call it again
});
}
function textchange(){
//if event fire twice use namespace at 1. and 2. and put $(document).off('namespace') here
//change text code
$('.romancheck').click(function(){
romanclick();// call it again
});
} ;
1.$(document).on("change", "span.iterationField input" ,function() { //call your function here });
2.$(document).on("change", ".romanCheck" ,function() { //call your function here });

jquery autocomplete with php foreach generated results

I have been trying for days to get jquery autocomplete to work the way I need it to.
so far I have this which works fine:
<script>
$(function() {
var availableTags = [<?php
$taglist = Array();
foreach ($users as $user)
if ($user->getAttribute('first_name') == ''){
$taglist[] = '"'.$user->getUserName().'"';
}else{
$taglist[] = '"'.$user->getAttribute('first_name').' '.$user->getAttribute('last_name').'"';
}
echo join(',', $taglist);
?>];
$("#searchmem").autocomplete({
source: availableTags,
minLength: 2,
select: function(event, ui) {
$("#searchmem").val(ui.item.label);
$("#submit").click();
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='/files/avatars/1.jpg' />" + item.label + "</a>")
.appendTo(ul);
}
});
</script>
This will output the image /files/avatars/1.jpg next to the respective users username or full name.
The problem I'm having is trying to output the right users avatar. Each .jpg file corresponds with the username so I could have used $user->getUserID() in the src but this won't work because it's not inside the foreach $users as $user loop.
I have tried putting the whole autocomplete script inside the foreach which when tested did alert the right thing but autocomplete wouldn't work.
I have also tried creating two variables such as
availableTags1 = { label: .... $user->getUserName() etc... }
availableTags2 = { avatar: .... $user->getUserID() etc... }
availableTags = availableTags1 + availableTags2;
and
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src=' + item.avatar + ' />" + item.label + "</a>")
.appendTo(ul);
}
But again this didn't work. I'm completely lost! How can I get it to output the image alongside the relevant username? Help would be much appreciated.
In your case, you have to build an array like :
var availableTags = [
{label: '...', avatar: '...'},
{label: '...', avatar: '...'},
...
];
And use:
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.label + "</a>") // Note the additional double quotes
.appendTo(ul);
}
(see this example on jQuery UI for using custom data)
Then, for generating you array via PHP, you should use:
<?php
$taglist = Array();
foreach ($users as $user) {
$data = array();
if ($user->getAttribute('first_name') == ''){
$data["label"] = $user->getUserName();
} else {
$data["label"] = $user->getAttribute('first_name').' '.$user->getAttribute('last_name');
}
$data["avatar"] = $user->getUserID();
$taglist[] = $data;
}
?>
var availableTags = <?php echo json_encode($taglist); ?>;

php jquery selecting the specific checkbox inside the while fetch_array

I have a problem selecting specific checkbox and putting higlight css for its div inside the mysql_fetch_array
here's my code
$count=1;
$query = mysql_query('SELECT * FROM thread');
while($row = mysql_fetch_array($query))
{
echo "<div class='row".$count."'><input type='checkebox' class='chk_box".$count."'> ".$row['title']."</div>";
$count++;
}
<script>
var count= "<?php echo $count?>";
for(var y=1;y<=count;y++){
$('.chk_box'+y).click(function() {
if(this.checked) {
$('.row'+y).addClass('backcolor');
}
else{
$('.row'+y).removeClass('backcolor');
}
});
}
</script>
Fixed som typos, added a DOM ready function, and changed the jQuery a bit, try that ?
$count=1;
$query = mysql_query('SELECT * FROM thread');
while($row = mysql_fetch_array($query)) {
echo "<div class='row".$count."'><input type='checkbox' class='chk_box".$count."'> ".$row['title']."</div>";
$count++;
}
<script type="text/javascript">
$(function() {
$('[class^="chk_box"]').on('click', function() {
$(this).closest('div').toggleClass('backcolor', this.checked);
});
});
</script>​​​​​​​​​​
as a sidenote, attaching event handlers inside for loops is usually not a very good idea.

Different Jquery hover popup divs on different links

I've a php for loop which finds data from an Json object, and creates based on these information different divs and different links:
echo $remoteTownFB . " - " .
"<a href=\"#\" id=" . $remoteTownFB . "_trigger>" .$eventName . "</a></br>";
After that, I wrote a Java Script to create different divs (with different names) wich should pop up on mouseover (with a Jquery Script)
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
document.getElementById('pop-up').appendChild(samplediv);
document.getElementById('pop-up').appendChild(txt);
</script>
My problem is now the Jquery Script. I tried around with $.each on an Array where every Town name is in, but I couldn't figure it out.
This is my base:
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#pop-up').show().;
}, function() {
$('div#pop-up').hide();
}
);
$('a#trigger').mousemove(function(e) {
$("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
Any help or ideas?
First of you forgot to close the id-property:
echo $remoteTownFB . " - " .
"" .$eventName . "</br>";
Then, for the pop-up to work you could try:
<script type="text/javascript">
var samplediv = document.createElement('div');
samplediv.id = '<?php echo $remoteTownFB . "_info" ?>';
samplediv.style.display = 'none';
var txt = document.createTextNode("Informationen über: <?php echo $eventName?>");
samplediv.appendChild(txt);
document.getElementById('pop-up').appendChild(samplediv);
</script>
The jquery part would be:
<script type="text/javascript">
$(function() {
$('a[id$="_trigger"]').hover(
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).show();
},
function() {
var targetSelector = '#' + this.getAttribute('id').replace('_trigger', '_info');
$('#pop-up, ' + targetSelector).hide();
}
);
});
</script>
I'm not really sure what you are trying to do with the mousemove call so I left that alone.

Correct syntax to get my Ajax function to work

The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>

Categories