This is my script:
<script>
$(document).ready(function(){
$("#ID_Blangko").on("change", function() {
var blangko = $("#ID_Blangko").val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah';
$.ajax({
url: baseUrl,
data: {nama : blangko},
dataType: "json",
success: function(datas){
$("#Jumlah_Blangko").val(datas);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Jumlah_Blangko').val("some error.");
}
});
});
});
</script>
and this is my controller code:
public function ajax_jumlah($nama)
{
$this->db->select('Jumlah_Blangko');
$this->db->where('Nama_Blangko', $nama);
$result = $this->db->get('tb_blangko');
$amount = $result->row()->Jumlah_Blangko;
return json_encode($amount, JSON_NUMERIC_CHECK);
}
i've double checked the onchange function and controller function is working well and returning value. The problem is I cant pass this value to my ajax code and print it on input form. Here's my html:
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="row">
<div class="col-md-6">
<?php
$atribut_blangko = 'class="form-control" id="ID_Blangko"';
$selectedBlangko = $values->ID_Blangko;
echo form_dropdown('ID_Blangko', $dropdown_Blangko, $selectedBlangko, $atribut_blangko);
?>
</div>
<div class="col-md-6">
<?php echo form_input('Jumlah_Blangko', '', 'id="Jumlah_Blangko" class="form-control" placeholder="Jumlah" maxlength="50" readonly="true"') ?>
</div>
</div>
<?php echo form_close() ?>
update #2 and this solve my problem
this the controller function im accessing directly from browser URL that is http://localhost/amc/program/administrasi/blangko_rusak/ajax_jumlah/Malaysia
and i found out that
return json_encode($amount, JSON_NUMERIC_CHECK); this doesnt work and then i changed to:
echo json_encode($amount, JSON_NUMERIC_CHECK); this work.
I dont know how this is possible, anyone can explain?
Please check the line no 3 in your code it should be "$("#ID_Blangko").val()" instead of "$("#ID_Blangko").val"
Explanation:
in the above code line you were expecting to get the value of the element having id "ID_Blangko" and you are using the jQuery, but the main thing here is that the "val" is a function and not a variable so you can not access the value by just saying "$("#ID_Blangko").val" because it looks for a property named as 'val'
I think
var blangko = ID_Blangko.value;
should be
var blangko = $('#ID_Blangko').val();
or
var blangko = $(this).val();
EDIT
Your problem with controller/action not seeing the variable could be because it expects params instead of query string vars like most frameworks do. Something like this could help you with that
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah/' + blangko;
Related
I get category id by js and want to use it to get category description.
when i am passing this id using ajax into php variable its print correct output but when i try to put this id in get_description code ajax give 500 error and not return output why this happen please help me.
Below is my code.
<script type="text/javascript">
$(".-filter").click(function() {
var js_var = this.id;
$.ajax ({
type: "POST",
url: "<?php echo plugin_dir_url( __FILE__ ); ?>category.php",
data: { val : js_var },
success: function( result ) {
$("#update").html(result);
}
});
});
</script>
<div id="update">
<?php
$cat_id = $_POST['val'];
echo $cat_id;
//echo term_description($cat_id,'category');
?>`enter code here
</div>
Thanks,
I'm trying to get the value that I passed in AJAX to PHP. It shows an alert that says, "Success!" however it when I try to display the value in PHP, it says undefined index. Also I am passing it in the same page.
Whenever I click a button, it opens a modal and I also passing values from that button to the modal. This is evident in my JS code.
<script>
$(document).ready(function(){
$('#editModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id'); //im trying to pass this value to php, e.g. 5
var time = $(e.relatedTarget).data('time');
var name = $(e.relatedTarget).data('name');
var stat = $(e.relatedTarget).data('stat');
var desc = $(e.relatedTarget).data('desc');
alert(id);
$("#task_id_edit").val(id);
$("#new-taskID").val(id);
$("#allotted_time_edit").val(time);
$("#task_name_edit").val(name);
$("#task_status_edit").val(stat);
$("#task_desc_edit").val(desc);
$("#task_id_ref2").val(id);
//AJAX CODE HERE
$(function() {
$.ajax({
type: "POST",
url: 'tasks.php?id='<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>,
data: { "userID" : id },
success: function(data)
{
alert("success!"); //this display
}
});
});
}); // line 1131
});
</script>
PHP CODE:
<?php
$uid = $_POST['userID'];
echo $uid." is the value";
?>
It keeps getting an error that says, undefined index: userID. I am confused. Please help me how to fix this. Your help will be much appreciated! Thank you!
Echo the number in the javascript string.
Currently you will get:
url:'tasks.php?id='1,
The 1 should be concatenated or inside the quote. Try:
url: 'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
or take that parameter out since it doesn't appear to be being used.
Just put the $_POST['userID'] in a if statement
Undefined index: UserID is not a error it is a warning
<?php
if(isset($_POST['userID'])
{
$uid = $_POST['userID'];
echo $uid." is the value";
}
else
{
echo "Sorry Value cant be printed";
}
?>
I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";
Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}
I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData