Ajax is not working on my customize component in joomla - javascript

I'm having problem on my joomla article which i customize the code with Sourcerer.
Here is some of my example code for the ajax javascript:
<script type="text/javascript">
function showBox1(element) {
document.getElementById('hideBox1').style.display = "";
if (element == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q=" + element, true);
xmlhttp.send();
}
</script>
The code for passing the value to the function is here:
<?php
// Get default database object
$db = JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid') . '=' . $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if ($results) {
foreach ($results as $result) {
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' id ='campusID' name='campusID' value='$result->campusid' onChange='showBox1(this.value)'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
} else {
echo 'Error';
}
?>
Here is my getuser.php code:
<?php
$q = intval($_GET['q']);
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] ); // define JPATH_BASE on the external file
require_once( JPATH_BASE . DS . 'libraries' . DS . 'import.php' ); // framework
require_once( JPATH_BASE . DS . 'configuration.php' ); // config file
$db = JFactory::getDBO();
$sql="SELECT courseid FROM course WHERE campusid = '".$q."'";
// Build the query
$query->select($db->quoteName('courseid'));
$query->from($db->quoteName('course'));
$query->where($db->quoteName('campusid').'='. $db->quote($q)); //This later must change to retrieve id from current user
// Set the query for the DB oject to execute
$db->setQuery($query);// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo $result->courseid;
}
}
else{ echo 'Error';}
?>
Is there any mistake i had made? Because it does not show up the output i want which i refer the code from here http://www.w3schools.com/php/php_ajax_database.asp. Sorry if any inconvenience cause because i still new to joomla and php ajax.

xmlhttp.open("GET","home/matedis/public_html/joomla/Add_Edit_Intake/getuser.php?q="+element,true);
This is real path of public_html? No..

Related

Multiple XMLHttpRequest in one page

