I have a modal which opens on click:
jQuery('.calendar-day-update-edit-trigger').click(function(event){
var targetDate = jQuery(this).attr('data-day');
jQuery('.updater-date-edit').html(targetDate);
jQuery('.hidden-date-input-edit').val(targetDate);
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
})
});
I want to send the data to a blade file so I can query my database.
public function getData($getData){
$data = Day::where('sale_at', $getData)->first();
return $data;
}
Hello,
If you want to return data from your controller to your template, you must return your data in json.
After this, you can use the success method in your ajax call to get the data from your controller and affect these data to an or more HTML elements in your blade template.
In your JS:
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
success: function(data) {
$('#your_html_element').val(data);
}
})
In your PHP:
header('Content-Type: application/json');
echo json_encode($data);
In your blade template:
<div id="your_html_element"></div>
Related
In my page
$(document).ready(function(){
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>total',
data:'id=1',
beforeSend:function(){
$('.searc_res').show();
},
success:function(html){
$('.searc_res').remove();
$('.searc_res').append(html);
}
});
});
This is just to return in the div the value of a session
Session is: $this->session->userdata('searchItems_Total')
How to do this in the total.php file?
Do I need to create something in the model?
Just print it?
public function total()
{
header('Content-type: application/json');
/.../
echo json_encode($this->session->userdata('searchItems_Total'));
}
In your client side call (to view the returned data's structure):
$.ajax({
...
success: function(resp){
console.log(resp);
});
You can just return $this->session->userdata('item'); in your php function or you can just echo the values in your html since you are trying send an ajax request in document ready state which is not necessary.
I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);
I would like this function:
After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?
Here's my HTML:
<select id="category1" name="cat1">
<option>Hardware</option>
<option>Software</option>
<option>Network</option>
</select>
AJAX code:
$('#category1').on('change',function(){
var data = $("cat1").val();
var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
if(data){
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo base_url();?>User/TicketView/update_cate",
data: {data: data,ticket: ticket},
success:function(response){
alert('successful');
},
error: function(response){
alert('tangina!');
}
});
}
});
Controller:
function update_cate(){
$this->TicketView_m->update_cat1();
redirect($_SERVER['HTTP_REFERER']);
}
Model:
function update_cat1(){
$ticket_id = $_POST['ticket'];
var_dump($cat = $_POST['data']);
$this->db->set('vCategory',$cat);
$this->db->where('cTicketNo',$ticket_id);
$this->db->update('tconcerns');
}
THanks for all the help!
Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.
First of all, AJAX will allow you to send data to server without redirecting to another page.
Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).
Then you can access it in your response like this:
success:function(response){
alert('successful');
var res = response.result; //Access the JSON
$("#certainDiv").html( res ); //Print to the div you want
}
And it is also better to get the post request in your controller then pass it to your model:
function update_cate(){
$ticket_id = $this->input->post('ticket');
$cat1 = $this->input->post('cat1');
$this->TicketView_m->update_cat1($ticket_id, $cat1);
echo json_encode(['result' => 'things you want to show']);
}
The model seems to be working as well as the controller. The AJAX displays the results as "null" so I think it is because we need to send the data as json. Any ideas on how to get the data into the correct format and to display in the view
View
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table' style="color:white;">
hola amigo
</div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'index.php/trial/getValues';?>',
type:'POST',
dataType: 'json',
error: function(){
$('#result_table').append('<p>goodbye world</p>');
},
success: function(results){
$('#result_table').append('<p>hello world</p>');
} // End of success function of ajax form
}); // End of ajax call
});
</script>
Controller
function getValues(){
$this->load->model('get_db');
$data['results'] = $this->get_db->getAll();
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
in your view, you set your data type to json so you need a controller that it's generate a json output. codeIgniter has a system to generate this type. you can use this code in your controller to do that:
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $data ));
and in ajax success get your response and use it:
success: function(response){
server_res = JSON.parse(response);
console.log(server_res);
$('#result_table').append('<p>hello world</p>');
}
just print/echo the $data in controller if you want html form(dont return). If you want json then print/echo json_encode($array)
and in success ajax write
success: function(results){
$('#result_table').append(results.arraykey);//arraykey=array key from controller
} // End
In the controller just use this
function getValues(){
$this->load->model('get_db');
echo json_encode($this->get_db->getAll());
}
And in the view
success: function(results){
results = JSON.parse(results);
$('#result_table').append('<p>hello world</p>');
}
On my page I have a form that inserts a new record in to the database. On the same page there is a DIV that contains the current resultset.
What I am trying to do is refresh just that DIV (not the whole page) when the form is submitted. The DIV will then contain the latest records (including the one just added).
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
});
return false;
});
<div id="current-rows">
<?php while($variant=mysql_fetch_array($variants)) { ?>
<div class="row">
// resultset
</div>
<?php } ?>
</div>
I set $variants from within my controller (beforehand):
$variants=Catalog::getProductVariants($product['id']);
Ideally I don't want to be returning a whole load of HTML to be injected in to that DIV.
Set the new content in the success handler of ajax request. Try this
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent){
$('#current-rows').html(newContent);
}
});
return false;
});
I think it is easier to use .load method, which injects the response from the server to the given div, something like:
$('#idOfYourDiv').load('/your/url', {params: params});
alternatively you can still use $.ajax, like:
$('#add-variants-form').submit(function(){
$.ajax({
url: 'admin/addvariants',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(data) {
$('#yourDiv').html(data); // html will insert response, response is stored in "data" variable
}
});
return false;
});
on php site just echo what you want to be displayed, for example
foreach($results as $result){
echo $result."<br />";
}
hope that helps
I have put the contents of the "current-rows" div into it's own seperate view file:
<div id="current-rows">
<?php include("_current-rows.php"); ?>
</div>
And in my controller 'addvariants' action I just do this:
$variants=Catalog::getProductVariants($_POST['product_id']);
include('application/view/admin/catalog/_current-rows.php');
That is the response that is passed back to my jQuery success function.