PHP Javascript Variable problem - php

I have a while loop in my PHP page where I look the following...
print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id='vote_$row->id' class='getPoint'>Get " .$row->coff. "<input type='hidden' value='$row->coff' id='credoff'/> credit(s)</a><br /></div>$clearDiv</div></div>";
I have a value set in my hidden field which I then call in my javascript...
{
var theid = $(this).attr("id");
var onlyID = theid.split("_");
var onlyID = onlyID[1];
credoff = $("#credoff").val();
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: function(data) {
if(data != "success1" && data != "success5") {
$("#" + theid).text(data);
}else{
$("#thediv_" + onlyID).fadeOut("slow");
$('#creditsBalance').fadeOut("slow");
newbalance = parseInt($('#creditsBalance').text());
if(data != "success5") {
alert('Credits offered = '+credoff);
The only thing is in my javascript its grabbing the highest 'credoff' variable value on the page, not the one clicked on, does this make sense?

First off, $('#credoff') is an id... and IDs are unique to a page. Secondly, if there were more than one (and built properly through a CSS selector), the way you're calling $('#credoff') would only give you the value of the first one, since you're not associating it with the event target.
Since it looks structurally like the input is a child of the (which is odd, too, btw), you'll need to use a selector like this to get credOff:
$('.getPoint').click(function(){
// properly associated with the event target.
var credOff = $(this).find('input').val();
// etc.
}

Element IDs must be unique throughout the page; if they are not, then attempting to select by ID is undefined. Your best bet is to use something like this:
<input type="hidden" ... class="credoff" />
And then in the javascript something like this:
credoff = $(this).children('input.credoff:hidden').val()

Related

how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?

I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?
From the code below the data gets entered like this: DATA1|DATA2|DATA3|
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + "|";
}
});
Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
Here is how I'm getting other data and re-displaying it from normal input text boxes:
$.ajax({
url: 'ajax/example/example.php',
data: "findval="+carrier+"&column="+column,
dataType: 'json',
success: function(data)
{
var auto_id = data['id'];
var auto_name = data['name'];
var auto_address = data['address'];
var auto_trailer_types = data['trailer_types'];
$('#output_autocomplete_forms').html("<form id='example' class='form-horizontal'><input type='hidden' name='auto_id' id='auto_id' class='form-control' value="+auto_id+">......<div class='form-group'>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA1'>DATA1</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA2'>DATA2</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA3'>DATA3</label></div>
var auto_trailer_types = data['trailer_types'];
Now how do I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
So, I am guessing that the string stored in the database is something like 0|0|1|0, and you need to restore the checkboxes to that state.
As has been said, you can use AJAX for that. First, you need a trigger to launch the AJAX routine -- a button click, usually:
<button id="mybutt">Update Checkboxes</button>
Your AJAX routine will look something like this:
var rowID = $(this).closest('tr').attr('id');
alert(rowID); //this datum must allow you to identify the row in the database
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'id=' +rowID,
success: function(recd){
var arrCB = recd.split('|');
for (var n=0; n<arrCB.length; n++){
var z = n+1;
$('#cb'+ z).val( arrCB[n] );
}
}
});
another_php_file.php:
<?php
$id = $_POST['id'];
$pseudo_query = "SELECT `field_name` FROM `table_name` WHERE `id` = '$id' ";
echo $pseudo_query_result;
The pseudo_query_result that you echo should be your original 0|0|1|0. The PHP echo sends that datum back to the jQuery AJAX routine's success function. Important: the received data is not available outside that success function. You must do what you want with that data inside the success function, as shown in above example.
In above code, .split() was used to turn the 0|0|1|0 string into an array, and then we use a for loop (or even just manually code each checkbox update individually).
Use ajax to resolve this issue. But before try to encode your php query response in JSON
$.ajax({
url: "test.php" //Your request URI
}).done(function(data) {
//data (you can name it whatever you want) is the data that you get from your request.
//eg. if(data.checkbock){ //do something }
});
More informations here

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

variable in jquery function is null

I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();

Generic jquery structuration question

please take a look of this:
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
val1 = $('#add_lang_level').val();
listitem_html = '<li>';
listitem_html += val + ' <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelang.php', data: {addname: val,addlevel: val1}, type: 'post', success: function(output) { alert(output); }});
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
$(this).parent().remove();
$.ajax({ url: 'addremovelang.php', data: {delname: val}, type: 'post', success: function(output) { alert(output); }});
});
});
This simple jquery script adds strings to a html list when the user hits the button with the id add. Also, it puts a remove link to each line, so when the user hits remove it triggers the function remove_lang and the string is deleted.
When the users add a string, this text comes from a text field, and i stored it on the variable val (as you can see on the 5 line of the code). Then i call a php script via Ajax to add this info to my mysql database.
But, when the user remove the string, i dont know how to know what string was removed, i mean, the name of this one, that i need to send to my php script in order to remove it from the database.
Take a look of this version of my code without the ajax call: http://jsfiddle.net/wnFsE/
Thanks for any help!!!
When you click remove you can do something like this:
val = $(this).parent().find('input').val();
That will get the value from hidden input you added:
Demo Here
You need to think about the string as instead a group of elements:
var li = $('<li/>');
var strong = $('<strong/>', { text: '(' + val1 + '/100)' });
var link = $('<a/>');
link.click(function()
{
// Insert code here for the link click
});
li.append(strong).append(link);
$('#langs').append(li)
There are other patterns that would work too, like:
$(listitem_html').find('a').click(function()
{
// Insert code here for the link click
});
Just get a reference to the element, and then attach the click event handler.
An Object Oriented Programming approach would help keep the actions very organized. You basically store the actions for each given language in an object, modifying the action for that language whenever it's removed or added.
Here's a live example that will print that "storage" object out to the console every time you add or remove a language so that you can clearly see what's going on.
And here's just the JS code (you'll notice that I barely changed a thing):
languageActions = {}
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += val;
listitem_html += '<input type="hidden" name="languages[]" value="' + val + '" /> ';
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
//now add it to our object
languageActions[val] = 'add';
console.log(languageActions);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
val = $(this).prev().val();
$(this).parent().remove();
//now change it's value in languageActions
languageActions[val] = 'remove';
console.log(languageActions);
});
});
The only other thing I'll point out is that you don't really need that hidden input element since you're doing this via AJAX rather than a standard form submit. Instead, you could just do <li><span>Spanish</span><a class="remove_lang">Remove</a></li> for your HTML and then the click event on .remove_lang would do $(this).prev().text() rather than $(this).prev().val(). Not a huge deal, but you're HTML will be a little cleaner.
I guess that would be a simple:
$i = 1;
while(xxx){
//get the list with a different value for each element
echo '<div id="add_' . $i . '>$whatever</div>';
$i++;
}

