How can I get the serialized data in the Controller?
For example i have this data...
var str = $('#edit-form-data').serialize(); //string
I pass it inro the function like this...
editDosage(urlEdit,str);
My function is like this...
function editDosage(url,res)
{
console.log(url);
$.ajax({
url: url,
method: 'POST',
data: res,
success:function(data){},
error: function(data){}
});
}
How do I get the input value of the serialized data in the Controller in Laravel?
For example, I have included in the edit-form-data the name of the 'store_id' and I want to access it in the controller. Can I do something like?
$store_id = Input::get('store_id');
dd($store_id);
you may also use,
$(document).ready(function() {
$('#edit-form-data').ajaxForm();
});
checkthis out: http://malsup.com/jquery/form/
Or check this one:
$(document).ready( function(){
$(document).on('click','#submitButton', function(){
var _this = this;
var request = $.ajax({
url: url,
type: "POST",
data: jQuery("#form").serialize(),
dataType: "json"
});
request.done(function( msg ) {
});
request.fail(function( jqXHR, textStatus ){
});
});
});
And in php
try {
// input code
if($_REQUEST){
echo json_encode("success");
} else {
echo json_encode("checkinput");
}
}catch (Exception $e){
echo $e->getMessage();
echo json_encode("error");
}
You can use a few different ways to get the input.
From the Request
If your function has a Request parameter, it you can get the input from it.
public function methodA(Request $request) {
$data = $request->all();
}
You can view the documentation on Requests here.
Input Facade
Similar to requests you can use the Input Facade to get the inputted data.
public function methodB() {
$data = Input::all();
}
You can view the API docs for the Input Facade here.
Jquery code
$.post('/ajax', {'_token': $token,data: $this.serialize()}, function(resp) {
/*optional stuff to do after success */
});
controller function##
public function CreateBill()
{
parse_str($_POST['data'], $data);
return $data;
}
Related
I'm getting
ReferenceError: Y1ohe1oTVVG6916 is not defined
response when viewing my console. This happens while trying to pass two parameters via Ajax. Y1ohe1oTVVG6916 is the unique identifier for this input.
AJAX:
function checktickets(val)
{
var myserial = <?= $row['eventserial']?>; //this outputs the unique identifier Y1ohe1oTVVG6916
$.ajax({
type: "POST",
url: "<?php echo base_url();?>welcome/gettickets",
data:{
id:val,
evtsr:myserial
},
beforeSend :function(){
$(".numberoftickets option:gt(0)").remove();
$('.numberoftickets').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
/*get response as json */
$('.numberoftickets').find("option:eq(0)").html("Select Number of Tickets");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
console.log(data);
alert(data);
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.numberoftickets').append(option);
});
/*ends */
}
});
}
CONTROLLER:
public function gettickets() {
$evt =$_POST['evtsr'];
$tkt =$_POST['id'];
$query = $this->db->query("SELECT * FROM events_tickets where event_serial ='$evt' AND tickets_id='$tkt'");
$data=array();
foreach($query->result_array() as $key=> $r)
{
for($i=1; $i<=$r['ticket_max_allowed_buyer']; $i++)
{
$data['value']=$i;
$data['label']=$i;
$json[]=$data;
}
}
echo json_encode($json);
}
If I remove the second parameter evtsr:myserial from ajax function and readjust my query from the controller, everything works, but I need this second parameter to be included so as to sort the selection more.
There is only one possible explanation I guess.
Try using the declaration like this :
var myserial = '<?= $row['eventserial']?>';
Please reply if it works. I'm curious whether that is the problem
I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.
Just starting to learn about ajax although I am running into trouble trying to return a success message in an array.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function (response) {
if (response.success) {
alert('Saved!');
} else {
alert('Some error occurred.');
}
});
});
});
</script>
<?php
$array = array();
$array['success'] = TRUE;
echo $array;
?>
response.success should refer to $array['success'] correct?
You are trying to echo your array, which will just spit out "Array".
Instead you need to encode your array as JSON and echo that out.
Change this:
echo $array;
To this:
echo json_encode($array);
Also you probably need to add your dataType in your ajax params so jQuery auto-parses the response:
dataType : 'json' // stick this after "data: $form.serialize()" for example
Also, here's a good post to read on how to properly handle success/errors with your ajax calls (thanks #Shawn):
Jquery checking success of ajax post
How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on
I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!