how to pass the text value to controller in <a> format? - codeigniter

I have to pass the value to controller page using link format.
My view page code for link:
<form action="<?=site_url('Account_Master/Tax_Save')?>" method="POST">
<head><h5><center>TAX SLAB ENTRY</center></h5><button type="submit" class="btn bg-slate"><i class="icon-file-plus position-left"></i>Ok</button>
<a id="button" method="POST" href="<?=site_url('Account_Master/get_data')?>" class="btn bg-info"><i class="icon-book3 position-left"></i> View All</a>
</head>
<div id="item1">
Tax Type: <input type="text" style="height: 28px; width:250px; " id="taxtype" name="taxtype">
</div>
When i clicked the view all button type link the value of the tax type should be pass to controller page.But i have written code to post the value but the value is not passed.
My controller code:
public function get_data(){
$tax = $this->input->post('taxtype');
print_r($tax);
$data['query']= $this->db->query("SELECT * FROM tax where taxtype ='$tax' ")->row();
$this->load->view('Account_Master/Tax_Setting1', $data, FALSE);
}
I have so far tired this code the value of the taxtype is not passed to the controller

hello I hope there is a problem with your code if I may say
Edited Part
Base on getting the input value which is not possible on button click can be done using jquery js library
html file
<form id="form" action="<?php echo site_url('Account_Master/Tax_Save');?>" method="POST">
<head>
<h5>
<center>TAX SLAB ENTRY</center>
</h5>
<button type="submit" class="btn bg-slate">
<i class="icon-file-plus position-left"></i>
Ok
</button>
<a id="button" href="<?php echo site_url('Account_Master/get_data/');?>" class="btn bg-info">
<i class="icon-book3 position-left"></i>
View All
</a>
</head>
<div id="item1">
Tax Type:
<input type="text" style="height: 28px; width:250px; " id="taxtype" name="taxtype">
</div>
</form>
Place this code just before your closing body tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('click', '#button', function(event){
event.preventDefault();
var form_box = $(this).parents('#form'),
tax_value = form_box .find('input').val(),
link_url = $(this).attr('href'),
url = link_url+tax_value;
form_box.attr('action', url);
form_box.submit()
})
})
</script>
Then in your controller,
either you do this
public function get_data($tax_value){
$tax = $tax_value;
print_r($tax);
$data['query']= $this->db->query("SELECT * FROM tax where taxtype ='$tax' ")->row();
$this->load->view('Account_Master/Tax_Setting1', $data, FALSE);
}
OR
public function get_data(){
$tax = $this->input->post('taxtype');
print_r($tax);
$data['query']= $this->db->query("SELECT * FROM tax where taxtype ='$tax' ")->row();
$this->load->view('Account_Master/Tax_Setting1', $data, FALSE);
}
I hope this help you if not let me know your argument okay... I am here to help

Related

Data not going to controller using Ajax

