I have a drop down in html.
When I change the value of the drop down I want to store the selected value in a php variable
How can i achieve this ?
Technically it is impossible. PHP is server side, HTML is client side. When a user calls up a URL the server runs the PHP which gets sent to the HTML, so you can not go backwards.
You can however use ajax to get the value of the select box and use it in some meaningful way. What are you wanting to do with this variable?
EDIT
Using jQuery I would send the value of the select box to an ajax file, and then have the ajax file create the text box if the value is what you want it to be. Here is an example.
$("#selectEle").change(function() {
$.ajax({
type: "POST",
url: "yourajaxpage.ajax.php",
data: {selectVal: $(this).val()},
success: function(response) {
$("#textBoxArea").html(response);
},
error: function() { alert("Ajax request failed."); }
}
});
You will grab the value in your ajax page using $_POST['selectVal']. Test that value there, and create an HTML textbox which gets sent back to the success function.
Without submitting the form, this can be done using an AJAX call (see libraries like Prototype and MooTools for easy methods) all off the onchange HTML attribute of your select tag.
yes, as suggested a javascript/ajax implementation would be a good fit here.
I use jQuery but I'm assuming it can be achieved in other libraries.
Anyway .change() in jQuery would work for this. When a user changes the selected index of the drop down it triggers the the .change() function and you would insert more javascript conde inside of this function to make the needed changes.
If you wanted you could find out the selected index or get the value of the selected index and put in logic based around that to load your textbox (also using javascript).
Something like
$('target').change(function() {
var value = $('target').val(); // gets the selected value
if(value == "what you want it to be")
{
// load data into a div from your php file.
$('#loading_div').load('ajax/test.html');
}
});
That should definitely get you started.
Related
I have a dropdown selector on a page that allows a user to select a template type (for example, "human" or "dog").
Based on what template is selected, different fields will need to populate below the dropdown (for example, text fields for "parents names" or a dropdown list for "breed") that are unique to each template.
I will have a button that the user will click once the data fields are put in that will output data to an "output div" section of the same page when clicked (no POSTing data as it's not being saved). The output will have different output logic based on the selected template (for example, "I'm a human named X" or "I'm a dog, my breed is Y").
My real program will be more complex and each template will have a php class that stores all of the logic. Since I will be dealing with both php objects and variables gathered by jquery, what's the best way to let them interact?
For 1., I know I can do something easy like -
var selected_template = $('#my-template-dropdown :selected').text();
if (selected_template == 'Human'){
$('#my-fields').html('<?php echo HumanTemplate::render_fields(); ?>');
}
which is easy enough, but for 2. I need to pass variables from jquery to php, then return output back to jquery.
I would like some advice on the easiest way to do this before I start down the wrong path.
HTML
Allow the user to select the template type:
<form>
<select id="my-template-dropdown" name='template'>
<option value="dogs">Dogs</option>
<option value="humans">Humans</option>
</select>
</form>
<div id="my-fields"><div>
<div id="output"><div>
jQuery
Any time the user changes the template selection, request new content to display via AJAX, and insert it on the current page so the page does not have to refresh:
$('#my-template-dropdown').on('change', function() {
var template = $(this).val();
$.ajax({
url: 'http://your-site/path/to/' + template,
success: function(resp) {
$('#my-fields').html(resp);
}
});
});
PHP
http://your-site/path/to/template simply generates the HTML you want to display for that template, eg (just an example, don't know if this is suitable for your app):
if ($template == 'humans') {
echo HumanTemplate::render_fields();
} else if ($template == 'dogs') {
echo DogTemplate::render_fields();
}
For part 2, assuming all the logic you refer to is in the template rendered by PHP, you could then handle it with jQuery. This is pretty crude, you probably need something more sophisticated (eg a full template which you swap variables into?), but you get the idea:
$('#output').on('click', 'button', function(e) {
e.preventDefault();
// fields in your template which the user will fill
var species = $('#species').val(),
title = $('#title').val();
// Probably better to have this text as a template in your source
$('#output').html("I'm a " + species + ' named ' + title);
});
NOTE the gotcha in the event handler. Event handlers will only attach to elements that exist at the time the handler is defined. Since the content is injected after page load, an event handler like $('#button).on('click', function() {... would have no effect when clicking a button inserted via AJAX. The syntax here attaches to the parent #output div, which does exist at page load, and filters for clicks on a button. See the jQuery event delegation docs for more info.
Another option would be to POST the submitted data to some PHP controller, which generates and returns the output. This way all your logic is in the one place. For example, here the user's click will query the same PHP file which generated the initial template, this time including the values the user has entered. It could then generate the required output and return it, to be inserted on the page. You'd need to update the PHP so it can determine which of these cases it is handling (eg hidden field?); alternatively if you wanted to keep those separate you could hit another PHP file all together.
$('#output').on('click', 'button', function(e) {
var template = $('#my-template-dropdown').val(),
$form = $('form'),
data = $form.serialize(); // Values from all fields user has entered
$.ajax({
url: 'http://your-site/path/to/' + template,
data: data,
success: function(resp) {
$('#output').html(resp);
}
});
});
The best way to pass data from jQuery to PHP, is by using AJAX.
Mozilla has an excellent guide on getting started, that i recommend you follow.
An example of how you can achieve what you are requesting, is by trying the following:
var selected_template = $('#my-template-dropdown :selected').text();
var ajaxurl = 'ajax.php',
data = {'select_template': selected_template };
$.post(ajaxurl, data, function (response) {
console.log(response);
});
On the PHP end (Ajax.php in my example) It could look something like this
if(isset($_POST['select_template'])) {
// do something with the input from jQuery
$selected_template = $_POST['select_template'];
// return the result back to the client
echo $seleted_template;
}
?>
$selected_template will be sent back to the client, and response in the AJAX function will be whatever the server returned. So the console.log(response) should display whatever was being sent to the server
You can have a look to the function wp_localize_script.
This function make available PHP datas to JS files on the page load through the wp_enqueue_scripts action.
This will not work like an Ajax request and only populate data for a specific handle on page load. But you can mix this method with ajax in the same script.
Hope it helps even it doesn't seems to fit to your case.
As your class not fires on page load, you can use the action wp_ajax_{custom _action} and wp_ajax_nopriv_{custom_action} . For example, that's usually used to populate multiple dropdown, each time an event is trigger by the user, a php function returns result the js script.
I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});
I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)
I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);
I have a table where one field is titled a secure password. In this field, there is an input button that calls an AJAX function. The AJAX function on return updates the password in the secured password field. This updates the DOM value for that field.
On this same page I have another function which uses Javascript to parse all the elements in the table into an array. The problem is the Javascript function is writing what was originally in the secure password field rather than what the AJAX function has updated it to.
It seems as though Javascript does not pull the current DOM value but the DOM value when the page was loaded. Is this the default nature of Javascript and if so how can I get around this so I can get the current values for all fields in the table, not just the page load values.
This script is written in PHP/Javascript, thanks in advance for the assistance.
Your Javascript function that parse all elements in the table into an array uses
the document.ready function or is loaded only once when the Page is loaded.
In Vanilla JS
document.addEventListener('DOMContentLoaded', (event) => {
//Where you wrote your function
})
Jquery
$(document).ready(function() {
// where you have your function if you are using Jquery
});
And AJAX calls do not reload the page. That means your Javascript function does not get executed so it does not update the array with the new data from the calls.
You need your Javascript as a callback function to the success or complete property of the AJAX call.
jQuery.ajax({
type: 'POST',
url: ajaxurl,
success: function() {
parsingFunction();
},
error: function() {
alert(errorThrown);
}
});
Did you try using a hidden input field for storing the data instead of updating the text input? Or may be you can try using the data-xxx attributes
bests,