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

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')
?

Related

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

Codeigniter weird ajax result in controller

I've started a codeigniter project and now a i have to do an ajax call to a special controller.
It goes something like this:
- I have two select fields: 1 for selecting county's and the other one must populate with the city's in the selected county.
The problem is I get a really weird result when I send the selected county id to the ajax controller.
If I put something like this in the controller : echo "a $county_id" in the controller it will give me the response : a [selected county_id], but if I only echo out the county id it shows some json empty response, and I don't know what's wrong, below is the code:
the ajax(jquery) call.
$(document).ready(function(){
$('#judet').change(function(){
var county = $( "select option:selected" ).val();
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/") ?>',
success:function(){
console.log('id_judet:' + county);
},
error:function(mesaj){
console.log("there's an error");
}
});
});
});
The codeigniter ajax_controller Controller:
public function index()
{ header('content-type text/html charset=utf-8');
$cou_county = $this->input->post('cou_county');
$decodedCounty = $cou_county;
echo "$decodedCounty";
}
The county and city selectors are two simple select inputs with id's I'll post some pictures if you think i haven't explained it well eneugh.
EDIT: the ajax call does access the controller, where i actually echo that id, but in the response i get some weird json thingy instead of the number, like in the picture below:
the response
Thanks for taking the time to read this, and thanks in advance to those of you who take the time to help a brother out.
You can't use PHP code in javascript:
<?php echo base_url("ajax_controller/") ?>
Instead, you should create a js variable like this:
base_url = '<?php echo base_url("ajax_controller/") ?>';
Then use this variable with your function.
In order to use base_url() you have to load url helper in controller like this..
$this->load->helper('url');
Or load in application/config/autoload.php.
Then in your ajax edit url to
url:'<?php echo base_url("ajax_controller/index");?>',
In controller:
public function index()
{
$cou_county = $this->input->post('cou_county');
echo $cou_county;
}
In ajax:
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/index");?>',
success:function(data){
console.log(data); //see your console
},
error:function(data){
console.log("there's an error");
}
});

Undefined index in php when getting value passed from AJAX

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

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.

ajax not able to pass variable to php

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

Categories