I am new to AJAX and I am trying to send some data to the controller using the AJAX. on clicking the button "Start Event", nothing is happening..
This is my jsp page where I have written the AJAX code
<c:forEach items="${scheduledEvents}" var="event">
<div class="col-md-3" id="eventId">
<div class="card-counter primary">
<div id="head" class="card-counter head-color"></div>
<span class="count-head">${event.eventName}</span>
<br>
<span class="count-name">Date : ${event.date}</span>
<span class="count-name">Location : ${event.location}</span>
<span class="count-name">Hosted By : ${event.hostName}</span>
<span class="count-name">Description : ${event.description}</span>
<br>
<br>
<div class="count-join">
<button class=" btn" id="${event.linkId}" style="background-color: #cc3300;"><font style="color: white;">Start Event</font></button>
</div>
</div>
</div>
</c:forEach>
<script type="text/javascript">
$(function() {
$('.count-join').on('click',function(){
var eventData = $(this).attr("id")
.ajax({
url : 'startEvent?data=' +eventData,
type : 'GET',
contentType : 'application/json',
success : function(data){
$
.get(
'${pageContext.request.contextPath}/startEvent',
function(data,status) {
$("#eventId").html(data);
}
);
}
});
});
});
</script>
And this my controller mapping
#RequestMapping(value="/dashBoard/startEvent")
public ModelAndView startScheduledEvent(#RequestParam("data")String data)
{
System.out.println(data);
return new ModelAndView("DashBoard");
}
Where am I wrong? please give some detailed explanation as I do not know much about AJAX. Thanks in advance.
As per you controller #RequestMapping, you have missed the /dashBoard in ajax call.

How to POST an object to controller

I'm having a difficulty passing my 'product' object to the controller. How can I do it? I'm not getting errors. The problem is that the 'product' object is null on my controller.
html:
<section th:each="menu : ${allMenus}">
<button
<h1 th:text="${menu.name}"></h1>
</button>
<div>
<div th:each="product : ${menu.productList}">
<a data-toggle="modal" th:href="'#' + ${product.name} + 'Modal'">
h5 th:text="${product.name}"></h5>
<small th:text="${product.price} + '$'"></small>
<p th:text="${product.description}"></p>
</a>
<div th:replace="/productModal :: productModal(product=${product})"></div>
</div>
</section>
Modal:
<div th:fragment="productModal(product)">
<div role="document">
<form method="post" th:action="#{/addItemToCart}">
<div th:each="topping : ${product.toppings}">
<input type="checkbox" th:id="${topping} + ${product.id}" name="checkedToppings" th:value="${topping}" />
<label th:for="${topping} + ${product.id}" th:text="${topping}"></label>
</div>
<div>
<button type="submit">Add to Shopping Cart</button>
</div>
</form>
</div>
</div>
controller:
#RequestMapping(value="/addItemToCart", method=RequestMethod.POST)
public String addItemToCart(#ModelAttribute("product") Product product, #RequestParam("checkedToppings") List<String> toppings)
{
//product is null;
//checkedToppings are retrieved correctly
return "redirect:/menu";
}
Short answer:
you don't post objects to controllers using HTML.
Details:
You will never be able to post a "product" object to your controller from an HTML page.
Instead,
you should send identifying information about the desired "product" to the controller,
perhaps a product-id or some other product-unique-identity-blammy.
Response to options in comments:
Hackers love hidden fields and JavaScript;
I recommend against using those for this situation.
I believe that you only have one option: identifying info.
This does not need to be a "real" product number.
You can generate a UUID and store a map in the choose one: (Servlet Session, Database, Application Session, somewhere else on the server) that maps from the UUID to the desired product.

Kendo Mobile - Submit Entire Form

I have a kendo mobile form that I will be using to capture some information from my users.
I would like to post the data to a web service or aspx(test page) using ajax. It seems like overkill to use MVVM for a form that the user fills out and there will be no reads/updates/deletes.
The ajax call happens but I cannot figure out how to post the data . Nothing goes over if i use $(this).serialize(). If I hard code some data, then it works.
There are going to be a lot of controls on the page and i hope i don't have to manually build the form data. I cannot add a <form> tag as it breaks the styling of the page.
If there is a more "kendo" way of doing this please show me how. Thanks
Here is what I have so far.
//Submit Form
function submit_form(e) {
$.post('TestPost.aspx', $(this).serialize(), function (data) {
// This is executed when the call to web service was succesful.
// 'data' contains the response from the request
alert(data);
}).error(function (xhr, ajaxOptions, thrownError, request, error) {
alert('xrs.status = ' + xhr.status + '\n' +
'thrown error = ' + thrownError + '\n' +
'xhr.statusText = ' + xhr.statusText + '\n' +
'request = ' + request + '\n' +
'error = ' + error);
});
e.preventDefault();
}
//Example of html controls
<div id="checks" data-role="view" data-title="Foo" data-layout="checklayout">
<ul data-role="listview" data-style="inset" data-type="group">
<li>Floor
<ul>
<li>
<label for="Foo">
<input type="radio" name="Foo" id="FooOk" value="Ok" />
Ok</label>
</li>
<li>
<label for="Foo2">
<input type="radio" name="Foo" id="FooNotOk" value="NotOk" />
Not Ok</label>
</li>
<li id="Comment1" class="divComment" style="display: none;">
<label>
Comments
<input type="text" name="TextComment" id="TextComment" placeholder="Type Comments" autocomplete="off" tabindex="1" />
</label>
</li>
<li id="C1" class="divComment" style="display: none;">
<label>
Charges
<select id="Charges" name="Charges" >
<option value="nc">test</option>
</select>
</label>
</li>
</ul>
</li>
</ul>
<ul data-role="listview" data-style="inset" data-type="group">
<li>Picture
<ul>
<li>
<label>
Select a Photo
<input type="file" id="kitFile" style="display: none;" />
<a data-role="button" data-click="select" style="float: right;">Select</a>
</label>
</li>
</ul>
</li>
</ul>
</div>
//Submit button
<a data-align="right" data-role="button" class="nav-button" data-click="submit_form">Save</a>
Here $(this) will give u only the button element. The easy way to do this is use the built in MVVM feature in Kendo UI Mobile. create an model as JS object and set data-model attribute of your view as this object. Now on click of the submit button, just send this object to your server using ajax. This way u are reducing the amount of data sent to the server.
Documentation on mobile and mVVM integration: http://docs.kendoui.com/getting-started/mobile/mvvm .
I have used a PageMethod previously.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Would something like this help your cause?
Let's take an example of such a method in the code behind:
[WebMethod]
public static string MyMethod(string Id)
{
return string.Format("Thanks for calling me with id: " + Id);
}
Things to note: the method must be static and decorated with the [WebMethod] attribute.
And on the client side you could invoke this method using the jQuery.ajax() function like this:
$.ajax({
url: 'default.aspx/MyMethod',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ID : ID }),
success: function (result) {
alert(result.d);
}
});
Make sure that in your WebForm you have actually added reference to the jQuery library before using it.
For example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>

ajax script onclick alert to popup message box

