Undefined index in php when getting value passed from AJAX - javascript

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";
}
?>

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

how to pass values from ajax to controller on button click?

this is my js code which is executed on button click
$("#search_tutor").click(function(){
$("#show_tutors").hide();
var subject = $( ".subject" ).val();
var degree_level = $(".degree_level").val();
var city = $(".city").val();
console.log(subject);
console.log(degree_level);
console.log(city);
$.ajax({
url:"<?php echo base_url(); ?>public_controller/search_tutor_jquery",
method:"post",
data:{subject: subject, degree_level : degree_level, city : city},
success:function(data){
$('#search_results').html(data);
}
});
});
and this is controller function
public function search_tutor_jquery(){
$subject = strtolower($this->input->post('subject'));
$degree_level = strtolower($this->input->post('degree_level'));
$city = strtolower($this->input->post('city'));
echo $subject; //prints nothing
$data['filtered_tutors'] = $this->public_model->search($subject,$degree_level,$city);
$this->load->view('public/search_results',$data);
}
values are being logged in console but i cannot receive values in controller. can somebody help me out?
thanks in advance
What do you mean by
$('#search_results').load("<?php echo base_url('public_controller/search_tutor_jquery') ?>");
Try
$('#search_results').html(data);
Read about load() function here. It sends a new empty request and load that data to your element. It doesn't load the response.
Have you tried using
$_POST['subject']
instead of
$this->input->post('subject')
?

ajax send and get data to/from controller mvc

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;

How do i make my php variable accessible?

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; ?>";

How can i add a variable in AJAX URL

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Categories