Ok I know this can't be done using PHP and I think it's done by using Ajax/Javascript...
Unfortunately I'm very low on these and I need your help..
So I have made a <select> based on what players there are playing for the team the user has selected. It works fine, no problems.
What I need for it is a button that will add 1 XP to the player that the user has selected.
<?php
$query = mysql_query("SELECT `team` FROM `users` WHERE `username`='". $_SESSION['username'] ."'");
$row2 = mysql_fetch_assoc($query);
$result = mysql_query("SELECT `name` FROM `players` WHERE `team`='". $row2['team'] ."'");
$dropdown = "<select name='players'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name']}'>{$row['name']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<button onclick="">Support</button>
In my case, the update would look something like this:
$oldxp = mysql_query("SELECT `xp` FROM `players` WHERE `name`="the option the user selected,got stuck here");
mysql_query("UPDATE `players`SET `xp`=''". $oldxp ."' + 1' WHERE `name` = "the option the user selected, got stuck here");
So what I need is how do I get what the user has selected and replace it with that "the option user selected, got stuck here" and how do I do this in Java since I can't put that PHP code in the onclick event because it won't work?
Thanks a lot.
Change your button html
-- add a onclick function
html:
<button onclick="saveData()">Support</button>
onclick in the button send an ajax request to the server and run your query.
jquery:
function saveData(){
$.ajax({
type: "POST",
url: "your_php_page.php",
data: { name: $("select[name='players']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
php:
your_php_page.php:
$sql = "UPDATE `players`SET `xp`= `xp`+ 1 WHERE `name` = '".$_REQUEST['name']."'";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
you should not use mysql_* since it is deprecated. you should use pdo or mysqli_*
jquery ajax api doc
First off, Java and Javascript are totally different languages. They share very little except a name and their both a programming language.
You'd need to use Ajax to do this, so you'd need a PHP file on your server that the AJAX can request to run the query you're wanting. You would then use AJAX to request this file to add the XP, I suggest you use jQuery (http://jquery.com/) for AJAX calls as its much easier to use than pure javascript.
Once you have included jQuery into your site you can use the following to make an ajax call:
$.ajax({
type: 'post',
url: 'http://domain.com/myscript.php',
success: function(data){
// callback function
}
});
Documentation: https://api.jquery.com/jQuery.ajax/
You could wrap the ajax call in a function and then call that function using onclick on the button you're wanting to use.
eg:
<button onclick='javascript:ajaxCall()'>Call AJAX</button>
function ajaxCall(){
// include code above
return false; // not always essential, but I usually return false.
}
Related
I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.
I've tried using isset and POST and I get some variation of Undefined key array.
Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.
Current setup...
I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.
<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id = '" . $row['id'] . "'/>
JavaScript...
function edit(clicked_id){
var selid = clicked_id;
var seleid = selid.toString();
$.ajax({
type: 'post',
data: {name: seleid},
datatype: 'text',
success: function(data){
console.log(name);
alert("Success, data is: " + data); // This correctly returns the id of the button clicked
},
});
}
The PHP at the top of the page is...
if(isset($_POST['name']) && !empty($_POST['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?
Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.
Please help and thank you!
Try something like this in your php code :
$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
I've got a piece of javascript as follows:
$.ajax({
type:"get",
url:"http://www.orc23.com/get.php",
data: { solution: src },
datatype: "json",
success: function(returndata){
alert(returndata);
}
});
And this is the corresponding php file that interacts with mysql:
<?php
$con = mysqli_connect("orc23com.fwdsfawmsdfaysql.com","ssft","dsfss123","cookies");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db($con, "cookies");
$sql="SELECT SOLUTION FROM requests WHERE theurl = '$_GET[solution]')";
$result=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$returndata=json_encode($row);
echo $returndata;
mysqli_close($con)
?>
The variable "src" I am passing in is a URL (string) , so I believe I should be treating it in a different way b/c of the nature of an URL with all its' special characters ,,,, I am running my code and it errors out as a "null" , but when I run the appropriate sql statement query in mysql DB then the DB returns what I am expecting ..... please advise what I may be doing wrong please ?
the sql I am running is this:
SELECT solution
FROM requests
WHERE theurl = 'https://www.google.com/fskdfalkadsl?=sksdkalsk&soccer=uwiw'
;
I know it will return back to me single row with just one column , and know what to expect as the value , but I can't seem to get the "get.php" page to return anything but "null" it seems ....
You get NULL because PHP does not automatically populate the $_GET when it receives JSON formatted data, so there is nothing in $_GET['solution']. You need to capture and decode the input yourself.
Instead of:
$solution = $_GET['solution'];
You need
$data = json_decode(file_get_contents('php://input'), true);
$solution = $data['solution'];
Or something close to it.
I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}
This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.
I am very new to programming with jQuery. I've spent quite a while trying to move forward with this, and I've managed to get some of it done. But I've really hit a wall and I can't seem to find help from anywhere/anyone.
Scenario:
I am using a select box to store different music genres, which I have retrieved via PHP/MySQL.
<?php
include 'connectingDB.php';
$catSQL = "SELECT * FROM category ORDER BY catDesc";
$queryresult = mysql_query($catSQL)
or die (mysql_error());
echo "<select id= \"catID\">";
while ($row = mysql_fetch_assoc($queryresult)) {
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = \"$catID\">$catDesc</option>\n";
}
echo "</select>";
mysql_free_result($queryresult);
mysql_close($conn);
?>
When I click on a genre, I want all of the related CDs and CD information to be retrieved in JSON format and dynamically displayed in a table using AJAX (below the select box on that same page)
<?php
header('Content-type: application/json');
include 'connectingDB.php';
$category = $_REQUEST['catname'];
$sql = "SELECT `CDID`, `CDTitle`, `CDYear`, `pubID`, `CDPrice`
FROM `tiptop_cd`
INNER JOIN tiptop_category
ON tiptop_cd.catID=tiptop_category.catID
WHERE catDesc = '{$category}'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
$returned[] = $row;
}
echo json_encode($returned);
?>
All of the above code works on its own. But I'm looking to connect it all together. I think it needs to be via an onchange event in jQuery?
I've got an alert to pop up after clicking a category, but that's as far as I can get..
$(document).ready(function(){
$("#catID").change(function(){
alert("The text has been changed.");
});
});
Does it need to be in a foreach loop? Or a foreach within a foreach?
To summarize, I'm trying to understand how to: display the cds and cd information that are related to the specific category that is currently selected, in a dynamic table with ajax
Any help is massively appreciated.
hopefully this can get you started
$(document).ready(function () {
$("#catID").change(function () {
$.post("index.php?catname=" + $(this).val(), function (data) {
var table = $('<table></table>'); //create table
$.each(data, function (index, value) { //loop through array
var row = $('<tr></tr>'); //create row
var cell1 = $("<td></td>").val(value.CDID); //create cell append value
//etc
row.append(cell1); //append cell to row
table.append(row); //append row to table
});
$('#div').append(table); //append table to your dom wherever you want
});
});
});
You may want to use AJAX for this purpose. Ajax will allow you to send the user's choice (ie. the dropdown selection) to a back-end PHP file.
The PHP file will process the received data (ie. the user's choice) and perform a database lookup based on that info. It will take the result from db and construct (in a variable) the required HTML for the table, and then echo back the contents of that variable -- which will be received in the AJAX procedure's success: (or .done() to use promise syntax) function.
INSIDE the success/done function, you can use received data. For example, you can use the jQuery .html() method to replace the contents of a specified DIV with the HTML you received.
My approach would differ from the other proposed solutions in the following ways:
I prefer using the full $.ajax() syntax, as it allows for greater structure, which makes it somewhat easier to understand/manipulate at first. Note that .post(), .get() and .load() are all shortcut forms of $.ajax() that make certain assumptions in order to streamline the process. I suggest learning the $.ajax() format first, and then utilizing the others. Having done gazillions of ajax blocks myself, I continue to use $.ajax() most times. Perhaps it is a preference, but I find it much easier to use/read/review -- and it also allows additional params that the others do not, which makes it more flexible and useful**.
It is necessary to use a second .PHP file to act as your ajax processor. You cannot use the same .PHP file that contains your AJAX code block. See this answer.
The place to construct the HTML table is in the PHP (processor file). As mentioned, construct it all in a variable and then, at the end, output that variable:
Note how the $r variable is constructed in the while loop, and only ECHOed out at the end.
$aContact_info = mysql_query("SELECT * FROM `contacts`");
$r = '<table>';
while ($rrow = mysql_fetch_array($aContact_info)) {
$r .= '<tr>
<td>
Name:<br/>
<input type="text" id="first_name" name="first_name" value="'.$rrow['first_name'].'">
<input type="text" id="last_name" name="last_name" value="'.$rrow['last_name'].'">
</td>
<td>
Email:<br/>
<input type="text" id="email" name="email" value="'.$rrow['email1'].'">
</td>
<td>
Cell Phone:<br/>
<input type="text" id="cell_phone" name="cell_phone" value="'.$rrow['cell_phone'].'">
</td>
</tr>
';
}
$r .= '</table>';
echo $r;
Here are some examples that should help:
Simple explanation of AJAX
Example with MySQL lookup in PHP Processor file
** Differences between .get() and .post() and $.ajax():
GET vs POST in AJAX calls
Kevin Chisholm
Sychronous AJAX
another (faster) method would be to return an html table as a string and inject it into the DOM. generate the table in your PHP handler, then do $('#div').load('/index.php?catname=catname'); or do $.get like below
$(document).ready(function () {
$("#catID").change(function () {
$.get({
url: 'index.php',
data: { catname: $(this).val() }
dataType: 'html',
success: function (html) {
$('#div').html(html);
},
error: function (xhr, err) { displayErrorMessage("Error: \n\nreadyState: " + xhr.readyState + "\nstatus: " + xhr.status + "\nresponseText: " + xhr.responseText, 'nosave'); }
});
});
});