JQUERY & Select box not updating database - php

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.

Related

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 apply the jQuery classes to HTML elements generated through AJAX response so that the jQuery functionality should be workable?

I'm using PHP, jQuery for my website. I've following HTML elements which are present on the page when the page loads.
//Date picker controls
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_start_date[1]" id="rebate_start_date_1" value="">
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_expiry_date[1]" id="rebate_expiry_date_1" value="">
//Select control
<select class="states" multiple="multiple" name="applicable_states[1]" id="applicable_states_1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>
In the above code, I've added jQuery classes to the HTML controls to make the jQuery functionality workable.
.date_control for two date picker controls
.states for select control
The jQuery code for above HTML elements with the above specified classes is as follows:
$(document).ready(function() {
//code for datepicker
$(".date_control").datepicker({
dateFormat: "yy-mm-dd"
});
//code for states
$('.states').multiselect({
includeSelectAllOption: true,
maxHeight: 150
});
});
Now on click of a button present on a page I'm calling AJAX function as follows.
<button style="float:right" class="add_new_rebate" type="button" class="btn btn-default" onclick="add_rebate_by_product(); return false;"><i class="icon-plus"></i> Add New Rebate</button>
Then in AJAX function I'm giving call to a PHP file. In PHP file I'm making the response and sending it back to the AJAX request. Till here everything works fine. But the issue I'm facing is the non-working of jQuery functionality on the HTML controls I added through AJAX response. I've taken care of adding the same classes as above while preparing the PHP response. Even if I check the source HTML by inspecting the respective HTML elements, the jQuery classes are present over there but functionality is still not working. For your reference I'm giving below the AJAX request code and the response preparation code from PHP file:
//AJAX request code
function add_rebate_by_product() {
var manufacturer_id = $("#company_id").val();
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
//PHP code snippet to prepare response
<?php
$op = $_REQUEST['op'];
switch( $op ) {
case "create_rebate":
echo "<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_start_date[$rebate_no]' id='rebate_start_date_$rebate_no' value=''><input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_expiry_date[$rebate_no]' id='rebate_expiry_date_$rebate_no' value=''>
<select class='states' multiple='multiple' name='applicable_states[$reabate_no]' id='applicable_states_$reabate_no'>
<option value='1'>Alabama</option>
<option value='2'>Alaska</option>
<option value='3'>Arizona</option>
<option value='4'>Arkansas</option>
<option value='5'>California</option>
</select>";
exit;
}
?>
I googled a lot about this but still couldn't get the perfect solution which could make the jQuery functionality workable for HTML controls added using AJAX. So can anyone please help me in this regard? Thanks for spending some of your valuable time in understanding my issue. If you need any kind of information regarding the question I can provide you the same. Any kind of help, comments, suggestions, answers will be highly appreciated. Waiting for your precious replies.
Wrap the initialization code in a function:
function initializeControls(){
//code for datepicker
$(".date_control").datepicker({
dateFormat: "yy-mm-dd"
});
//code for states
$('.states').multiselect({
includeSelectAllOption: true,
maxHeight: 150
});
}
Then call it in your ajax callback:
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
initializeControls();
}
$('.load').remove();
}

How to use onchange with serializeArray in jquery?

I've created a form with 3 select part and I tried to create an array with serializeArray. I want to use jquery ajax to post this array to my php file. But I don't want use submit. when I had just one select tag, I used this code
<form>
<select onchange="myfunction(str)">
<option value="">num</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
</form>
In my ajax code, I used open("GET","myphpfile.php?q="+str,true) and send() without jquery. but now I have 3 select tag and I don't know how too use serializeArray()(or serialize()) with jquery.
this is my new form
<form>
<select name="num1">
<option value="">num1</option>
<option value="12">12</option>
<option value="13">13</option>
</select>
<select name="num2">
<option value="">num2</option>
<option value="123">123</option>
<option value="133">133</option>
</select>
<select name="num3">
<option value="">num3</option>
<option value="12345">12345</option>
<option value="12346">12346</option>
</select>
</form>
the second part of my question is how to write my php code to echo my array. I think it should be something like this
<?php
$myarr = array();
$myarr = $_GET["str"]//or $_POST['str']
echo $myarr[0];
?>
Thanks a lot! and by the way, English is not my native language; please excuse typing errors.
Okay, if I get your question correctly, here is what you're trying to do:
Hooking events on dynamically added fields
$("form").on("change", "select", function() {
var name = $(this).prop("name");
console.log("Select-Name: " + name);
// if you use the plugin I mentioned further down and you'll need to serialize
// all fields already here, you can use the plugin's .fieldSerialize method
})
Get detailed information here: https://api.jquery.com/on/
Serializing forms
Easiest thing here would be to work with this jQuery Form-Plugin:
http://malsup.com/jquery/form/
Create a json-dataset with almost no effort like this:
$("form").ajaxForm({
dataType: "json",
success: function(data) { sendToServer(data); }
});
Working with the data in the backend
The plugin also allows you to work on the server with the script you provided ($_POST["value"])
use
var arrayForm = $('form select').serializeArray();
and then
var paramForm = $.param(arrayForm);
like http://jsfiddle.net/LBKeQ/
then you can use
$.ajax({
type: 'POST',
async:true,
cache: false,
data: paramForm,
success:function (data, textStatus) {
console.log(data);
},
url:"myphpfile.php"
});

retrieve value from database when onchange in dropdownbox by jquery

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
.
.
.
.
}
}
?>

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() ?>"

Categories