Calling function in alert in Joomla - javascript

I am facing an problem. I have a module mod_vodbalance. I have created a function balanceDeduct in that module. Also i have created a page with buyNow button. When I click on buyNow button, it shows an comfirm with ok and cancel. I want to call that function balanceDeduct when user click on ok button and proceed to another page. The Code I am using is this:
function deductBalance()
{
$db = JFactory::getDBO();
$result = null;
$user = JFactory::getUser();
if ($user->guest) {
return false;
}
$query = 'SELECT credit' .
' FROM #__vodes_credits' .
' WHERE userid = ' . (int) $user->id;
$db->setQuery($query);
$result = $db->loadResult();
$result_final=$result-10;
$query = 'update #__vodes_credits SET credit='.$result_final.
' WHERE userid = ' . (int) $user->id;
$db->setQuery($query);
$result = $db->loadResult();
if ($db->getErrorNum()) {
JError::raiseWarning( 500, $db->stderr() );
}
return $result;
}
I want to call this function on comfirm box. Please help me to sought it out.

Related

Integrate 2 functions for 1 button and keep input fields disabled after reload

A) I would like to have 2 different functions for 1 button.
For first click function 1 should start, for second click function 2, for third click function 1, fourth click function 2 ...
For now I need 2 buttons, one disables and the other one enables the possibility to input data in a form field. The best would be to have both functions for 1 button (as explained above).
Does anyone has an idea how to do that?
B) All data get saved and can be reopened in the datamanagementsystem. I would like that disabled fields stay disabled (after reopening the form again) for input. Is there a possibility to do so?
<script>
var nav = false;
function disable18() {
document.getElementById("field1").style.color = "red";
document.getElementById("field1").value = "X";;
document.getElementById("field1").disabled = true;
nav = true;
}
function enable18() {
document.getElementById("field1").disabled = false;
document.getElementById("field1").value = "";
document.getElementById("field1").style.color = "black";
nav = false;
}
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
</script>
How I get the data from database:
<?php
session_start();
require_once 'sc/functions.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
// php search data in mysql database using PDO
// set data in input text
$user = "xxx";
$pass = "xxxx";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', $user, $pass); //mysql:host=localhost;dbname=test_db","root","")
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$ID = $_POST['ID'];
// mysql search query
$pdoQuery = "SELECT * FROM dabase WHERE ID = :ID";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your ID to the query ID
$pdoExec = $pdoResult->execute(array(":ID"=>$ID));
if($pdoExec)
{
// if ID exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$ID = $row['ID'];
$field1 = $row['field1'];
}
}
// if the id not exist
// show a message and clear inputs
else{
header( "Location: nodatasearch.php" ); die;
}
}else{
echo 'ERROR Data Not Inserted';
}
} ?>
Submitting/Saving data:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require("php/tc.php");
$ID = $_POST['ID'];
$field1 = $_POST['field1'];
$sql = "UPDATE pdbase SET
field1 = :field1
WHERE ID = :ID";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ID', $ID);
$stmt->bindValue(':field1', $field1);
$stmt->execute();
// var_dump($_POST['user']);
?>
My asnwer will solve problem A however problem B is a little more complicated. You will need a flag for this, for example this is your html
<input type="text" id="field1">
<button id="toggler" class="btn btn-success" onclick="toggleNav()">Toggler</button>
in your js start off with creating your flag, let's set it to false
var nav = false;
When your 1st function is called change your flag to true
function disable18() {
document.getElementById("field1").disabled = true;
nav = true;
}
Now for the second function we will set it back to false
function enable18() {
document.getElementById("field1").disabled = false;
nav = false;
}
Now we create the function that toogles between the 2 of them
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
After that, all that's left is make sure your toggleNav() function is in the onclick() in your button. Now for problem B I have more questions than answers. Need more details about how do you want to do achieve that

How to fetch questions ony by one on save and next buttons

I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.
I want to use ajax to insert data into database after clicking next button by using file read and write function.
$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {
<h4><? echo $sha['id'];?></h4>
here's simple way to do it
first get question from database then put a button to the next id
<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
$rows++;
$stmt->close();
$mysqli->close();
if($rows === 0) {
echo 'qustion not found';
} else {
// output qustion
// button
echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}

Printing into a pop-up, instead on main window

I have this function which shows all my articles titles from 'Articles' database.
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
// die("Functie terminata cu succes! :)");
// die(json_encode(array("mesaj" => "Entered data successfully ")));
}
This is the function in javascript.
function show()
{
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
alert(mesaj);
});
}
PROBLEM: because of the alert(mesaj), it shows the string $html into a pop-up, not on my main window, as I wish!
HOW can I modify my functions so the articles list will show on m window?
you have to give a container id to which it will set the data. Bellow i put it in document.
function show()
{
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
$(document).html(mesaj);
});
}

Get the value of the click number in order to update the clicked data

we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};

Getting javascript response from a PHP login function

public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
Hi everyone,
im in a spot of bother regarding a conversion, I need to get a Javascript response from the above php function by calling that php function from another script(HTML)...
P.S
i saw an example in the internet like the below, cant i use method like below get the call
client.sendRequest('hello', null, { 'async': false }, function(rtn) {
if (rtn.isError())
document.write('<li>Request hello error: ' + rtn.getErrorMessage() + "</li>");
else
document.write('<li>Request hello result: ' + rtn.getResult() + "</li>");
});
If you are using ajax return response in json format
return json_encode($res);
Or just print response in script tag
<script>
var res = <?php echo json_encode(login('username','password')); ?>
</script>

Categories