I have a select dropdown that when it is changed I want to update a value in the database. Ajax is firing as I get the gif pop up and there are no errors in the console but the database does not get updated. All other fields (eg the startdate in the example below) work fine so the Ajax call is right I think. I've tried using both onBlur and onChange as my event handlers for the select.
<td <form><select onblur="saveToDatabase(this,'workingpatternid', 'employmenthistory', 'employmenthistoryid','<?php echo $employmenthistory[$k3]["employmenthistoryid"]; ?>')"><option value="<?php echo $employmenthistory[$k3]["workingpattternid"]; ?>"><?php echo $employmenthistory[$k3]["text"]; ?></option><?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?> <option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>"><?php echo $workingpatterns[$k4]["text"]; ?></option><?php }}?></select></form></td>
<td contenteditable="true" onBlur="saveToDatabase(this,'startdate', 'employmenthistory', 'employmenthistoryid','<?php echo $employmenthistory[$k3]["employmenthistoryid"]; ?>')" onClick="showEdit(this);"><?php echo $employmenthistory[$k3]["startdate"]; ?></td>
Savetodatabase function:
<script type="text/javascript" name = "editable fields">
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,table,primary,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&table='+table+'&primary='+primary+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
saveedit.php
<?php
require_once("connect_db.php");
$table=$_POST['table'];
$column=$_POST['column'];
$value=$_POST['editval'];
$primary=$_POST['primary'];
$id=$_POST['id'];
$sql = "UPDATE `$table` SET `$column` = '$value' WHERE `$primary`='$id'";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
Debugging the request being sent:
Client side
If you press F12 while on your calling page, go to the network console (I am asuming that you are using a newer browser like Chrome 40+ or IE 9+) and make sure that the cache is being saved (ie not refreshed on page refresh).
Update the page, clear the list, and then trigger your code again. Note whether the request is sent as you expect (click on the line representing the call to saveedit.php and then request)
Server side
You could add a call to error_log(var_export($_POST)) to see if you received what you expect. Results will be in your webservers error.log, thereby this does not expose data to users, if accidentally left in after deployment.
Also verify that the page is being called, by tailing access.log on your server.
Getting the expected value via javascript:
The trouble is that the first call is in a select; the code could be editableObj.options[editableObj.selectedIndex].value but the second is in a div element. Either you should reconsider your page design, or make two different functions (not recommended)
Related
I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>
I'm trying to use a button to load more data from database with PHP.
Till now I can count the results and the results that are showing.
So when $count==$countAll, all the results are normally showing.
Can someone explain why this isn't working?
// Count all results
$allResults = $conn->prepare("SELECT*FROM tl_picture WHERE text LIKE '%$innerhtml%' ORDER BY id DESC");
$allResults->execute();
$countAll =$allResults->rowCount();
echo "Found results: ".$countAll."<br>";
//max 20 results showing
$statement = $conn->prepare("SELECT*FROM tl_picture WHERE text LIKE '%$innerhtml%' ORDER BY id DESC limit 20");
$statement->execute();
$collection = $statement->fetchAll();
$count =$statement->rowCount();
echo "viewable results: ". $count;
<script>
<?php if($count==$countAll): ?>
document.GetElementById('loadButton').style.display='none';
} else {
document.GetElementById('loadButton').style.display='block';
}
<?php endif; ?>
</script>
What you are trying to achieve is normally done with ajax calls. So the check for the visibility of the Load More button must be done with javascript after every asynchronous load. PHP runs on server side, once before sending the HTML document to your browser and doesn't help at all in this case.
Also you execute the sql query for all rows and then you do it again with limit this time. It is inefficient to run twice the same query just to get the number of all records.
The logic should be that you load 20 rows and each row should have an identifier. Using the identifier of the last loaded row, you ajax request the next 20 rows etc. If response data from ajax is empty, then you hide the Load More button (or disable it and set text to something like "No more records").
You might have an error in this script:
<script>
<?php if($count==$countAll): ?>
document.GetElementById('loadButton').style.display='none';
} else {
document.GetElementById('loadButton').style.display='block';
}
<?php endif; ?>
</script>
You might change it to something similar to:
<script>
<?php if($count==$countAll): ?>
document.GetElementById('loadButton').style.display='none';
<?php } else { ?>
document.GetElementById('loadButton').style.display='block';
<?php endif; ?>
</script>
The problem might be that your } else { is in JavaScript, yet there might be no if for it?
I'm trying to have my code add this 2 fields to a form (quantities and products) on a click of a button.
How do I format my script so the innerHTML can include php code?
Or is there another way to add a select element via JS?
newdiv.innerHTML = "<input type='text' name='quantities[]'> <select name='products[]'>
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>";
PHP code is interpreted by your server before the page is even sent to the browser. The server then sends a completed html page (no PHP code) across the internet to your browser, which then loads it and then executes the JavaScript in the browser. The PHP interpreter would have no way of reading what the JavaScript changes on the finished page.
You might want to look into making an Ajax call to a PHP page, your PHP page can then contain the sql query and return data the JavaScript can use to add the options.
I have some php that connects to a database and creates a drop down list. I have a specific form in the HTML that I'd like to put the list in.
<body>
<form>
// some text inputs
// where i'd like the drop down to go
<?php makeList(parameter1, parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList(arg1, arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
The only languages I'm allowed to use (apart from the sql) are php, html and javascript. As it is right now, makeList() returns an empty list. When I include opening and closing form tags in the function it returns a fully functional list, but then it acts as it's own form and I need to to be a part of the original form. Thanks.
EDIT: Sorry, forgot to mention the makeList function works fine when called within the php tags. It's when I call it in the HTML that it returns an empty list.
Firstly, you have some syntax issues with your script. It's not a valid HTML file, not a valid PHP file, and not a valid JS file.
If it were up to me, I'd define the PHP function at the stop of my script. Be careful to balance your opening and closing PHP tags. Something like this:
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
?>
And only after that would I start to output my HTML.
Now there are a couple of important things to note about that script I just posted:
the database code is not in here...I don't see any connection or query getting run or anything
In your script, this function doesn't look valid. arg1 and arg2 need a $ in front of each to be a valid PHP function. If it's a JS function you want then well, you are very confused and probably need to go back and figure out why this is not a valid JS function.
Your function refers to a variable, $result, that you have not bothered to define. It is not mentioned anywhere else in your script. It is most certainly not mentioned anywhere inside your function. For $result to be defined inside your function, you either need to pass it in as an array or declare it as a global:
global $result
Your function doesn't return anything at all. It just echoes stuff. This doesn't mean you can't use it, but it does mean that the function has no return value. Echoing the result of makeList won't output anything at all
So after that script above, you might have something like this:
<body>
<form>
// some text inputs
<?php makeList($parameter1, $parameter2); ?>
// submit button
</form>
Depending on what your parameters ($parameter1 and $parameter2) are this should work.
<body>
<form>
// some text inputs
<?php echo makeList($parameter1, $parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option>";
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
I am trying to update the $_SESSION['state'] whenever the user clicks on the anchor tag by firing the onclick event. The variable $state_names_array as all the names of the states of a specific country. But problem is that no matter whichever of the anchor tag I click on, the $_SESSION['state'] is always getting updated by the last element of the $state_names_array.
<?php
foreach($state_names_array as $value){
$temp = '<?php $_SESSION["state"]=$value;?>';
?>
<?php echo $value ?><br>
<?php
}
?>
I will not code whole code, I will just show you an example, how to do it:
<?php
foreach ($state_names_array as $value) {
echo ''.$value.'<br>';
}
?>
Then you will have javascript function change_value:
here you will send ajax call to some PHP file, where you will process $_SESSION["state"]=$value;
Also you didnt say, what you want after anchor is clicked, because you will be able to access new $_SESSION["state"] only after refreshing your site...
Also maybe you just want to redirect to index.php, after clicking on some anchor, and that will be enough for you, then just use value as $_GET parameter, f.e.:
<?php
foreach ($state_names_array as $value) {
echo ''.$value.'<br>';
}
?>
and add to you index.php file this lines:
if (isset($_GET['new_value'])) {
$_SESSION["state"] = $_GET['new_value'];
}