I hope this problem is very simple, I can't figure out the solution myself it seems. Been trying and googling for hours, driving me nuts :) Ok, so I have a drag'n'drop + sortable (using scriptaculous and prototype for your information) on my index.php. I use this code to send the items dropped in a div using this code:
<script type="text/javascript">
//<![CDATA[
document.observe('dom:loaded', function() {
var changeEffect;
Sortable.create("selectedSetupTop", {containment: ['listStr', 'selectedSetupTop'], tag:'img', overlap:'vertical', constraint:false, dropOnEmpty: true,
onChange: function(item) {
var list = Sortable.options(item).element;
$('changeNotification').update(Sortable.serialize(list).escapeHTML());
if(changeEffect) changeEffect.cancel();
changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" });
},
onUpdate: function(list) {
new Ajax.Request("script.php", {
method: "post",
parameters: { data: Sortable.serialize(list), container: list.id }
onLoading: function(){$('activityIndicator').show(), $('activityIndicator2').hide()},
onLoaded: function(){$('activityIndicator').hide(), $('activityIndicator2').show()},
});
}
});
});
// ]]>
</script>
I've been using this code before so I "kind of know" it will send me data to my script.php page. selectedSetupTop is my div containing the elements. Don't mind about the notification and the activityIndicator thingy. My script.php page looks like this for the moment:
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$test .= $selectedSetupTop[$i];
}
echo "<script>alert('$test');</script>";
I can't seem to get any output in the alert message, it's just blank. The purpose of the script.php is to update a row in a database and it will look kind of like this:
$sql = mysql_query("UPDATE table SET row = '$arrayInStringFormat' WHERE id = '1'") or die(mysql_error());
where the $arrayInStringFormat is a conversion of the array $selectedSetupTop to the format (1, 2, 3, 4). I guess I'll solve that using implode or something, but the problem is parsing the array $selectedSetupTop. I'm not it passes between the pages at all, really appreciate help! Tell me if I need to explain further.
Thanks in advance!
''''''
EDIT 1
If it will help, I used this code before that I know will send me the data and use it. Notice I don't wanna do my task like the way I do below:
$querySetup = $_GET["s"];
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$sql = mysql_query("UPDATE " . $querySetup . " SET orderId = $i, hero_selected = 'n' WHERE imageId = $selectedSetupTop[$i]") or die(mysql_error());
}
''''''
EDIT 2
So it does parse, but I still have the problem I can't print it. I wanna implode the array somehow.
Not sure how AJAX works in Scriptalicious/Prototype, but you don't seem to be getting the data from the AJAX call. In jQuery it would be something like this where the data you receive from the script is returned as the argument of the function.
onLoaded: function(msg){
$('activityIndicator').hide(),
$('activityIndicator2').show(),
alert(msg)
}
Secondly, you can't echo a PHP array, you have to encode it to JSON:
echo json_encode($test);
Related
I've just started learning Jquery and I'm trying to post and retrieve some data with Ajax. The data that i wanna extrapolate is some simple text (no json), more specifically numbers. So I wrote this:
$.ajax({
url : 'finproj.php',
type : 'POST',
data : 'p=' + devidproj,
success : function(resultaat) {
var lengtebalxkx = Math.floor(100*resultaat/<?php echo $number; ?>);
$(".ongelezendonatiesproj").animate({opacity:1}, 300).show();
if(lengtebalxkx > 120)
{
$(".ongelezendonatiesproj").width(120);
}
else
{
if(lengtebalxkx < 1)
{
$(".ongelezendonatiesproj").width(2);
}
else {
$(".ongelezendonatiesproj").width(lengtebalxkx - 10);
}
}
},
});
devidproj is a number, as is $number. I tried adding dataType : 'text',
But that didn't work.
The php-file which I'm trying to retrieve the data from, is:
<?php include('config.php');
$pid = $_REQUEST['p'];
$nieuwgeld = mysql_query('SELECT bedrag, aantal, projectid FROM donaties WHERE projectid="'.$pid.'"');
while($nieuwebed = mysql_fetch_assoc($nieuwgeld)) {
$plusbedrag = $nieuwebed['bedrag'] * $nieuwebed['aantal'];
$nieuwebedragen = $nieuwebedragen + $plusbedrag;
}
if($nieuwebedragen<>0) {echo $nieuwebedragen;} ?>
The php-file works fine.
I think I missed a comma or something in the Jquery-script but I can't seem to see what's wrong with it :s I've tried debugging it with alert() but that didn't work.
use
data : {p:devidproj},
insted of
data : 'p=' + devidproj,
Use the following data on your ajax request:
data : {p: devidproj}
Note that there should be no quotes on p.
You should also parse the result on your Ajax request as integer thru parseInt() function since that's suppose to be a number. JS will parse it as string by default if not added.
var lengtebalxkx = Math.floor(100*parseInt(resultaat)/<?php echo $number; ?>);
I saw other posts but it doesn't work. I am a bit confused here on how I implement an array into JS from PHP...
In the PHP file (test.php) I have :
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
And in JavaScript I have :
<?php include 'test.php'; ?>
...
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
So what I look for is to put $value=$row['value']; in the y : and $date=$row['date']; in the x : OR perhaps putting the entire table $table in the var data will work also .
I'm new to JavaScript, so thanks in advance..!
So in your php file....
Add a line at the bottom that converts the table to json data.
And give it a variable...
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
$jsondata = json_encode($table);
Then in your other file....
echo that variable into your data object, in the javascript.
Remember to remove that whole random number generating function...(its just an example)
Echoing PHP into javascript is definitely not considered good practice though.
And it would be better to actually do an ajax call to your php file, and insert like that....I'll also show you how to do ajax.
<?php include 'test.php'; ?>
...
data: [<?php echo $jsondata;?>], //remove that function that was here..
// it was just to generate random numbers for the demo
....
}
EDIT / UPDATE For ajax...
So for ajax...instead of assigning a variable to $jsondata.
Just return it like so...(in your PHP file)
return json_encode($table);
Then for this way....you dont include('test.php') like you did before.
Instead you just have this script inside your $(document).ready(function(){....
$.getJSON('test.php', function(myJSON) {
//and inside this function you put your highcharts stuff...
//remove that function() that generates random data
// And you will put the 'myJSON' return object inside the 'data':[] array...
// Provided you have structured your data correctly for highcharts, it should work...
// If not.... it'll be a start, and you're well on your way to debugging it
}
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
I'm using the following code to pull data and nothing happens. Here's my PHP CODE.
$getall = "SELECT * FROM pages WHERE account_id=$id ORDER BY course_id";
$showall = #mysqli_query ($dbc, $getall); // Run the query.
$json = array();
if (mysqli_num_rows($showall) > 0)
{
while ($row=$showall->fetch_assoc()) {
$json[]=array(
'logged' => true,
'pagename'=>$row['pagename'],
);
} // end while
header("Content-Type: text/json");
echo json_encode(array( 'pages' => $json ));
}
And here's my JS CODE that runs the app.
sendit.open('GET', 'http://myurl.com/mypages.php');
sendit.send();
sendit.onload = function(){
var json = JSON.parse(this.responseText);
var json = json.pages;
var dataArray = [];
var pos;
for( pos=0; pos < json.length; pos++){
dataArray.push({title:'' + json[pos].pagename + ''});
// set the array to the tableView
tableview.setData(dataArray);
};
};
var tableview = Ti.UI.createTableView({
});
currentWin.add(tableview);
When I run the app, all I get is a blank table. Any help would be greatly appreciated.
Have you tried to move sendit.send(); below sendit.open?
Put a log in your onload event to make sure it is being fired at all.
It states in the docs that the onload must be defined before you call open in order for that even to be registered.
You're embedding your array in another array, so on the javascript side it'd be:
dataArray.push({title:'' + json.pages[pos].pagename + ''});
^^^^^ - missing level
You should have sendit.onload before send it.send.
I would also recommend you to implement sendit.onerror method, as well as intermediate Ti.API.debug(stuff);
You also double the declaration of json, with is working, but not great.
Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?
Mainpage:
$("#group_name").change(function(){
var groupname = $("#group_name").val();
var selectedGroup = 'gr_name='+ groupname;
$.post("selectedgr.php", {data: selectedGroup}, function(data){
$.each(data, function(){
$("#" + this).attr("checked","checked");
});
},"json");
});
PHP (selectedgr.php):
<?php
include_once '../include/lib.php';
$gr_name=mysql_real_escape_string($_POST['gr_name']);
$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo $res[];
?>
Change the last line in your PHP sample (echo $res[];) to:
echo json_encode($res);
json_encode() manual page will tell you more.
Also as #Unicron says you need to validate the $gr_name variable before passing it to your SQL statement.
You could use:
if(isset($_POST['gr_name'])) {
$gr_name = mysql_real_escape_string($_POST['gr_name']);
}
See: http://php.net/manual/en/function.mysql-real-escape-string.php for more information in the PHP manual.
You can use json_encode function to convert arbitrary data into JSON. Assuming that you want to return an array of strings, here is how you will use json_encode:
<?php
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
On the client side you can use jQuery.post method, like this:
<script type="text/javascript">
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i < data.length; i++) {
$("#" + data[i]).attr("checked", "checked");
}
}, "json");
});
</script>
If you want to use JSON then just use echo json_encode($res);
But I don't really understand what you'll gain if your code is working now, since you'll still have to do some processing in the Javascript to handle the result.
I found my major problem as below
instead of (before):
$.post("selectedgr.php", {data: selectedGroup}, function(data){
do this (after):
$.post("selectedgr.php", selectedGroup, function(data){
Forgive my bad. Ahh ya guys, regarding the escaping on mysql actually #group_name is not any input field but a select box. Appreciate for every comment, suggestion and guide.
Eric.