Reload Ajax Content from on.Change function after Page has been refreshed - php

I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.
The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.
This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:
$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
});
});
My dropdown menu:
<select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
<option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>
The div it is loaded into:
<div id="subjectqualidiv1"></div>
The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.
Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?
EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:
$(document).ready(function () {
// For loading the ajax content on refresh/form submit
var subject1 = $('#subjectapp1');
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
$('#subjectapp1').change(function()
{
var self = $(this);
$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
$('#subjectqualidiv1').html(data);
});
});
});
Thank you!

You can add your function that calls your AJAX to the $(document).ready() function which executes on page load. Be careful to check for valid data before executing your function because there may be instances when the page loads and the selector will be empty. For missing information you may want to look into the required attribute in HTML, which will prevent form submission if no data exists for that element. That will prevent a refresh for insufficient data.

You can do this along with your current code:
$(document).ready(function () {
$("#subjectapp1").trigger('change');
}

Related

Populate a drop-down list depending on what is selected from another drop-down list from two variables PHP

I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.

Variables not sent when pressing back button

I have a javascript that runs on a set of checkboxes to filter some items shown via PHP.
When someone filters the information and then clicks on an item, he is directed to that item's description. My issue is when that user clicks on the BACK button in the browser, since my filtering is already gone.
This happens because my script loads a .php but only inside a DIV (so I don't need to reload the whole page). This means my sent variables are just loaded at the DIV level and not at the URL level, so when they go to the description of a specific product and then go back, those variables are not there anymore and the filtering is gone.
Here is my JS:
$(function() {
$("input[type='checkbox']").on('change', function() {
var boxes = [];
// You could save a little time and space by doing this:
var name = this.name;
// critical change on next line
$("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
boxes.push(this.value);
});
if (boxes.length) {
$(".loadingItems").fadeIn(300);
// Change the name here as well
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>&'+this.name+'=' + boxes.join("+"),
function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>', function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
}
});
});
Any idea to solve this?
Either open the item description in a new window, or (more elegantly) open the item description in a modal dialog (e.g. using jQuery UI dialog).

load data from mysql with jquery and php

I have a drop down list (ddlAccount) which i can choose an item from it and do a db query in test.php to retrieve corresponding data, then output an input element with the returned data.
This is my javascript code:
function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')});
}
load1 function called when i change the dropdown list items, and it takes the value of the selected option and sends it to test.php in a parameter called "accountInfo".
my html:
<select name="ddlAccount" id="ddlAccount" onchange="load1();">
<option value="1"> Account1</option>
<option value="2"> Account2</option>
<option value="3"> Account3</option>
</select>
<div id="divAccountNum" >
</div>
And test.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']); //mysql query
//print an input holding account number as its value
echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>";
}
The problem is that nothing happened when i choose an option (nothing appear in div (divAccountNum))
Any suggestions? Thanks in advance.
Edit:
I used #thecodeparadox 's bit of code and it works and i found a solution for the problem that i mentioned in the comments below which is that when choosing one item from the dropdown list it shows the value in input element and loads the form again. The solution is in:
jQuery Ajax returns the whole page
So my jquery code now looks like:
$(document).ready(function(){
$('#ddlAccount').on('change', function() {
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
//console.log(accountNum);
$('input#txtAccountNum').val(accountNum);
});
});
And testJquery.php :
if($_GET['accountInfo'])
{
$account = $accountDAO->load($_GET['accountInfo']);
$accountNum = $account->accountnumber;
echo $accountNum;
}
And at last i added input element in divAccountNum which has id="txtAccountNum"
Though you don't give enough info about your problem, but you can try this:
function load1(){
$('#ddlAccount').on('change', function() {
$.get('test.php?accountInfo=' + $(this).val(), function(response) {
$('div#divAccountNum').html(response);
}, 'html');
});
}
NOTE:
$('#ddlAccount').on('change', fires when dropdown change
$.get('test.php?accountInfo=' + $(this).val().. send a get(ajax) request to test.php with value selected from drop down
parameter response with in $.get() second parameter callback function is the response from the server
'html' as third parameter of $.get() for data type you return, as you return a html so it is html.
for more info read:
change()
$.get()
To get selected option value from select input use:
$('#ddlAccount option:selected').val()

Dynamically add new combo (select) box

In my page, I have a combo box with an add button. How do I create a new combo box below the original combo box when I clicked the add button? If clicked again, it will produce another combo box. The value inside each combo box is called from the database.
Here's an example, though you'll have to work out the middle tier and back end portion yourself.
Example: http://jsfiddle.net/9hvbt/3/
JavaScript
$('#btnAdd').click(function(){
//Use Ajax to talk to your server (middle tier)
$.ajax({
url: '/echo/json/', //Replace with your URL to return Database data (JSON format)
dataType: 'json',
type: 'get',
success: function(data){
//Use the returned data to pass into CreateDropDown (Hard coded for an example)
CreateDropDown(["Item 1", "Item 2", "Item 3"]);
}
});
});
function CreateDropDown(data){
var $newSelect = $('<select />');
$.each(data, function(i, val){
$newSelect.append($('<option />', {
'text':val
}));
});
$newSelect.appendTo('#dropDowns');
}
​
​
HTML
<div id='dropDowns'>
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
<input type='button' id='btnAdd' value="Add" />​
EDIT
You should also read up on jQuery's AJAX method
any ideas with jquery? jquery clone() will help you to solve this problem
JQuery .clone()
A LIVE EXAMPLE : http://jsfiddle.net/laupkram/6LBNs/
in the case of your problem try to study this one
Dynamic Loading of ComboBox using jQuery and Ajax

Cascading select

Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.

Categories