I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.
First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"
I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:
Connect to the database
Choose Columns/Tables
GET Data from Columns/Tables
Create HTML Form to Display Result of MYSQL Query
Create Dropdown Selection List of Query Results
Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values
This is my code so far:
<div class="form-group" style="margin: 30px 10%;">
<h3>Create Zazzle Products</h3><p><h4>Select a Template Category</h4>
<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
<?php
//connection
$con = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
$cg = $_GET['cim_template_cg'];
$coverimage_iid = $_GET['main_image'];
$result = mysqli_query($con,$sql);
?>
<select name="selectZcategories" id="selectZcategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
<button onclick="ajaxFunction();">Submit</button><br /><br />
<?php
<script>
function ajaxFunction() {
var selectedData=$("#selectZcategories option:selected").val();
$.ajax({
type : "POST",
url: "select_zproduct.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
</script>
?>
<?php
echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
echo $cg = ['cim_template_cg'];
echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
echo $coverimage_iid = ['main_image'];
echo $product_text = "&t_text1_txt=Welcome";
?>
</form>
</div>
// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$cg=$selecterArrayData[0];
$coverimage_iid=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:
Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation
Assign proper $variables to database dropdown SELECTION Result to be used in the URL above
Concatenate all $variables
Parse all $variables
Embed final encoded URL into button
Use thumbnail of active page main_image as button image src
What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!
So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>
Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
alert(html);
}
})
}
PHP:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
echo 'cg: '.$categoryID.' img path: '.$imagePath;
?>
<script>
//window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* #package J2Store
* #copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* #license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;
//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>
<div class="cg_values">
<form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
<select name="cg" class="cg">
<?php foreach($cg_values as $cg_value): ?>
<option value="<?php echo $cg_value->cim_template_cg; ?>">
<?php echo $cg_value->cim_template_cgname; ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="rf" value="238500395169782226" />
<input type="hidden" name="ax" value="DesignBlast" />
<input type="hidden" name="sr" value="250508120301240636" />
<input type="hidden" name="t__useQpc" value="false" />
<input type="hidden" name="ed" value="true" />
<input type="hidden" name="t__smart" value="false" />
<input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>" />
<input type="hidden" name="tc" value="" />
<input type="hidden" name="ic" value="" />
<input type="hidden" name="t_text1_txt" value="" />
<input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
<input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
</form>
</div>
<?php endif; ?>
So I didn't found what I was looking for in last two days.
To be clear I have a table "tracks" in my database.
So I can show from "tracks" the "demo" field wich is an audio file "url"..
<?= $tracks['demo']; ?>
I have multiple url's but then I need to replace the a href
<a href="<?php echo $tracks['demo'];?>"
in a logical way.
In simple terms it's like I want to click on button 1 that loads
url 1 into this a href with the ID, title field from that track.
When you press button 2 you need to load another url and replace url 1 with url2.
I tried many ways including javascript but it won't work.
Problem now is that when I list 4 items it always loads the latest "URL" i have posted in my source code. :)
When I echo out <?php echo $tracks['demo]; ?> on all items I can see the correct url's so the functionality to replace the url is my issue.
* I basically want to load many mp3 url's in a player I made in the footer of my website. It works by hardcoding the urls in the url field but this is not what it should be... *
Code:
<?php while($tracks = mysqli_fetch_assoc($muziek)) : ?>
<div class="col-md-2 viny" id="muziek">
<h4><?= $tracks['title']; ?></h4>
<img src="<?= $tracks['img']; ?>"
alt=" <?= $tracks['title']; ?> />
<p class="artist">Artist: <?= $tracks['artist']; ?></p>
</div>
<?= $tracks['demo'] = $audiourl ; ?>
<button type="button" onclick="play">Play</button>
</div>
<?php endwhile; ?>
*THIS LOOPS PERFECT FOR ALL ITEMS TRACKS ARE LISTED PERFECT *
In my player I have
<a href="<?php echo $audiourl;?>" ><?= $tracks['artist']; ?></b> - <?= $tracks['title']; ?></a>
function play(){
I'm not good at JS... And this is my issue because it now loads the latest output from the php loop...
}
I don't know how you are replacing it but
Why not pass the audio in the function. Here like this
<button type="button" onclick="play(<?= $tracks['demo'] = $audiourl ; ?>)">Play</button>
assign a id to anchor tag
<a id="someId" href="<?php echo $audiourl;?>" ><?= $tracks['artist']; ?></b> - <?= $tracks['title']; ?></a>
and in the play function, you receive it like this
function play(audioUrl){
}
and change the href like this in the play function
If you are using jquery
$('#someId').attr("href", audioUrl);
sometimes the above does not works. Can't remember why but if that does not works try this
$('#someId').href = audioUrl
If you are using javascript
document.getElementById('abcd').href = audioUrl
So I tried many things but I had many issues with the player it's js file using the same id's and so on.
The new logic I tried out seems to work:
<form action="" method="POST">
<input type="submit" value="Play" name="Play">
</form>
<?php
if (isset($_POST["Play"]))
{
echo $tracks['demo'];
}else{
echo ' ';
}
?>
There is more going on but I tried to write it down as simple as this to show the logic. All Track url's are hidden and when the page loads there is an empty $audiourl by default loaded in the a href from my audioplayer. By clicking the button play I show the url in the source but not on the site.
Then the latest $audiourl variable changes to this value.
I am trying to explain this as clearly as possible. What I would like to to do in jQuery and my jQuery is not that good sadly, but I am trying to have user input several fields with information. Then on the same page use those inputs are far so I can call a jQuery function from an external page to start a bit of code.
Below is my code. Everything works except for the part where the user is inputting his information that has to be send along as data in ajax with do all sorts of others things later on in a PHP function that I have written.
My code is so far:
<input name="myField" id="myField" type="text"><br/>
<div id="output"></div>
<script type="text/javascript">
$('#myField').keypress(function() {
var txtVal = this.value;
$("#output").text(txtVal);
console.log(txtVal);
});
var value= '<?php echo $connect_d["value"] ?>';
var value= '<?php echo $connect_d["value"] ?>';
var value= '<?php echo $connect_d["value"] ?>';
var value = 'txtVal';
$(document).load(function(){
value();
});
</script>
<div class=""><p>To install <?php echo"$value"; ?> please click the button below to start the process. </p></div>
<input type="button" class="btn btn-outline btn-success btn-lg btn-block blinstbtn" onclick="<?php echo"$value"; ?>();" value="Start <?php echo"$value"; ?> install process" />
I hope this makes sense, but in short, i need people to fill in some fields and sent that over to an js function that i call in from an external file so I can have that function start a php function.
I only need help with how to make var out of the input fields so the function I have written in jQuery and ajax and use it right away when I click the button to start the install process.
Thanks for the help.
After looking around on a Google without any success, i feel posting here may be a good idea as I have used this site to answer previous questions.
Anyways, I am currently working on an HTML5 canvas game using; PHP, MYSQL, Html5, and JavaScript.
I have MYSQL databases setup and an PHP page displaying player high-scores, and usernames.
My question is how would I go about displaying the high-scores inside the canvas once the game is over.
As well as saving the high score when the game ends. I've looked on W3SCHOOLS site about AJAX but I'm still unsure of what codes to use inside the JavaScript file.
These are my php/script codes. or at-least the ones that are relevant:
// Here's the savescore.php file
<?php
include 'connect.php';
$user_score = ($_POST['user_score']);
$user_name = ($_POST['user_name']);
if(mysql_query("INSERT INTO users VALUES('$user_name','$user_score')"))
echo "Score Successfully Saved";
else
echo "Score Saving Failed";
?>
// Here's some of the index.php file
<link rel="stylesheet" href="css.css">
</HEAD>
<body>
<div id="menu">
<a class="item" href="/index.php">Home</a>
<?php
include 'connect.php';
session_start();
if($_SESSION['signed_in'])
{
echo 'Hello ' . $_SESSION['user_name'] . '. Not you? Sign out';
include 'chat.php';
}
else
{
echo 'Sign in or create an account.';
}
?>
</div>
<BODY>
<canvas id="canvasGAMEOVER" width="800" height="599"> </canvas>
<script src="game.js"> </script>
// here's whats inside inside game.js... well the part I want to be able to save score
var score = 0;
function drawGAMEOVER() {
}
I have used google and looked at tutorials for AJAX, I found I have been able to connect to the server using AJAX only using:
<form action="savescore.php">
user_name: <input type="text" name="user_name"><br>
user_score: <input type="text" name="user_score"><br>
<input type="submit" value="Submit">
</form>
inside the index.php page, but I am not sure if its possible to grab the 'user_name' they logged in with (displayed on the index.php page) as well as this.score (displayed inside the javascript file.)
Could anyone tell me how this is possible... if not maybe a better way of doing this?
Any help/reply is much appreciated thanks in advance.
If you are using jquery you can use $.get to get all highscores.
http://api.jquery.com/jQuery.get/