Basically i want to update my database with values from an array that i converted from javascript to php
then when a button is pressed it updates the database
i have this code but it doesnt update to the database
var v = document.getElementsByName('mark[]');
var arr = new Array();
for(var a=0; a<v.length; a++){
arr[a]=inputs[a].value;
}
var str;
for(var i=0; i<arr.length; i++) {
str+='&array_items[]='+arr[i];
}
document.location.href='./markandfeedback.php?'+str;
}
</script>";
for ($i=0; $i<count($_GET['array_items']); $i++){
$arr[] = $_GET['array_items'][$i];
}
if(isset($_POST['update'])){
$sql1="UPDATE `groupdatabase1` .`questions` SET `mark`= '".$arr[1]."',`studentID`= '4140001', `feedback` = 'meh' WHERE `questions`.`questionID`=1";
mysql_query($sql);
}
You are assigning your query to the variable named $sql1, but then using a different (probably uninitialized variable) named $sql in your call to mysql_query.
Well youre not sending a POST request youre sending a GET so $_POST['update'] will never exist. In addiiton to that im not sure why there is a " sfter the script tag... unless youre omitting code and thats actually written inside php theres no reason for it.
Typically you would use AJAX for this, otherwise you would use a form... even if you still run your JS and put the results in a set of hidden fields so there is no real form interface.
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.
I have this PHP Code which populates a select menu from a MySQL Database...
<select name="input" id="input">
<?php
$sql="SELECT * from table ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<option value="'.$result["db_field"].'">'.$result["db_field"].'</option>';
}
?>
</select>
which works perfectly fine but i need to somehow get it into a javascript function.
I have the javascript code that when you click a button it adds more text boxes and another select menu but it does not populate the data from the database in any new (added on) select menus
You can probably convert the options into JSON using json_encode (I am not a PHP programmer and dont know exact semantics of using it)
In PHP do something like:
echo '<script>var optionsJSON = '.json_encode(mysql_fetch_array($rs)).'</script>'
In javascriptn do something like (I am using jquery):
var select = $('select.classOfThisSelect');
var options = JSON.parse(optionsJSON);
for(var i = 0; i < options.length; i++)
$('option').attr({value: options[i]}).append(options[i]).appendTo(select);
optionsJSON will be the JSON string which will be globally available
You can freely use it in your Javascript function
Note: You may need to surround the json_encode with quotes
Start by converting the string of values into an array, so you have something like:
var values = ['value0','value1','value2'];
Then you can convert them to options and add them to a select element like:
function addOptions(select, values) {
for (var i=0, iLen=values.length; i<iLen; i++) {
select.appendChild(new Option(values[i],values[i]));
}
}
And call it like:
addOptions(document.getElementById('input'), values);
after the select is added to the page.
Incidentally, you don't need to add both an id and name to form controls. You must have a name for them to be submitted, the ID is unnecessary. If you get a reference to the form you can access controls as named properties of the form, so you might reference the select using:
document.forms[0]['input'];
or
document.forms[0].input;
and so on. Note that "input" isn't a good choice of control name.
-Issue Still Unresolved-
I'm trying to call a database, put all the rows of a table in an array, pass that table to my JS as json data, and then use that data as parameters for a function.
When I run the script nothing happens. I don't get any errors in the console, the rest of the script loads normally. I'm pretty new to mySQL and PHP, what am I doing wrong here? I suspect that I goofed up the php somehow.
XAMPP server, being tested on my desktop
all linked files are in the same directory
There are no visible errors displayed anywhere. As far as I can tell, the script doesn't even try to load the PHP to begin with, but also doesn't display an error in firebug's console
Attempted:
Renaming the table without spaces
placing the for loop inside the callback function
amending php errors
Here's the updated JS I'm using:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {"table" : "firstlist"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
and here's the updated PHP:
error_reporting(E_ALL); ini_set('display_errors','On');
$con = mysql_connect("localhost", "root", "m3648y73");
if (!$con){die('Could not connect: ' . mysql_error());};
mysql_select_db("tasklistdb", $con);
$table = $_GET['table'];
$sql = mysql_query("SELECT taskName, taskId, taskDescription, taskComplete FROM `".$table."`");
$listTasks = array();
while ($row_user = mysql_fetch_assoc($sql))
$listTasks[] = $row_user;
echo json_encode($listTasks);
mysql_close($con);
Am I linking to the DB correctly?
getJSON is asynchronous call. So before it could fetch values from PHP and execute the callback function, it moves to the for loop and here table is empty.
Solution: shift your for loop inside the callback function
You are missing a semi colon on the line $listTasks = array() in the php file
This happens because js-code after async request executed earlier than request itself is over. Try this:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {table : "first list"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
Your table name can't be 'first list'
You can't have a space in a MySQL table name.
Also you should put put table in the JSON value in double-quotes like {"table":"table_name"}
From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())
All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>