javascript error with php variable passing in codeigniter - php

function something(frm,i){
//var ch=frm.outof1.value;
for(var j=1;j<=i;j++)
{
//var b="outof" + j;
alert(frm.outof+j.value);
}
//alert("outof" + i);
return false;
}
$js='onClick="something(this.form,\''. $ii .'\')"';
echo form_button('mybutton', 'Click Me', $js);
and getting output NAN
where in html this is // echo form_input('outof'.$i,''); // the form input.

First, you will want to make sure the passed $ii is made into the correct type (not a string) by using parseInt. Then you construct the form input name by concatenating 'outof' and the number before evaluating .value.
function something(frm, i)
{
for(var j = 1; j <= parseInt(i); ++j) {
alert(frm['outof' + j].value);
}
}

alert(parseInt(frm.outof) + parseInt(j.value))
Most likely, you're trying to sum up strings, and not integers

Related

jQuery append dict to html, how to insert a auto-incrementing id from 1

How to insert a auto-incrementing id from 1 before info.name in jQuery? I use below code to get aggregated data, for example, each quessionId has many related reasons. Below is my partial code of .js code in jQuery:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
var info = lc;
console.log('info', info);
$('.tags_question').append('['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>
In the console, I do have those dictionaries, but why the page only get one dict?
Thanks so much for any help.
Thanks so much for Swati's help, to change .html to .append.
You can define a variable which will store the value of count and then whenever you need to print it first increment it and then add that as well with the data which you are already appending .So your code will look like below :
var count = 0; //declare this
for (var i = 0; i < DATA.questions[id].tags.length; i++) {
//..other codes
var lc = lb[c];
if (lc._id == lid) {
count++; //increment
var info = lc;
console.log('info', info);
//add with other datas
$('.tags_question').append(count + '[' + info.name + ']' + info.description + '。' + 'Reason: ' + info.reason + '。' || '[no data]');
}
}

convert php to javascript #1

I'm trying to convert this awesome pathfinding php function from http://granularreverb.com/a_star.php to javascript.
PHP function
function path_float(&$heap, &$values, $i, $index) {
for (; $i; $i = $j) {
$j = ($i + $i%2)/2 - 1;
if ($values[$heap[$j]] < $values[$index])
break;
$heap[$i] = $heap[$j];
}
$heap[$i] = $index;
}
JAVASCRIPT function
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = j) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}
I'm not sure if javascript understands for() without all elements? If i try to execute javascript function my browser freezes.
P.s. i'm not interested in pre-written js pathdindings, because i need identical php and js function.
Thanks in advance
You can use for without all the elements in javascript similar to PHP. So that is not the problem.
I think the problem is the float that is returned to J. it could be that it never realy is 0 but might be some large float like 0.00000000001 or something and thus never evaluates to false. Unfortunately I cannot test it as You did not provide any input values.
Try the following:
var $path_f;
var $path_h;
var $path_g;
var $path_open_heap;
function path_float($path_open_heap, $path_f, i, index) { // return heap & values
var j;
for (; i; i = parseInt(j)) {
j = (parseInt(i) + parseInt(i)%2)/2 - 1;
if($path_f[$path_open_heap[j]] < $path_f[index] ){
break;
}
$path_open_heap[i] = $path_open_heap[j];
}
$path_open_heap[i] = index;
}

learning getjson

I'm trying to get a grasp on using $.getJSON with an array from PHP.
Here's a simple example where all I want to do is output the requested info. Should the alert(data) return the array object? I am not alerting anything.
PHP file (account.php):
$arr = array('items' => 5,'others' => 6);
echo $arr = json_encode($arr)
HTML file:
$("#unsubscribe").click(function() {
$.getJSON("account.php?", function(data) {
alert(data);
});
});
First of all, it's probably a good idea if you try to load account.php in your browser. You should expect to see:
{"items":5,"others":6}
However, you won't see this. You will instead see a Parse Error, expected ;. Because you forgot it on the echo line.
This is why you see no alert. A PHP error is clearly not valid JSON, and viewing the browser's error console would tell you this ;)
In my projects I am using dump function for viewing json returned array.
Here it is:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "'"+"\\n";
if (level < 0)
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => '" + value + "'"+"\\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

assigning a $_GET variable to a JS variable

www.mywebsite.com/?foo=bar
How can I get the value of foo into a Javascript variable?
You don't even need PHP for that. Basically, you can parse window.location.href to get the value of a GET URL parameter into a JavaScript variable.
There is plenty of code online, you can use for example this:
function getUrlParameter( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
To get the value of foo, just call getUrlParameter("foo") in your JavaScript code.
You can parse the window.location.search string for query variables.
https://developer.mozilla.org/en/DOM/window.location
For example
var query = window.location.search.substring(1);
var pairs = query.split('&');
var _get = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
_get[pair[0]] = pair[1];
}
I did some googling and here is a link for you http://www.zrinity.com/developers/code_samples/code.cfm/CodeID/59/JavaScript/Get_Query_String_variables_in_JavaScript
You can try this
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
EDIT
The above will parse the URL and give you the parameters as an associative array. You can also try
function getURLVars(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
In this if you want the value of foo, call this with getUrlVars('foo')

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories