retrieve value from database when onchange in dropdownbox by jquery - php

This is my html code
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
and my database table is like this
courseId courseName courseCredits
1 Diploma in Computing 5
So my request is, if i change the value in the 'select' the 'courseCredits' value should appear in the textbox. for this how can i write jquery code?

"Ajax with Jquery" is what your are looking for. It will work like this:
the user chooses an option from the select box
you submit via Javascript the chosen option to a PHP script
the php script fetches the data from the database
the php script returns the result as json encoded data
there is a callback function in your javascript code. This js code will manipulate the HTML in whatever way you want, e.g. "add the option to your select box"
There are tons of tutorials on how to do Ajax requests in detail, e.g. http://openenergymonitor.org/emon/node/107
Check out one of those tutorials - eventually you will want to update your question so that it becomes a bit more specific? :-)

it is good practice to seperate you html from scripts so i would like to change :
<select name="course" id="course" onchange="valuesOfAll(this.value)">
to
<select name="course" id="course" >
then my script will be following (hoping you add reference of latest jquery )
<script>
$(document).ready(function(){
//bind change event once DOM is ready
$('#course').change(function(){});
getResult($(this).val());
});
function getResult(selectedValue){
//call ajax method to get data from database
$.ajax({
type: "POST",
url: url,//this should be replace by your server side method
data: "{'value': '"+ selectedValue +"'}", //this is parameter name , make sure parameter name is sure as of your sever side method
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
alert(Result.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>

use $.post.. (ajax or get)... i am using post here....go through the docs if you want to read more about jquery post..
javascript
function valuesofAll(val){
$.post('test.php',{data:val},function(result){
$('#course_credits').val(result.coursecredit)
}, "json"); //expect response as json..
}
test.php
$data=$_POST['data']; //this is the value posted
//make you query in db get result..
$courseCredits= $row; //db returned courseCreadit value
echo json_encode(array('coursecredit'=>$courseCreadits)); //send response as json

this will helps you .....
<script>
function valuesOfAll(value)
{
var base_url="http://.../../hello.php";
var ip=new Object();
ip.course=value;
var inputParam=JSON.stringify(ip);
var module="getcourseCredits"
$.ajax({
type: "POST",
url: base_url,
data: {coursevalue:inputParam,module :module},
dataType: "json",
success: function(msg)
{
$("#course_credits").val(msg.credit);
}
});
}
</script>
<body>
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
</body>
In your PHP file
<?php
if(isset($_POST['module']))
{
if($_POST['module']=='getcourseCredits')
{
$val=json_decode($_POST['coursevalue'],true);
$courseval=$val['course'];
// do the connectivity and query here and finally echo the result as json format that is the response to the ajax call
.
.
.
.
}
}
?>

Related

JQUERY & Select box not updating database

I have the following 3 checkboxes which are populated from a php database. I need assistance with JQUERY that once any select box is changed the value is posted to a php file and able to return a response through JQUERY.
Each select box should be standalone to only send that checkbox value & name to the PHP file.
I have the below JQUERY to start with to send the first checkbox but am getting no response back.
What amendments need to be made to the JQUERY to receive the input of the other checkboxes and then send the data correctly?
The php file will simply have echo "WHAT EVER THE RESPONSE IS" using if statements.
Any help grately appreciated with thanks.
$(document).ready(function() {
$('select.person-1').change(function() {
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $('select.person-1').val(),
changeCol1: $('input[name$="changeCol1"]').val()
},
dataType: "html",
},
success: function(data) {
var a = data.split('|***|');
if (a[1] == "update") {
$('#msg').html(a[0]);
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name='person-1' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol1' value='person-1'>
<select name='qty' class='marshal-select'>
<option value='1'>1</option>
</select>
<input type='hidden' name='changeCol2' value='qty'>
<select name='person-2' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol3' value='person-2'>
The selectors you've used are incorrect for the HTML displayed. .person-1 is a class selector, yet the select elements have that value in their name.
In addition your success property is outside the options object of the $.ajax call - it needs to be inside.
You can fix this issue and DRY up the code to make it more extensible by removing the hidden fields, hooking the change event handler to the common marshal-select class on all the select elements, and by using the name attribute of the select elements to fill the changeCol property of the data you send in the AJAX request. Try this:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
// in your AJAX request...
let data = {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
};
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="person-1" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
<select name="qty" class="marshal-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="person-2" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
As an aside, the logic in the success handler implies that you're returning plain text and then hacking the string around using split(). Do not do this. Return a serialised data structure, such as JSON instead. This is more extensible and makes the code far more robust.
Update:
With your code you have added could you just add an edit where how you would receive a response ideally I want a positive response to show the msg div and where you would call the php file?
Sure, here you go:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
},
dataType: "html",
success: function(data) {
// assuming a JSON response:
if (data[1] === 'update') {
$('#msg').html(data[0]).show();
}
}
});
});
});
Note that I've not included the PHP which would generate the JSON response as I'm not a PHP dev. I'm sure there are lots of topics covering that if you search.

change function on radio group loaded through ajax

jquery change function on radio button is working properly when they are part of html body i.e when they have written in html body, but when they loaded through ajax request change function not works. My code is-
html code
<form>
<select id="sel" name="sel">
<option value="">Select Type</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="load"></div>
<label id="change">--</label>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.radi').change(function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});
$("#sel").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax ({
type: "POST",
url: "faculty.ajax_load.php",
data: dataString,
cache: false,
success: function(html){
$("#load").html(html);
console.log( "radio loaded" );
}
});
});
});
</script>
ajax_load.php is:-
<?php
echo '<input class="radi" type="radio" name="sect" value="P" id="p"/>
<input type="radio" class="radi" name="sect" value="A" id="a" checked="checked"/>';
?>
Now the problem is radio buttons are appear but when I click them change is not shown on console and label. Please help, where I am doing mistake.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
As you are loading using ajax call.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document with closest static container.
As per your code
$("#load").on('change', '.radi', function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});

How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?

I'm passing form data to a PHP script for processing via JS(jQuery.ajax()).
Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. $_POST['zipcode'] ).
Instead I can only access the data with $_POST['form'], which is an entire form represented as one long string( e.g. string(89)"color=red&color=blue&zipcode=12345..." ).
How can I access individual values of form data inside PHP script passed from a HTML form via JS?
index.php(form)
<form id="myform">
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
index.php(JS)
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'html',
url : 'PHPscript.php',
data: {form : $('#myform').serialize()}
}).done(function(data) {
var myJSONresult = data;
alert(myJSONresult);
});
});
PHPscript
<?php
if(isset($_POST["form"])){
$form = $_POST["form"];
$myzipcode = $_POST['zipcode']; // won't work; will be null or empty
echo json_encode($form);
}
?>
EDIT: The zipcode field:
$("#zipcode").focus(function(){
if(this.value == "zipcode"){
$(this).val("");
}
}).blur(function(){
if(this.value == ""){
$(this).val("zipcode");
}
});
You need to use serializeArray() on the form data instead of serialize. That will submit as an array.
data: $('#myform').serializeArray()
HTML
<input type="hidden" name="action" value="submit" />
PHP
if(isset($_POST["action"]))
{
//code
}
Add dataType: 'json' to your ajax handler and further modify your code like this:
$.ajax({
type: 'POST',
dataType: 'json', // changed to json
url : 'PHPscript.php',
data: {form : $('#myform').serialize()},
success : function(data){ // added success handler
var myJSONresult = data;
alert(myJSONresult.yourFieldName);
}
});
set traditional to true like
$.ajax({
traditional:true,
//your rest of the ajax code
});
on the php end you are getting the value fine the problem is at the form serialization end

Usng JSON in codeigniter with form submit

