Calling a PHP function from inside javascript? - 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']);
}
?>

Related

Output of drop down list in php mysql

I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**

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.

I want to update my webpage when some one else updates the database through another instance of the same page

I want to update my page when I update the database from another instance of the same page.But I am unable to do so. Index.php is my Home page.
The if block of the doo() function, if(x.readyState==4 && x.status==200)
never exeutes, may be because the status never becomes equal to 200.
In the console I am getting "1000 Failed to load resource: net::ERR_INSUFFICIENT_RESOURCES" . Moreover I do not understand why the update function is not waiting for 10 seconds and overflowing the stack.
I will be very obliged to get any solution and suggestions.
index.php
<html>
<head>
<title>das shuler
</title>
<script>
function foo()
{
//if (str.length==0) {
//document.getElementById("txtHint").innerHTML="";
//return;
//else {
data=document.getElementById("story").value;
alert(data);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("state change");
data=xmlhttp.responseText;
parent=document.getElementById("content");
child=document.createElement("div");
news=document.createTextNode(data);
child.appendChild(news);
parent.appendChild(child);
id=setTimeout(update(data),20);
alert("after setTimeout");
//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
alert("data sent");
xmlhttp.open("GET","populate.php?story="+data,true);
xmlhttp.send();
}
function update(str)
{
data=str;
//alert(data);
//alert("inside update");
var x=new XMLHttpRequest();
x.onreadystatechange=doo();
function doo(){
if(x.readyState==4 && x.status==200)
{
alert("here");
data=x.responseText;
if(data!=str)
{
parent=document.getElementById("content");
child=document.createElement("div");
news=document.createTextNode(data);
child.appendChild(news);
parent.appendChild(child);
}
}
x.open("GET","retrieve.php",true);
x.send()
id=setInterval(update(data),10000);
}
}
</script>
</head>
<body onload="update()">
<div id="header"><h1 style="color:grey;align:center;">das shuler</h1><hr></div>
<div id="content">
</div>
<div id="make-content"><form method="post" action="populate.php"><input type="text" name="story" id="story"><input type="button" value="post" onclick="foo()"></form></div>
</body>
populate.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$data=$_REQUEST["story"];
echo $data;
$sql = "INSERT INTO News (Data)
VALUES ('$data')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
// echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
retrieve.php
<?php
$conn=mysqli_connect("localhost","root","root","myDB");
echo "hrloo";
$sql="select Data from News ";
$q=mysqli_query($conn,$sql);
$data=mysqli_fetch_assoc($q);
echo $data;
mysqli_close($conn);
?>
Your code seems to be broken. The setTimeout function logic is not working properly. The alert() right after setTimeout will fire on page load as it is not included in the function on which you are setting the timeout.
Also setTimeout() takes time in milliseconds. Try putting 10,000 if you need a 10 sec break on window.
Refer this:
setTimeout(function(){ alert("after setTimeout"); },10000);

how to assign ajax response in two different textbox elements ?(different values in each textbox)

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sr_db", $con);
$sql="SELECT * FROM client_info WHERE name like '".$q."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['address'];
echo $row['balance'];
mysql_close($con);
?>
i want to display the two echo line in two different textbox on my main page...
i have also written ajax code lines and it also run.... but don't know how display values of both the echo line in two different textbox
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("address").value="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
document.getElementById("address").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_search_address.php?q="+str,true);
xmlhttp.send();
}
</script>
You should probably consider sending the response from PHP with json_encode() and parsing the response:
https://mathiasbynens.be/notes/xhr-responsetype-json
Short of that, you can set a delimiter in PHP, and split with javascript. Ex:
<?php
echo $row['address'] . "|" . $row['balance'];
?>
Javascript
values = xlmhttp.responseText.split("|");
document.getElementById("address").value=values[0];
document.getElementById("balance").value=values[1];
Get the response in json format. it work as an array when receive in ajax call, then the data can be parsed accordingly.
In server
echo json_encode(array('address' => $row['address'], 'balance' => $row['balance']));
In ajax end
$.ajax({
url: "php page url",
type: 'GET',
dataType: 'json',
success: function(json) {
$('.address').val(json.address);
$('.balance').val(json.balance);
}
});

Ajax is not working on my customize component in joomla

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..

Categories

Resources