This Works fine and count returns 2:
$request_ids="166409183417843,1913616994605";
$sent = explode(',',$request_ids);
$count = count($sent);
But when using Jquery to post to another page sent var returns only the last id and count returns 1.
Page of origion:
$(function(){
$.post("process_ids.php", { request_ids: response.request_ids } );})
process_ids.php file:
$sent = explode(',', $_POST['request_ids']);
$count = count($sent);
I also checked with alert() the value of response.request_ids value and it's the same.
Something is totally screwed here, what's wrong?
I hate answering my own question but it's better than no answer.
The problem was like some mentioned above - the data type of the variable.
I simply cast the string to it before sending:
$(function(){
$.post("process_ids.php", { request_ids: String(response.request_ids) } );
return false;
});
Related
So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?
change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.
So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.
What I'm attempting to do is invoke the loading of data from mysql into a php that's being called through jQuery then json_encode the array and send it via header('Content-type: application/json') to the jQuery function that's going to subsequently process the array as data for updating specific elements on the page.
I'm at the final lap here, having jQuery making the call, php accessing the database and sending the data back as a json array to the main page and getting most of the elements updated with their fresh data. Where I'm stuck is at analyzing a specific attribute of one element of the array: determining if a specified element exists in the array and, if so, disabling and hiding an input element.
What is being returned by the call is "btn1:true" ("true" being an arbitrary value) and no matter how I approach checking its existence, inArray gives me a -1, meaning that, even though it is making it through as an element of the array, my code is failing to find it.
Here is the code that makes the call and processes the incoming data:
<script type = "text/javascript">
$(document).ready(function () {
$('#refresh').click(function () {
$.get('includes/refresh.php', function (data) {
if (jQuery.inArray(btn1, data) > -1) {
$('#btn1').prop("disabled", true);
$('#btn1').hide();
}
});
});
});
</script>
Here's the JSFiddle, though without understanding exactly what format the array is in, getting positive results here doesn't help.
Here's the code that's called to pull data from mysql and send it back as a json array:
if (isset($_SESSION['id'])) {
$divs = array ();
$divs['item'] = $row['item'];
$divs['cost'] = "Ticket price: ".$row['cost'];
for ($i = 1; $i < 20; $i++) {
$divs['tname'.$i] = $row['t'.$i];
if ($row['t'.$i] != "") {
$divs['btn'.$i] = "true";
}
}
$divs['end'] = $row['end'];
$divs['winner'] = $row['winner'];
header('Content-type: application/json');
echo json_encode($divs);
die();
} else {
// nothing to refresh. clear the page and prompt user to start a new raffle.
}
... and here's the button that I totally want to make disappear:
<input id="btn1" class="submit" name="t1" type="submit" value="Buy!" />
So, to sum: the call is functioning, the data is being dragged from mysql and compiled into an a json-encoded array that's subsequently being passed to and being received by the calling script. My element check is failing to find what I know to be in the array. What am I overlooking?
Couple of things. Use getJSON instead of get because you're getting JSON.
$.getJSON('includes/refresh.php', function (data)...`
And, you're sending this data
$divs['btn'.$i] = "true";
// which gives $divs['btn1'] = "true";
but you're using btn1 as a variable not a string literal
if (jQuery.inArray(btn1, data) > -1) {
and it's a KEY not a variable in the array.
It should read
if (data.btn1) {
// or to be really specific:
// if (typeof data.btn1!='undefined' && data.btn1)
Also, while "true" IS truthy, so is "false", I think you mean $divs['btn'.$i] = true;
Also also (it's not part of the problem but...)
$('#btn1').prop("disabled", true);
$('#btn1').hide();
There's no need to keep selecting the element. Chain the commands.
$('#btn1').prop("disabled", true).hide();
Every time you select it, jQuery has to search for it. If you can't chain them, set a variable once. $btn=$('#btn1'); and use that $btn1.hide(); $btn1.show(); ....
After searching for internet and even here for 5 hours, i am still stuck at getting value of a local variable in a function and sending it to PHP.
I have tried different syntaxes but none of them seems to be working. This code below, takes an input field from PHP and assign some value to it (having problem send this value back to PHP)
$(document).ready(function() {
//select all the a tag with name equal to modal
$('form[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Dont go until value is not 7
console.log('i am Now waiting for input');
var s = $('#serial').val();
console.log('searching for ' + s);
while(s.length != 7) return;
//When code value reaches 7
var code = $('#serial').val();
console.log('Value is reached ' + s);
});
});
In PHP
echo "<script>document.write(code);</script>";
Uncaught ReferenceError: code is not defined
please help
You should do somthing like this in javascript when $('#serial') is your input field.
$.ajax({'url':'your_php_file_url', 'type':'post', 'data':{'str':$('#serial').val()}}).done(function(data){
console.log(data.code);
});
And in php
$output = Array('code' => 'not set');
if (isset($_POST['str']))
{
//do your search and assigne value to output
$output['code'] = 'some value';
}
echo json_encode($output);
In short - you send your search string via ajax to php and make your searches. Then you echo it out as json, then ajax will read it as an object and you can use those values you want.
ok, i have almost tested every possible solution but all in vain... so i am off and try to use some normal method rather than javascript. Thanks for all your answers guys.
I am using the jquery plugin datatables and am trying to take advantage of the fnRender function to manipulate some data.
I have a php script that returns a JSON string from my $.post. Here is a sample response that I get from each post: {"description":"myvalue"}. I got this from the Google Chrome Developer Tools.
Here is my post function:
$.post("functions/getDescription.php", {gpn:oObj.aData[1]},
function(data) {
returnedVal = jQuery.parseJSON(data);
var test = returnedVal.description;
//alert(test);
return test;
});
Here is my php script:
$passedVal = mysql_real_escape_string(($_POST['gpn']));
$descriptionPrint = array('description' => "");
include 'db_include.php';
$getDescription = "SELECT part_number_description, description FROM unit_description
WHERE part_number_description = '$passedVal' ";
$result = mysql_query($getDescription,$db) or die(mysql_error($db));
while ($row = mysql_fetch_array($result)) {
extract($row);
$descriptionPrint = $description;
echo json_encode(array('description' => $descriptionPrint));
}
There is only one value returned from each query.
Every row alerts the right value but returns undefined.
If I replace javascript function with only a return value of a string or any generic value it works fine.
I feel like there has to be something silly I'm missing in all this. Any help is much appreciated and please let me know if you need more information (I know troubleshooting something running in a plugin like datatables can be frustrating). Thanks.
Because $.post does not return the return value of the anonymous callback function you pass to it as its third argument.
Since Ajax is asynchronous, $.post even returns before the callback function is executed.
If you want to do something when the data gets back from the server, then the callback function has to to it (or call another function to do it).
This is the same reason that the following wouldn't work:
var were_you_expecting_sunshine = $('button').click(function () {
return "sunshine";
});
What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.
What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit.
I've seen several examples around here but not quite what I'm trying to do.
$('#mybtn').live('click',function(){
$("input[type=checkbox]").each(function() {
// I guess do something here.
)};
)};
the code i believe you are wanting is this
$('#mybtn').live('click',function(){
var num_checked = $("input[type=checkbox]:checked").length;
var checkbox_values = new Array();
if( num_checked > 3 ) {
//its greater than 3
//do what you need to do
} else if( num_checked < 3 ) {
//its less than 3
//do what you need to do
}else {
//it equals 3
//do what you need to do
//go thru and add values to array
$("input[type=checkbox]:checked").each(function() {
checkbox_values.push($(this).val());
});
}
});
if you want to send email of variables you can output array checkbox_values to php
If all your checkboxes are in a form, you can do $('#form_id').serialize();
You can get how many are checked using
$("input[type=checkbox]:checked").length
http://jsfiddle.net/XKRRL/7/
Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.
full code
$(function() {
$('#mybtn').live('click', function() {
var checkedBoxes = $("input[type=checkbox]:checked"),
checkedNum = checkedBoxes.length;
if(checkedNum === 3){
for(var i=0; i< checkedNum; i++){
alert($(checkedBoxes).eq(i).val());
}
}
});
});
It's simple to grab all checked checkboxes:
var checked = $('input[type=checkbox]:checked'),
count = checked.length;
if (count == 3) {
values = $.map(checked, function(i){
return $(this).val();
});
}
Then do whatever you want on the values array.