Post SELECT element value

I use jquery to post data to mysql.
**In settings.php i have this short JS code:**
$("form#submit").submit(function() {
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "settings.php",
data: "fname="+ fname +"& lname="+ lname,
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
return false;
});
**And this short php:**
if (isset($_POST['fname'])){
$fname = htmlspecialchars(trim($_POST['fname']));
DO SOMETHING....
}
This is the code where the FNAME comes from: (after hit ADD image-button then posted the fname value..)
echo "......
<form id='submit$i' method='post'><input type='hidden' name='fname' id='fname' class='text' value='$fm_linkaz'></div><input name='add'type='image' id='add' value='$fm_linkaz' src='s.png'/></form>..........";
This is work well. But i need a SELECT element, so i changed the code to:
......
echo "<select name=dropdown_list id='**ONAME**'><option value''>test</option>";
for($i=0; $i < count($myarray); $i++){
echo "<option value='$myarray[$i]'>$myarray[$i]</option>";}echo "</select>";
......</form>";
This is work well, but i dont know how can i modify the JS code, to post the selected value too.
Thank u for your help.
First of all the javascript code needs a few updates:
$('#fname').val() is better than $('#fname').attr('value') -- .val() will work on selects/checkboxes as well - where .attr('value') won't be reliable.
Second: the data parameter to your $.ajax() call can take a json object (which it will convert to the form string)
$.ajax({
type: "POST",
url: "settings.php",
data: {
'fname': $('#fname').val(),
'lname': $('#lname').val(),
'oname': $('#oname').val()
},
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
There is a plugin that makes this much easier:
$("form").ajaxForm({
success: function(){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
UPDATED:
Also - the <select> element was named "dropdown_list" - perhaps you wanted it to be submitting data as "oname" instead. Form elements use the "name" property to submit, the id property only makes css/js selectors easier to code.
To get a selected value for use
jQuery('#**ONAME**').val();
Although I'm not sure if **ONAME** is valid ID, try removing the **
To get the value use the
$('select[name=dropdown_list]').val();
You could also use and ID, but I think you have some invalid chars in it and I doubt this will work:
$('select#**ONAME**').val();
Anyway .val() is what you are looking for. I also suggest using val() instead of attr('value').

Categories