codeigniter call a view / controller on ajax call sucess - javascript

I am new to codeigniter , I am trying to call a controller on AJAX call sucess...
I tried to search stackoverflow but i didn't get what i needed..
Form in my view
<form onsubmit="categorysearch()" method="GET">
<label for="username">Category : </label>
<select id="category" name="category">
<option value="android">android</option>
<option value="iphone">iphone</option>
<option value="windowsphone">windowsphone</option>
<option value="blackberry">blackberry</option>
</select>
<input type="submit" name="searchkeywordsubmit" title="Search" id="searchkeywordsubmit" />
</form>
When the form is submitted the below java script is executed.
JavaScript in my View
function categorysearch()
{
var categorykeyword = document.getElementById("category").value;
alert("Category keyword is " + categorykeyword);
$.ajax({
type: "GET",
async: false,
//dataType: "json",
url: "http://localhost/2009074/index.php/rest/resource/categorysearch/category/" + categorykeyword + "",
success: function(data)
{
alert("Returned data is " + data);
// i want to call the constructor here with the returned data
//$("body").html(data);
//$('body').append(output_string);
},
error: function(data)
{
alert("error is " + data);
}
});
}
AJAX call works successfully , I can see the returned data in the alert (Returned data is JSON encoded)
Now i want to call another controller with the recieved data ...
Please help me to figure this out

you just need to redirect the control the required controller :
success: function(data)
{
window.location.href="http://localhost/my_project_name/my_controller_name";// you just need to add this event on success call.
},

A really dirty way to do it is save the JSON object as session variable and navigate to a page or reload the page and in the constructor of the page, check for the session variable and use the variable.
well that's the only way I can think of at the moment.

Related

How can I load a list of object into select tag with Ajax through API Controller?

I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});

How to get javascript value into php variable without reloading the page using ajax

Here I want to get a value from JavaScript to PHP variable without using any POST or GET method.
Here I'm giving HTML code:
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" onclick="GetValue()" class="btn btn-danger">Generate</button>
Javascript Code
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $('#base').val();
$.ajax({
type: 'post',
url: base_url,
data: {'days' : days, 'night': night},
success: function( data ) {
console.log(data);
}
});
});
});
</script>
php code
<?php
$days = $_POST['days'];
$night = $_POST['night'];
echo $days . " " . $night;
?>
Variable value not working.
You can not directly assign javascript variable to PHP variable, that's why ajax is used.
If you want to perform operations on client side variables to server-side without page refresh and using the same page then you have to write the PHP code on the top of the page before anything start of client-side and the use exit to break after the PHP response is completed. and in jquery ajax forget the URL part as you are using the same page for request and response.
Note: Make sure to include jQuery
Cover all the element in form tag so we can simply send data using serialize method.
index.php
<?php
if(isset($_POST) && !empty($_POST['days'])){
$days = $_POST['days']; // you can write the variable name same as input in form element.
$night = $_POST['night'];
//Perform any operations on this variable and send in response whatever you want it will send the response to success function of jquery ajax and you can check response in `data`
echo $days . " " . $night;
exit();
}
?>
<!--<form id='frmsbmt' method='post' action='#'>-->
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" class="btn btn-danger">Generate</button>
<!--</form>-->
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $("#base").val();
$.ajax({
type: 'post',
//url: base_url,
data: {'days' : days, 'night': night}, //$("#frmsbmt").serialize(), //form serialize will send all the data to the server side in json formate, so there is no need to send data seperately.
success: function( data ) {
console.log(data);
//alert(data);
// It will write the response in developer tools console tab or you can alert it.
}
});
});
});
</script>
You can use an AJAX call for this.
function GetValue() {
var str = document.getElementById('days').value;
$.ajax({
type: 'post',
url: 'text.php',
data: {
someValue: str
},
success: function( data ) {
console.log( data );
}
});
}
To answer your question without using any post or get method to retrieve the variable is impossible. One language is a server side language, one language is a client side language, if the two languages never communicate through an established standard and protocol passing a variable between the two are impossible. PHP is translated server side which means the client side interface doesn't really know it exists unless there is an action that is tied to a method namely get or post. An Ajax request uses either POST or GET or one of the other established methods to communicate.

