jquery to take textbox value and pass to controller action - javascript

I have two textbox in form.
when i type some value inside textbox and click the button then i want to echo this value in my function.
I want to take value of my textbox and pass this in my controler function on button click using javascript and ajax.
but my script is not working and not showing any value..
<script>
$(document).ready(function() {
$("#subvessels").on('click', function() {
var shipment_title = $("#shipment_title").val(); //textbox value
var shipment_point = $("#shipment_point").val(); //textbox value
if (shipment_point) {
var dataString = 'shipment_title=' + shipment_title;
var dataString = 'shipment_point=' + shipment_point;
var values = $(this).serialize();
ajaxRequest = $.ajax({
url: '<?php echo Router::url(array("controller" => "DispatchedJobs", "action" => "approxBudget")); ?>',
type: 'POST',
data: dataString,
dataType: "html",
beforeSend: function() {
$('.spinicon').show();
},
success: function(response) {
$("#vessels_table").html(response);
},
complete: function() {
$('.spinicon').hide();
}
});
}
});
});
</script>
//controller function
public function approxBudget($shipment_point,$shipment_title)
{
echo $shipment_title;
echo $shipment_point; exit();
}

Give the parameters as an object to data. This is everything you need.
$("#subvessels").on('click', function() {
ajaxRequest = $.ajax({
url: '<?php echo Router::url(array("controller" => "DispatchedJobs", "action" => "approxBudget")); ?>',
type: 'POST',
data: {
shipment_title: $("#shipment_title").val(),
shipment_point: $("#shipment_point").val()
},
dataType: "html",
beforeSend: function() {
$('.spinicon').show();
},
success: function(response) {
$("#vessels_table").html(response);
},
complete: function() {
$('.spinicon').hide();
}
});
});
In php you get the values with $_POST["shipment_title"] and $_POST["shipment_point"] by default. If you use a framework, there could be other ways to access the values. But the request is correct like above.

Related

Jquery UI autocomplete plugin not working

I am a new learner, trying to use JQuery autocomplete plugin. but unable to get the results in autocomplete suggestion, although I am getting the results in console.log and as an alert. But not in suggestion list.
Input field
'Name: <input type="text" id="hint" name="hint" />'
jquery
$(document).ready(function () {
$("#hint").keyup(function () {
$( "#hint" ).autocomplete({
source: function(request, response) {
//console.info(request, 'request');
//console.info(response, 'response');
$.ajax({
//q: request.term,
url: "<?php echo base_url(); ?>index.php?Librarian/autocomplete/",
data: { term: $("#hint").val()},
dataType: "json",
type: "POST",
success: function(data) {
alert(data)
console.log(data);
response(data);
}
});
},
minLength: 2
});
});
});
Controller
function autocomplete($param1 = '', $param2 = '', $param3 = '') {
// load model
$this->load->model("Librarian_model");
$search_data = $this->input->post('term');
$result = $this->Librarian_model->get_autocomplete($search_data);
echo json_encode($result);
//returning the result as result_array() also tried implode function but got the error at response
}
OUtput at console log :
enter image description here
and in alert i got object-object but when I use JSON.stringify output is a array
Seams that you're ajax response format issue use map function to format ajax response -
$(document).ready(function () {
$("#hint").keyup(function () {
$( "#hint" ).autocomplete({
source: function(request, response) {
//console.info(request, 'request');
//console.info(response, 'response');
$.ajax({
//q: request.term,
url: "<?php echo base_url(); ?>index.php?Librarian/autocomplete/",
data: { term: $("#hint").val()},
dataType: "json",
type: "POST",
success: function(data) {
alert(data)
console.log(data);
response($.map(data, function (item) {
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 2
});
});
});

Passing variable to PHP using Ajax/jQuery

This is probably very simply but I cannot figure it out. I am using a jquery script I found to display a timer. I then want to send the number of seconds to a PHP file. Below is the script, if I just alert the value variable, it contains the correct data, so I am accessing it correctly but its empty on the PHP side when it arrives.
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
The result alert displays empty based on this test php file
<?php
if (isset($_POST['value'])) {
$value = $_POST['value'];
echo $value;
} else {
$value = "Empty!";
echo $value;
}
?>
I would really appreciate some help.
I thought you must add a header to Ajax object.
edits :
change var name
check URL address
add header
$('.get-timer-btn').on('click', function() {
//change this name !
var value_data = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php', //make sure correct address
headers: {'Accept': 'application/json'}, //add header is so important
data: { value : value_data },
cache: false,
success: function(result){
alert(result);
}
});
});
You must end php hier is a worked example:
<?php
if(isset($_POST['value'])){
$value = $_POST['value'];
echo ($value)?$value:'Empty';
die;}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p class="timer" data-seconds="2"></p>
<button class="get-timer-btn">BTN</button>
<script>
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
</script>

how to send the ajax array values to php and how to check script value is assigned or not

I want to send the array value to php using array
<script>
$('input.update').on('focus', function() {
$(this).data('val', $(this).val());
});
function sendvalue() {
// Array
var postData = [];
$('input.update').each(function() {
var inp = $(this);
postData.push({
previous: inp.data('val'),
currentvalue: inp.val(),
});
});
$.ajax({
type: "POST",
url: "updateedit.php",
data:postData,
success: function(data) {
alert(data);
},
error: function() {
alert('failed');
}
});
}
</script>
My php page
foreach($_POST['postData] as $value)
{
echo $value;
}
In My php page I got the Error as undefined index:postData and how to check if the script value is assigned or not
The data option needs to be an object. The property names of the object become the $_POST keys.
$.ajax({
type: "POST",
url: "updateedit.php",
data: { postData: postData },
...
});

jQuery access Ajax Response from PHP function

I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return $date;
}
?>
I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:
if (isset($_POST['dateFunction'])) {
print_r(dateRangeTimeFrame($_POST['dateFunction']));
}
My jQuery code is as follows:
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response['startDate']);
console.log(response.startDate);
}
});
My issue is that I do not know how to access the response that the php function is returning.
Here is the response I am getting from the PHP function:
Array
(
[startDate] => 2015/01/17
[endDate] => 2015/02/16
)
How would I go about getting these 2 vars from the PHP response?
You need to use JSON. Your Javascript natively understands and can parse it
if (isset($_POST['dateFunction'])) {
echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}
And your jQuery (note I added dataType)
$.ajax({
url: 'includes/functions.php',
dataType: 'json',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return json_encode($date);
}
?>
jQuery
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
dataType: "json",
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1) {
// ...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
echo json_encode($date);
}
?>
Ajax
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate },
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i].startDate);
}
}
});

Staying on page depending on value jquery

I want to stay on the same page if the login (data.login != 1) is incorrect , I tried with preventDefault but that's not working. Can anyone help me ?
$(document).on('submit', '#login', function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: $(form).serialize(),
dataType: 'json',
success: function(data) {
if (data.login === 1) {
$.mobile.changePage("<?php echo site_url('redirect/overview'); ?>");
} else {
e.preventDefault();
}
}
});
});
The page will submit before the result of ajax call is being received in success as you have asyn call, You can e.preventDefault() before ajax call and call submit on success.
$(document).on('submit', '#login', function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: $(form).serialize(),
dataType: 'json',
success: function(data) {
if (data.login === 1) {
$.mobile.changePage("<?php echo site_url('redirect/overview'); ?>");
}
else {
$('#submitButtonId')[0].submit();
}
}
});
});

Categories