I have a situation where I am making the following requests and for some reason only one of them is working?
The expected result is that the second div which is populated by filter2 will bring in the necessary information, however this is not working even though this is following the same logic as filter 1?
The code for the actual requests is here:
Request 1:
function show1(str) {
if (str == "") {
document.getElementById("id1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter1.php?q=" + str, true);
xmlhttp.send();
}
Request 2:
function show2(str) {
if (str == "") {
document.getElementById("id2").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id2").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter2.php?p=" + str, true);
xmlhttp.send();
}
The php code is as follows for both of the requests is as follows:
Filter1:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$q = strval($_GET['q']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE type = '".$q."'";
$result = mysqli_query($mysqli,$search);
echo "<ul id=\"list\">";
while($row = mysqli_fetch_array($result)) {
echo "<li>";
echo "<a class=\"class\">" . $row['column'] . "</a>";
echo "<a class=\"class\"><strong>" . $row['column'] . "</strong></a>";
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(this.value)\" value=\"" . $row['column'] . "\" class=\"class\"></button>";
echo "</li>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
Filter2:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$p = strval($_GET['p']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE name = '".$p."'";
$result = mysqli_query($mysqli,$search);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr id=\"id\"><td><strong>" . $row['column'] . "</strong></td></tr>";
echo "<tr id=\"id\"><td>TestContact</td></tr>";
echo "<tr id=\"id\"><td>" . $row['column'] . "</td></tr>";
echo "<tr id=\"id\"><td>Website ></td></tr>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
I am not sure if this is a common mistake or I have some kind of clash/stupid syntax error, but this is driving me crazy and I would be forever grateful for anyone to help?
Like I said in a comment ( and was also stated in the 1st comment by #jcubic ) an img element doesn't have a value attribute which is, I suspect, the reason your function is passing undefined
Instead you can use a dataset attribute and alter the parameter passed to the inline function / event handler:
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(event)\" data-value=\"" . $row['column'] . "\" class=\"class\"></button>";
and the javascript function
/* passing event allows access to event.target amongst other things - this is useful */
function show2( e ){
var el=e.target;
var str=el.dataset.value;
if( str )/* etc */
}
that said you'd be much better creating a generic ajax function ( or better yet look into the fetch api ) and write wrapper functions for each use case.

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.

How to save data which is inside a table dynamically created using JavaScript to database

function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});

Calling a PHP function from inside javascript?

Here is my javascript code
<script>
$(document).ready(function(){
$(".five").click(function(){
<?php echo updatepoints();?>
});
});
</script>
Here is my php code
<?php
function updatepoints() {
mysql_connect("localhost","user","password") or die (mysql_error());
mysql_select_db("database") or die ("Cannot connect to database");
$query = mysql_query("SELECT *from member WHERE username='" . $_SESSION["username"] . "'");
$row=mysql_fetch_array($query);
$points = $row["points"];
$points = $points + 5;
mysql_query("UPDATE member set points='" . $points . "' WHERE username='" . $_SESSION["username"] . "'");
}
?>
Both these codes are on same page one below other. This does not seem to update the values. How should I proceed?
Here, try this:
Sidenote: content.php will be your SQL file, which is being called by xmlhttp.open("GET","content.php",true);.
This will work, assuming your SQL is already good.
<!doctype html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","content.php",true);
xmlhttp.send();
}
</script>
</head>
</head>
<body>
<script>
setInterval(loadXMLDoc,5000);
</script>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
Create a file called ajax_update.php . Inside that file add your function and user ajax to call that function.
ajax_update.php
<?php
function updatepoints() {
mysql_connect("localhost","user","password") or die (mysql_error());
mysql_select_db("database") or die ("Cannot connect to database");
$query = mysql_query("SELECT *from member WHERE username='" . $_SESSION["username"] . "'");
$row=mysql_fetch_array($query);
$points = $row["points"];
$points = $points + 5;
mysql_query("UPDATE member set points='" . $points . "' WHERE username='" . $_SESSION["username"] . "'");
}
if($_POST['action_type'] == 'update') {
updatepoints();
}
?>
change your script like this
<script>
$(document).ready(function(){
$(".five").click(function(){
$.ajax({
type : "POST",
url : "ajax_update.php",
data : {action_type:"update"},
success : function(html){
}
});
});
});
</script>
You can change your ajax PHP file as separate file for ajax and class. Add functions in class. Let it be neat and clear
You can use jQuery, it makes things simpler:
<script>
$(document).ready(function(){
$.post("update_user_points.php", { username: 'someuser' }, function(response) {
console.log(response);//check your console
});
});
</script>
I didn't see how you start the session, but this example passes the username value from the client to PHP. if you just incrementing the points by 5 you can do it in a better way check this:
<?php
if(isset($_POST['username']){
function updatepoints($username) {
mysql_connect("localhost","user","password") or die (mysql_error());
mysql_select_db("database") or die ("Cannot connect to database");
$query = sprintf("UPDATE member set points = points + 5 WHERE username='%s'",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}else{
echo 'update success';
}
}
//call the function
updatepoints($_POST['username']);
}
?>

How to pass two php variables in JavaScript function

This is my code for fetching values from DB in a Table.
After fetching values I'm simply taking the ID of user in function to Activate and Deactivate that user.
<?php
$sql = "SELECT * FROM registration";
$result = mysqli_query($con, $sql);
while ($test = mysqli_fetch_array($result)) {
$id = $test['id'];
$status = $test['status'];
echo "<tr align='center'>";
echo"<td><font color='black'>".$test['username']."</font></td>";
echo"<td><font color='black'>".$test['firstname']." " .$test['lastname'] .
"</font></td>";
echo"<td><font color='black'>" . $test['status'] . "</font></td>";
echo"<td><a id='link' onclick=\"activate(" . $id . ");\">Activate</a></td>";
echo"<td><a id='link' onclick=\"deactivate(" . $id . ");\">Deactivate</a></td>";
echo "</tr>";
}
?>
Now, this is my AJAX code for activate()
function activate(item)
{
var id = item;
if (confirm("Do you wants to Activate user"))
{
$("#wait").css("display", "block");
var id = item;
var status = status;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.location.reload();
}
}
xmlhttp.open("GET", "php/update_act.php?id=" + id + "&req=activate", true);
xmlhttp.send();
}
}
I want to write or update the activate function so that,
I will get the current status of the user so that I'll check if the User is already Activated or not.
And if user is already Activated it should prompt me that this user is already activated else I should be able to Activate the User.
I assume you want to pass $status in the function as well so you can do something as
In Php code
echo '<td><a id="link" onclick="activate(\''.$id.'\',\''.$status.'\');">Activate</a></td>';
And you can change the JS function signature as
In Javascript
function activate(yourItem,uStatus){ }

Categories

Resources