update value after Ajax call PHP

I want to update TextBox value on basis of selectChange
HTML:
<select name="abc" id="def">
<option value="1">1st Record</option>
<option value="2">2nd Record</option>
<option value="3">3rd Record</option>
</select>
<input value="" name="final_value" id="final_value" />
JS:
$("#selectboxid").change(function() {
$.ajax({ url: "test.php", data:"value="+$("#def").val() , success: function(){
$("#final_value").val(data);
}});
});
PHP:
<?php
function abc($data){
// Database operations
echo json_encode($response);
}
abc($_GET);
?>
With this approach value is updating very nicely But i have below points:
above approach prints values and one can see in Network Tab. Is it a nice way to do it?
I also tried using return $response in PHP function but then response is null and console.log(data) in ajax shows null array.
So, how to update Input value after Ajax without echoing. I do not want that user shall see any type of response even in Network Tab.
I have seen various websites which does the same and not showing any values in Network tab.
** Is there any different approach to do this?
You can alternatively try like this
All HTTP requests can possible to watch on their own network. You can restrict this
$(document).ready(function(){
var params = {};
params['value'] = $("#def").val();
$.post('test.php', params, function(response){
console.log(response);
alert(response);
});
});
I've not tested this, but immediatly I've spotted a couple of things:
$("#selectboxid").change(function() {
// .val is a function
$.ajax({ url: "test.php", data:"value"+$("def").val() , success: function(data) { //Your success callback needs to take an argument
//data will be either a string or a JSON object, so depending on what you want from it, you'll probably not be able to just pass it to the val() function
$("#final_value").val(data);
}});
});
Not 100% complete I'm sure, but hopefully will give you a good starting point
It should be like this
$("#selectboxid").change(function() {
$.ajax({
url: "test.php",
data:{
"value": $("def").val()
},
success: function(){
$("#final_value").val(data);
}
});
});

Reload a page after jquery ajax call

I have a jsp page which displays the details of a student .Based on the student selection from the dropdown box on change event will be fired and retrieve the min and max marks for the student.
<form name="listBean">
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialMarks"/>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalMarks"/>
<input type="submit" value="submit" id="submit" />
MinMarks:<c:out value="${Item.minMarks}"/></c:if>
MaxMarks:<c:out value="${Item.maxMarks}"/></c:if>
</c:forEach>
</form>
After retrieval ,updated data will be stored into the bean.Server request is handled using jquery.ajax() method
function onChange() {
jQuery('form').each(function() {
jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
});
location.reload();
});
}
Once the server response is successful , i will be reloading the page so that the page will be refreshed with the bean data set during the ajax call.
But it is not displaying the data?What i am doing wrong ?
Or is there any better solution to achieve this?
Any suggestions are welcome .
Thanks
It looks like you are reloading the page immediately after sending the AJAX request, potentially before the server has received and processed it.
You could store your ajax requests in an array and only reload the page when all requests have completed using jquery's when().
function onChange() {
var requests = [];
jQuery('form').each(function() {
requests.push(jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
}));
});
jQuery.when.apply(jQuery, requests).then(location.reload, errHandler);
}
function errHandler (err) {
// handle any errors
}

JavaScript failing after second ajax request using submit/selection button

I'm guessing this error has to do with asynchronous programming, but I can't seem to wrap my head around it after looking at various examples on here...
I have a basic form that should do a post request and then it produces a d3 graph based on the form selection value...
<form id="target" method="post">
<select name="len" id="len">
<option value="sel">--Select--</option>
<option value="year">Most Recent Year</option>
<option value="all">All Data</option>
</select>
<input type = "submit"class="btn" value="Submit"/>
</form>
$(document).ready(function(){
$('.btn').on('click',function(){
var myvar = $('select[name=len]').val();
$.ajax({
url: 'dbquery_o2_select.php',
type: 'POST',
data: {'var':myvar},
dataType: "JSON",
success: function (result){
// produce a d3 graph here
},
error: function(jqXHR,textStatus){
alert(textStatus);
}
});
return false; });
});
Upon the second "submit", I get an error saying that 'sampledate' (which is an associated name in the ajax return array named 'result') is undefined.
Thanks in advance for any help. Let me know if you need more info!

Categories