Im trying to learn how to use JSON from within codeigniter. I'm trying to use a model to run the ajax code, but its not working.
I need to learn how to pass variables through to the model, and back out; or, if thats incorrect, I need to learn the correct process. The below is my code.
HTML
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<option name='Town Center' value='1' data-icon='../img/structures/tc.png' data-html-text='Town Center<i>
500 minutes<br>50000 gold</i>'>Town Center</option>
<option name='Barracks' value='2' data-icon='../img/structures/barracks.png' data-html-text='Barracks<i>
25 minutes<br>1500 gold</i>'>Barracks</option>
<option name='Dragon Roost' value='3' data-icon='../img/structures/droost.png' data-html-text='Dragon Roost<i>
200 minutes<br>5000 gold</i>'>Dragon Roost</option>
<option name='Mage Hall' value='4' data-icon='../img/structures/mage.png' data-html-text='Mage Hall<i>
40 minutes<br>300 gold</i>'>Mage Hall</option>
<option name='Test Lab' value='6' data-icon='../img/structures/testlab.png' data-html-text='Test Lab<i>
1 minutes<br>10 gold</i>'>Test Lab</option>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Here is my ajax/js/json
I'm trying a very simple example. I'd like to post the value of the OPTION above (1-6) to the model function insert_build. I don't know if its doing it, as I can't really think of a good way to test it. However, I would assume if it returned anything, I would be alerted. I am not.
$(function(){
$(".button").click(function(e, value){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build() ?>", //the script to call to get data
str_id: value,
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
});
The model code
public function insert_build()
{
$str_id = $this->input->post('str_id');
echo " TESTING $str_id";
}
Any help would be greatly appreciated. Why doesn't this work? I am still trying to understand the fundamentals of Codeigniter and JSON / JS.
Thanks
The url: you're setting in your javascript is the actual function you're wanting to call when the ajax is submitted. You'll need to have a controller in place that actually calls that function e.g.
url: "<?php echo base_url(); ?>/structure/insert/?str_id=" + $('#buildID').val(),
Also, setting dataType: to json means you're expecting what's returned from your function to be encoded as json.
Maybe change this:
url: "<?php echo $this->structure_model->insert_build() ?>"

simple jquery fetch from mysql

I am trying to use jQuery with MYSQL and I wrote something like this :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function example_ajax_request() {
$('#example-placeholder').html('<p>Loading results ... <img src="ajax-loader.gif" /></p>');
$('#example-placeholder').load("loadres.php");
}
</script>
</head>
<body>
<div id="query">
<select name="show" id="box" >
<option value="0">Select A Test</option>
<option value="All">--All--</option>
<option value="M1">Model1</option>
</select>
<input type="button" onclick="example_ajax_request()" value="Click Me!" />
</div>
<div id="example-placeholder">
<p>Placeholding text</p>
</div></body>
</html>
Basically I want to pass parameters to the loadres.php file. But unable to figure out the exact way to do.
Any help is appreciated.
Thanks.
You should use the $.ajax() method from jQuery. you can pass data to the url and have a callback at the end.
$.ajax({
url: 'loader.php',
data: 'somedata',
type: 'GET',
success: function(data){
$('#example-placeholder').text(data);
}
});
This will do the trick. This method also provides far more flexibility. You can have different functions such as error functions and complete functions.
$('#example-placeholder').load("loadres.php?show=" + $('#box option:selected').val());
This will use jquery to get the selected value from the drop down list and append it to the URL as a querystring parameter, which you can access in the loadres.php page.
similar to saif-bechan's post you can use ajax with post and data can hold an object to pass multiple parameters
$.ajax({
type:"POST",
url: loadres.php,
data: {
foo:'bar',
selected:$('#selector').val()
},
dataType: 'json',
error: function(data) {
//error code here
},
success: function(data) {
//success code here
}
});
I will also note that is is better to put your click event in jquery context not in the html
so in script somewhere use
$('#button_id').click(function(){
//call to ajax
};

Categories