how can i use the variable from my php-sql to become the message for my javascript alert?
heres my code
<?php
$select = "SELECT * FROM post";
$result = mysql_query($select) or die("couldn't select table");
while ($rows = mysql_fetch_array($result))
{
echo"<input type='button' class=term onclick='return terms()' value=Terms >";
echo"<input type='hidden' value='$rows[terms]' id='term' name='term'>";
}
?>
<script language="JavaScript">
function terms()
{
var readers = document.getElementById("term");
alert(readers.value);
}
</script>
It works, the alert message displays. But I got the problem on displaying the right message for specific fetch of row. All got the same message (message from the first row).
I tried to use getElementByName but the alert doesn't pop-up,
so i dont have to try making the input name="term[]" --------(into its array form)
Help please!
I think it will be find if you change this line of script
echo"<input type='button' class=term onclick='terms()' value=Terms >";
onclick='terms()' here, instead of onclick='return terms()'
EDIT:
<?php echo"<input type='button' class=term onclick='terms(this)' data-result ='". $rows['terms'] ."' value=Terms >"; ?>
/* Remove the hidden field */
<script language="JavaScript">
function terms(e)
{
var readers = e.getAttribute('data-result');
alert(readers);
}
</script>
Change your second echo statement inside the while loop to:
echo"<input type='hidden' value='". $rows['terms'] ."' id='term' name='term'>";
I usually do the following:
<?php
function alert($text){
echo '<script type="text/javascript">alert("'.$text.'")</script>';
}
alert("test");
?>
Hope that helps.
You are overwriting the value or "term" in your HTML code after each iteration of While-loop. This way it will only get the last value
All of your input elements have the same id. If you want to distinguish them, give them different identifiers. And pass the identifier to the terms function.
You must give different id for each element. I think simple way to do that is by using auto increment for the id.
Related
So, I have a form that has to be filled by the user in a duration. (Fyi, it's still a dummy web). Let's say the duration is 100sec. After 100sec, the data should be sent to database. Here are my codes :
HTML
<div id="countdown"></div>
<form class="test" method="post">
<?php
for($num=1;$num<=10;$num++){
echo "<div class=\"question\">" .$num. "<br>"; /* the question is written here */
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"A\">A<br>";
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"B\">B<br>";
echo "<input type=\"radio\" name=\"answer" .$num. "\" value=\"C\">C<br>";
}
?>
</form>
Why did I do PHP and looping? Coz this is the prototype of my form and also for shortening purpose. I'll not do this for the real web. But, if you think this is a bad idea although it's just a dummy web, just tell me :)
jQuery
var duration=100;
var countdown=setInterval(timer,1000);
function timer(){
duration=duration-1;
$("#countdown").html(duration+" sec");
if(duration<=0){
clearInterval(countdown);
var form_data=$(".test").serialize();
$.post("action.php",form_data,function(){alert("success!")});
}
}
action.php
<?php
include("connection.php"); /* it's the connection to the database */
$answer1=$_POST["answer1"];
$answer2=$_POST["answer2"];
$answer3=$_POST["answer3"];
$answer4=$_POST["answer4"];
$answer5=$_POST["answer5"];
$answer6=$_POST["answer6"];
$answer7=$_POST["answer7"];
$answer8=$_POST["answer8"];
$answer9=$_POST["answer9"];
$answer10=$_POST["answer10"];
mysqli_query($link,"INSERT INTO prototype (`answer1`,`answer2`,`answer3`,`answer4`,`answer5`,`answer6`,`answer7`,`answer8`,`answer9`,`answer10`) VALUES ('$answer1','$answer2','$answer3','$answer4','$answer5','$answer6','$answer7','$answer8','$answer9','$answer10')";
?>
So, the problem is : after the duration = 0, the success action (alert) appears, but after I checked the database, no data has been stored. Wut's actually happen?
I badly need your help on this.
I can't seem to find what's wrong in my code.
The case is, I am trying to populate my textbox field based on my combobox value and it is connected in sql database. I have tried some codes on the web and then I found a code which seems accurate but I can't seem to display the result on my textbox.
here is my HTML Code:
<?php
echo"Concept Store:";
echo "<select width='100' id='strs' name='strs' >";
echo "<option></option>";
while($row=sqlsrv_fetch_array($stmt))
{
$x= $row['strnm'];
echo " <option> $x</option>" ;
}
echo "</select>";
?>
Address    : <input type="text" id="add" name="add" size="27" /><br><br>
here's the AJAX:
<script type="text/javascript">
$(document).ready(function(){
$('#strs').change(function(){
$.post("gadd.php",{strs:$(this.val() )},function(result){
$("#add").val(result);
});
});
});
</script>
and here's my 'gadd.php'
<?php
session_start();
include ('sqlconn.php');
$gadd=$_post['strs'];
//$t1= mysql_real_escape_string($t1);
$sql="Select distinct dadd1 from ostore where strnm='".$gadd."' ";
$stmt = sqlsrv_query($conn,$sql);
//echo "<option></option>";
while ($row = sqlsrv_fetch_array($stmt))
{
// $type2=$row['dadd1'];
echo $row['dadd1'];
//echo '<option value ="'.$type2.'">'.$type2.'</option>';
}
?>
if you could help me, that would be really really awesome thank you!
Check it. Global variables should be in upper case.
$gadd = $_POST['strs'];
First, make sure you use the proper format for global variables $gadd = $_POST['strs'];
Second, check your query if it is working, try this
$sql=("Select distinct dadd1 from ostore where strnm = '$gadd'");
Most problably it's because you're missing the value in the option.
Use this:
echo " <option value='$x'> $x</option>" ;
instead of this:
echo " <option> $x</option>" ;
If still don't work, like was said before check if the query is working.
You can do that in chrome by the option "Inspect element" and the go to the "Network" tab. You can see what is sent through ajax and the return data.
I create one simple list in PHP where user can add Name, age, emails, etc. I added a delete option too, but I want to add a confirmation message when the user clicks on delete option.
I tried searching Google but I found only jQuery and JavaScript solutions. Is there any way to do this with PHP only?
List.php
<?php
include('config.php');
$query1=mysql_query("select id, name, age from addd");
echo "<table><tr><td>Name</td><td>Age</td><td></td><td></td>";
while($query2=mysql_fetch_array($query1))
{
echo "<tr><td>".$query2['name']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Edit</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."'>x</a></td><tr>";
}
</table>
?>
Delete.php
<?php
include('config.php');
if(isset($_GET['id']))
{
$id=$_GET['id'];
$query1=mysql_query("delete from addd where id='$id'");
if($query1)
{
header('location:list.php');
}
}
?>
If you want to do this only in PHP, you will need to add "steps" in your script, like:
step1 (show form) -> step2 (ask validation) -> step3 (validate)
To do so, you can use sessions to keep form content, and GET parameter to track the step.
Otherwise the simplest solution is to use javascript:
echo "<td><a onClick=\"javascript: return confirm('Please confirm deletion');\" href='delete.php?id=".$query2['id']."'>x</a></td><tr>"; //use double quotes for js inside php!
This is u need
while($query2=mysql_fetch_array($query1))
{
echo "<tr><td>".$query2['name']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Edit</a></td>";
echo "<td><a onclick='javascript:confirmationDelete($(this));return false;' href='delete.php?id=".$query2['id']."'>x</a></td><tr>";
}
and create javascript function
function confirmationDelete(anchor)
{
var conf = confirm('Are you sure want to delete this record?');
if(conf)
window.location=anchor.attr("href");
}
believe me it's work :)
Here is a variation of above that gives you the Confirmation box and passes a variable from PHP to Javascript and back to PHP.
I used this to select a radio button to delete a file from a list of files.
See OnClick runs function with php $fileName past to Javascript, confirmation asked with file name, and if yes, transfers to href with variables for $_GET
PHP/HTML Code:
<?php
echo "
<tr>
<td>
<input type='radio' name='input_sched_button'
onclick='confirmation(".'"'.$fileName.'"'.")' />
</td>
<td class='fixed-td-450'><a href='./$namehref'>$fileName</a></td>
<td class='fixed-td-40'>$extn</td>
<td class='col3'>$size</td>
<td class='fixed-td-80'>$modtime</td>
</tr>
";
?>
Javascript
<script>
function confirmation(delName){
var del=confirm("Are you sure you want to delete this record?\n"+delName);
if (del==true){
window.location.href="Some_Program.php?delete=y&file="+delName;
}
return del;
}
</script>
onclick="return confirm('Are You Sure ?')"
delete
Add an onClick event to trigger the dialog box and javascript:return confirm('are you sure you want to delete this?');
echo "<td>x</td><tr>";
<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
alert ("record deleted")
}
return del;
}
</script>
//add onclick event
onclick="return deleletconfig()"
work for me but, change this:
onclick='javascript:confirmationDelete($(this));return false;'
with:
onclick='confirmationDelete(this);return false;'
I don't know, if this makes any sence, but I have come up with a solution on my own. It does not work, but I would like to share the idea in here, as it basically is supposed to do the same thing. My solution was to just have php echo the javascript, and then having the code, that is supposed to be executed echoed in javascript, so it would be execuded as normal php on site.
this is the site where I got the idea of running the php inside the JS
echo "
<script>
if (window.confirm('möchten Sie die Datei wirklich unwiderruflich löschen?')){
window.alert('<?php
unlink($allFiles);
rmdir($fileDir));
?>');
}
else{
window.alert('Vorgang abgebrochen');
}
</script>
";
How I mentioned, it does not work, so I solved it just by not having confirmation.
Would be curious why this solution does not work.
I'm trying to update records in DB without refreshing Form. I have grid.php page with the form to display and update records. Then, I have the file update.php with the UPDATE query. The third file is js1.js with AJAX code. If I map the grid.php to update.php through action=update.php, the update query works great. But as soon as I try to include js1.js file to prevent form refreshing, it stops working.
The code is as following:
grid.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="j1.js"></script>
<?php //query.php
require_once 'header.php';
if (!$loggedin) die();
$query = "SELECT SpringMgmt.SpringMgmtID,
SpringMgmt.SpringMgmtActiveYear,
SpringMgmt.PoolID,
SpringMgmt.Notes,
SpringMgmt.SOIEstSubmitted,
SpringMgmt.EstAdditional,
SpringMgmt.SOIMeetingScheduled,
Pool.Pool,
Pool.AreaManager,
Employees.EmployeeID,
Employees.FirstName
FROM SpringMgmt
INNER JOIN Pool ON SpringMgmt.PoolID = Pool.PoolID
INNER JOIN Employees ON Employees.EmployeeID = Pool.AreaManager ";
$result = mysql_query($query);
echo "OK</div>";
if (!$result) die ("Database access failed0: " . mysql_error());
//TABLE AND ITS HEADING
echo '<table id="header" cellpadding="0" cellspacing="0" border="0" >';
echo "
<tr>
<th>Pool</th>
<th>Notes</th>
<th>SO Sent</th>
<th>Est</th>
<th>Meet Date</th>
</tr>
";
while($record = mysql_fetch_array($result)){
echo "<form id='myForm' name='myForm' method=post>";
echo "<tr>";
echo "<td >$record[Pool]</td>";
echo "<td ><textarea size=4 name=Notes rows=3 cols=22>$record[Notes]</textarea> </td>";
echo "<td style=background-color:><input type=text size=3 name=SOIEstSubmitted value='$record[SOIEstSubmitted]' /></td>";
echo "<td ><textarea size=4 name=EstAdditional rows=3 cols=12>$record[EstAdditional]</textarea></td>";
echo "<td style=background-color:><input type=text size=3 name=SOIMeetingScheduled value='$record[SOIMeetingScheduled]' /></td>";
echo "<td>
<input type=hidden name='SpringMgmtID' value=$record[SpringMgmtID] />
<input type=submit name='submit' id='submit' value='Submit' />
</div></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
?>
update4.php:
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = "UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
mysql_query($UpdateQuery);
};
?>
js1.js
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Disclosure: I may sound incredibly patronizing and even mean in my response, please note that it is not my intention. I will show you how to fix the issue, but let me first add some comments about the code above along with some suggestions:
The structure of your HTML is not good: a form shouldn't be wrapping each tr, you should consider using div instead of a table, or a "table inside a form inside a cell" (the code looks as ugly as it sounds). You can read more about a similar case here: Create a HTML table where each TR is a FORM
Your SQL statement is subject to SQL injection. This is bad. Really, really bad. As I mentioned in the comments, consider changing to MySQLi or PDO and using parameterized queries. You can read more about it here: How can I prevent SQL injection in PHP?
Your HTML code is not clean. In general, your page will work because the browser will help, but trust me, that is bad programming: you'll eventually change the code, forget about it, and it will be a mess. From what I see:
There are multiple elements with the same ID (all the forms created by the loop).
There is incomplete inline CSS (background-color:).
Quotes are missing in many places.
There are a couple of closing </div> without an opening <div> (this could be OK if the opening div comes from header.php; but even if that was the case, the code would be difficult to maintain)
Finally, the solution. I hope you didn't skip all the text above and jump directly here, because it will really help you not only now but in the future.
Change these two things and your code will work (both in js1.js):
Wrap the function in a $(document).ready so it is executed when the page finishes loading.
Change the data from $("form").serialize() to $(this).serialize(), this way you will be sending only the information from the form with the button that you clicked on (instead of all the forms).
The final code for js1.js would look like this:
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Okay, so a few things I'm going to try and help you out with quickly.
Query
Your query is complicated, but I feel needlessly so. I've been doing things with MySQL for quite some time now and I can't recall a situation where I used INNER JOIN in the method you are. A much shorter syntax for your query would therefore be: SQL Aliases
$query = "SELECT s.*, p.Pool, p.AreaManager, e.EmployeeID, e.FirstName
FROM SpringMgmt as s, Pool as P, Employees as E
WHERE s.PoolID = p.PoolID AND e.EmployeeID = p.AreaManager ";
HTML
Assuming the HTML in your script is the way you want for it to be shown, here's a few things: you can escape double quotes so that they do not break your code. I would change the code inside your loop to this: Click Here to understand the ".$variable." statements I put in your code
echo "<form id=\"myForm\" name=\"myForm\" method=\"post\">";
echo "<tr>";
echo "<td data-field-id=\"pool\">".$record['Pool']."</td>";
echo "<td ><textarea data-field-id=\"notes\" size=\"4\" name=\"Notes\" rows=\"3\" cols=\"22\">".$record['Notes']."</textarea> </td>";
echo "<td style=\"background-color:\"><input data-field-id=\"submitted\" type=\"text\" size=\"3\" name=\"SOIEstSubmitted\" value=\"".$record['SOIEstSubmitted']."\" /></td>";
echo "<td ><textarea size=\"4\" data-field-id=\"additional\" name=\"EstAdditional\" rows=3 cols=\"12\">".$record['EstAdditional']."</textarea></td>";
echo "<td style=\"background-color:\"><input data-field-id=\"meetingScheduled\" type=\"text\" size=\"3\" name=\"SOIMeetingScheduled\" value=\"".$record['SOIMeetingScheduled']."\" /></td>";
echo "<td>
<input type=\"hidden\" name=\"SpringMgmtID\" value=\"$record[SpringMgmtID]\" />
<input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\" />
</div></td>";
echo "</tr>";
echo "</form>";
AJAX/Javascript Calls
This is a bit more complicated to explain. The jQuery ajax object success function can accept a few parameters to help you in your request. See this link for more explanation. Jump the section about the .done() function. One of them is the data returned FROM the request. This means that in your update4.php file, if you would output the data to the browser as a JSON object, you could then use that data back on your original page.
$(document).ready(function(){
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'update4.php',
data: $(this).serialize(),
success: function (data,successText) {
for(var x in data){
//Use tree traversing to find the input/text elements that have the data-field-id option equal to the x variable; I can't test it right now so I don't want to have this here.
}
}
});
});
});
Update4.php
As another user pointed out in the comment section, your query here is very prone to SQL Injection. Please follow the link they provided to read more.
Now, assuming you want all of the data returned back, the very last set of lines in your update4.php file should be something close to :
<?php
require_once 'header.php';
if (!$loggedin) die();
if(isset($_POST['submit'])){
$UpdateQuery = /*"UPDATE SpringMgmt
SET Notes='$_POST[Notes]',
SOIEstSubmitted='$_POST[SOIEstSubmitted]',
EstAdditional='$_POST[EstAdditional]',
SOIMeetingScheduled='$_POST[SOIMeetingScheduled]'
WHERE SpringMgmtID='$_POST[SpringMgmtID]'";
Don't do this, please use a prepared statement or mysql(i)_real_escape_string() on the data.*/
$result = mysql_query($UpdateQuery);
if($result!==false){
echo json_encode(array(
'notes'=> $_POST['Notes'],
'submitted'=> $_POST['SOIEstSubmitted'],
'additional'=>$_POST['EstAdditional'],
'meetingScheduled'=>$_POST['SOIMeetingScheduled']
));
}
};
NOTE I do NOT recommend doing this. You should move these $_POST variables into other variables that you have properly sanitized. NEVER assume that your users have no knowledge of web technologies. Always, ALWAYS assume the user is someone who has the malicious intent to steal the data from your database. Therefore, ALWAYS check user-inputted data. The only reason I have set this up is because you seem like you are fairly new to these aspects of web development and with all of the other information I've presented I don't want to overload you and turn you off from web development/design.
Side Note
I would suggest looking up a template engine of some variety. It is generally a better practice to have your display (HTML) and data (PHP) as separate as possible. The only template engines I've used previously were a modified version of PhpBB 3's template engine, and Smarty (which the phpBB team based their template engine on).
Since beginning to type this I've seen another answer posted and read it quickly. I think both of us address slightly different portions of your overall problem, so I will give this post to you as a reference, though I think the other user's answer is a bit better than mine is. I repeat his sentiment though, if I sound condescending or mean, I don't mean to.
Also, as I'm sure someone will or has pointed out to you, get in the habit of using mysqli_* functions as mysql_ will be deprecated (no longer usable) in coming versions of PHP.
i am calling a javascript for image gallery and php on a single page.
let me show you some code to make things clear:
PHP
echo "<form method = post action = 'user_submit.php'>";
// get possible answers using question ID
$query = "SELECT aid, atitle FROM answers WHERE qid = '$qid' ORDER BY aid ASC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo "<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>";
echo "<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th".$row->aid.".jpg' /> </a>";
echo "<input type = hidden name = aid id = rd".$row->aid." value = ".$row->aid.">".$row->atitle."</input>";
echo "</div>";
}
echo "<input type = hidden name = qid value = '".$qid."'>";
echo "<br/>";
echo "<input type = submit name = submit value = 'Vote!'>";
}
echo '</form>';
}
the above code fetches object ids and places jpeg images accordingly (thumbnails).
now when i click on these thumbnails the javascript opens an overlay to display the large version. i want to pass the value of $row->aid to javascript.
then from the javascript i want to fill out a form and pass the $row->aid and the form to user_submit.php to add it to the DB.
i am new to php. please help me out.
You can write a variable, object or array literal declaration to your javascipt file or to a <script> element in a HTML file, as kiamlaluno correctly said. but i would suggest, (1) use the var keyword and (2) consider using a separate namespace.
If you have several things to tell the JS, it's handy to put them in a PHP hash and json_encode() and then write the encoded string to your output. This takes care of the namespace and correct escaping of the data. For example:
<?php
$jsdata = array(
'this' => "It\"s gone.\nWhat?",
'that' => array(1,3,2),
'another' => 0x2f );
$jsdata = json_encode($jsdata);
?>
<html>
<head></head>
<body>
<script type="text/javascript">
var thedata = <?php echo "$jsdata;" ?>
window.console.log(thedata);
</script>
</body>
</html>
Try that and look at the javascript console to see if it works.
EDIT: Another reason I like this approach is because you can use PHP's array handling conveniences to construct an arbitrarily complex $jsdata while not worrying about escaping issues and only consuming one global JS object name.
First of all, you don't need to echo everything. Something like this is just as valid:
while ($row = mysql_fetch_object($result)) { ?>
<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>
<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th<?=$row->aid?>jpg' /> </a>
<?php ...
In this case, uses php's echo shortcut tag to echo the value of the contents. It is equivalent to <?php echo $some_variable ?> .
Second, I don't actually see any JavaScript code in your question. But to accomplish what it sounds like you want to do, you can make an HTML form with a SINGLE hidden input whose value is set by selecting one of your images, and then have that form submit to user_submit.php.
The value-setting can happen in a number of ways, which is really up to you. But suppose you wanted it to happen when the user clicked an image. Then you could set the onClick event inside the img tag, like onclick="hidden_input.value='<?=$row->aid?>'"
There are many ways to pass data to JavaScript; the easier is the following:
<script>
aid = <?php print $row->aid; ?>
// The rest of the script
</script>
I only wrote the necessary code, without even write all the attributes for the tag SCRIPT.