I found this voting script online and was wondering instead of a onclick alert(You already voted) can i change it to a popup message that i can style with css... i have only submitted a part of the code if you need to see more let me know. thanks in advance
function addVotData(elm_id, vote, nvotes, renot) {
// exists elm_id stored in ivotings
if(ivotings[elm_id]) {
// sets to add "onclick" for vote up (plus), if renot is 0
var clik_up = (renot == 0) ? ' onclick="addVote(this, 1)"' : ' onclick="<a type="button" class="btn" style="width:100%;" href="#test_modal" data-toggle="modal">alert</a>"';
// if vot_plus, add code with <img> 'votplus', else, if vot_updown1/2, add code with <img> 'votup', 'votdown'
if(ivotings[elm_id].className == 'vot_plus') { // simple vote
ivotings[elm_id].innerHTML = '<h6>'+ vote+ '</h6><span><img src="'+votingfiles+'arrow.png" alt="1" title="vote"'+ clik_up+ '/></span>';
};
}
}
You can use Bootstrap modal pop up instead of alert.
This is well explained example
If you need more help let me know
Update
html for model pop up:
<div class="modal fade" id="test_modal"> <div class="modal-header">
<a class="close" data-dismiss="modal">×</a> <h3>Modal Header</h3> </div>
<div class="modal-body"> <p>Test Alert</p> </div> <div class="modal-footer">
Close </div> </div>
Html for Button
<input type="Button" Text="ShowModal" Id="MyButton"/>
javaScript:
$( "#MyButton" ).click(function() {
$('#modalName').modal('show');
});

CakePHP ajax with Js Helper loads the page rather than the template for success, why?

I am trying to make a form submit through ajax and the JsHelper from CakePHP 1.3
I try to make a call to /eng/feedbacks/submit_feedback but instead in the console, i see a post to http://lang/eng/pa/homepage instead. The result returned is another instance of that page, rather than anything else.
This seems to be irrelevant to whether such submit_feedback exists or not. I have started that action with die("test"); and it doesn't change anything.
why is that, what is going on?
the form is in my layout (as i want it to be in my footer). Runs when the url is /eng/pa/homepage
Form code:
echo $this->Form->create('Feedback', array('url'=>array( 'controller'=>'feedbacks', 'action'=>'submit_feedback')));
echo $this->Form->input('Feedback.content', array('label'=>false, 'type'=>'textarea'));
echo $this->Js->submit('Save', array('class'=>'button blue',
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->Get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();?>
<div id="success">xx</div>
In that #success DIV i get a related full page, rather than what I have defined in the controller action
Controller method:
function submit_feedback(){
if(!empty($this->data)){
$this->Feedback->set($this->data);
if($this->Feedback->validates()){
if($this->Feedback->save($this->data)){
// AJAX
if($this->RequestHandler->isAjax()){
$this->render('/feedbacks/success', 'ajax');
}else{
die('not ajax');
}
}
}
}
}
And the success template is:
<p style="background: lightgreen">Purple cow!</p>
What am i doing wrong?
NOTE: If I run the same form from the /eng/feedbacks/submit_feedback page, It works exactly as it should through ajax, and my database gets updated, i get the necessary 'success' template loaded and all is shiny and happy.
UPDATE: FORM SOURCE COUDE GENERATED:
<form accept-charset="utf-8" action="/eng/feedbacks/submit_feedback" method="post" id="FeedbackReadForm">
<div style="display: none;">
<input type="hidden" value="POST" name="_method">
</div>
<input type="hidden" id="FeedbackUserId" value="141" name="data[Feedback][user_id]">
<div class="input radio">
<input type="hidden" value="" id="FeedbackType_" name="data[Feedback][type]">
<input type="radio" value="suggestion" id="FeedbackTypeSuggestion" name="data[Feedback][type]">
<label for="FeedbackTypeSuggestion">Suggestion</label>
<input type="radio" value="problem" id="FeedbackTypeProblem" name="data[Feedback][type]">
<label for="FeedbackTypeProblem">Poblem</label>
<input type="radio" value="opinion" id="FeedbackTypeOpinion" name="data[Feedback][type]">
<label for="FeedbackTypeOpinion">Other Opinion</label>
</div>
<div class="input textarea">
<textarea id="FeedbackContent" rows="6" cols="30" name="data[Feedback][content]"></textarea>
</div>
<div style="margin-top: 17px; margin-right: 50px;" class="right">
<a onclick="javascript: closeFeedbackPuller(); return false;" href="#">Cancel</a>
</div>
<div class="submit">
<input type="submit" value="Save" id="submit-396027771" class="button blue">
</div>
</form>
UPDATE 2: JS generated:
$(document).ready(function () {
$("#submit-396027771").bind("click", function (event) {
$.ajax({
beforeSend:function (XMLHttpRequest) {
$("#sending").fadeIn();
},
data:$("#submit-396027771").closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#sending").fadeOut();
$("#success").html(data);
},
type:"post",
url:"\/eng\/pa\/homepage"
});
return false;
});
});
I see that the url is wrong, even thought the form url was right. How can this be resolved?
echo $this->Js->submit('Save', array('class'=>'button blue',
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->Get('#sending')->effect('fadeOut'),
'url' => '/eng/feedbacks/submit_feedback',
'update'=>'#success'
));
That may fix your problem, but I am not 100% sure. It seems that the Js->submit() method accepts a lot of the Form helper methods.

Resources