Laravel 5.5 send data to view without reloading page - php

In my view I have some data that I can use $data in this $data are several other arrays with a key. Now my goal is to when a user selects something from a dropdown I want to update this $data array without doing a redirect.
I am aware I need to use AJAX and my AJAX call works fine I am just a tad confused on what I am supposed to do in my controller method I need to do something like this but without refreshing the page but this would remove all my other data that is already in the $data array from before
This is my method:
/**
* Fetches a company
*
* #param $companyId
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
$data['company'] = $company;
return view('this should be the same view that I did my ajax call from', ['data' => $data]);
}
So I want to add this $company to the already existing $data array that I am using in my view.

Answering from what I have understand so far.
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
then you need to call ajax like this
<script>
$(document).ready(function(){
$("whatever your dropdown id").change(function(){
$.ajax({
url:'yoururl',
type: 'whatever datatype',
dataType:'json',
success: function(data){
var x;
for(x in data){
$("#div1").append(data[x]);
}
}
});
});
});
</script>

Related

I want to pass array of IDs to route in Symfony

this is my controller:
/**
* #Route("/order", name="finish")
*/
public function createAction(Request $request)
{
$form = $this->createForm(OrderType::class);
// get data using the ids pass to the request...
// handle the form and redirect to homepage
return $this->render(
"orders/order_view.html.twig",
['order'=>$form->createView()]
);
}
I would like to pass some IDs to the request so i can get the needed data with doctrine.
After that handle the form create new order and add to it the products that i already have thanks to the ids passed.
i tried passing the ids using ajax on button click:
$.ajax(
{
type: 'POST',
url: '/order',
data: {'arr':[2,3,4]} // sample ids
}
).done(function (data) {
console.log(data)
}).fail(function () {
console.log("some error")
})
but it just returns the HTML. What i need is to render the form in the specified route ("/order") so i can handle it and insert into the database the new order with products added to it
I here answered to like this question:
Symfony2.8. How to get data from post request
You can use for POST request :
$request->request->get('data');
For GET request:
$request->query->get('data');
For FILE queries:
$request->files.

Pass a variable with JQuery to the Controller - PHP Codeigniter

I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});

Symfony JsonResponse: Fetching each element of multidimensional array returned by symfony controller

basically what I am trying to do is trying to fetch each element from the array of "arrays" passed by symfony controller when I try to fetch all the rows of the table. my controller is working absolutely fine, and giving me output:
[{"id":1,"name":"johnsonn's baby shampoo","dsc":"shampoo","pic":"572f8a02d59b3.jpg","company":4,"type":"baby products","price":150,"sold":null,"stock":200},{"id":2,"name":"johnson's soap","dsc":"baby soap","pic":"57303fc35f72c.jpg","company":4,"type":"baby products","price":52,"sold":null,"stock":1000}]
and my javascript for fetching this output is the following:
<script>
function fetchprod() {
$.ajax({
url: "/show/prod",
dataType: "json"
}).success(function(data){
$('#container').html(JSON.stringify(data));
});
}
fetchprod();
setInterval(function () {fetchprod()}, 3000);
</script>
what I wanna do is fetch each element of each array separately so that I can place create a div out of them so they could be arranged in a grid properly.
also the array is fetched by symfony controller (if you need an extra info):
public function showAction($slug){
$em = $this->getDoctrine()->getManager();
if($slug == 'prod'){
$repo = $em->getRepository('SystemBundle:Products');
$q = $repo->createQueryBuilder('u')
->getQuery()
->getArrayResult();
return new JsonResponse($q);
}
}
Since you're using jQuery, maybe you could use the each method:
// ajax call
.success( function (data) {
$.each(data, function(key, value) {
var div = '<div>' + JSON.stringify(value) + '</div>';
$('#container').append(div);
});
});
// close function
In this way you iterate over every object in the array, place it in a div, and after that append it to the #container.
It should create something like:
<div id="container">
<div>{"id":1,"name":"johnsonn's baby shampoo","dsc":"shampoo","pic":"572f8a02d59b3.jpg","company":4,"type":"baby products","price":150,"sold":null,"stock":200}</div>
<div>{"id":2,"name":"johnson's soap","dsc":"baby soap","pic":"57303fc35f72c.jpg","company":4,"type":"baby products","price":52,"sold":null,"stock":1000}</div>
</div>

How to get data attribute to controller from ajax?

I’m having trouble passing my $_POST variable to my controller from an jQuery/ajax request.
Ultimately I want to be able to use that to update a field in my database.
My problem is that in trying to access $_POST[‘quantity’] in my controller. I keep getting the notice quantity is undefined and I’m var_dumping it and it’s null.
I’m new to jQuery/ajax and I’m not really sure how to go about fixing this issue. I could really use help in getting the data attribute, quantity, in my ajax request to my controller and understanding why $_POST[‘quantity’] is null.
I hope I am clear in my questioning and thanks for your help!
Controller function:
/**
* Updates quantity using ajax/jQuery request from showCart twig file
*
* #Route("/{id}/quantityUpdate", name="product_quantityUpdate")
* #Method("POST")
* #Template()
*/
public function quantityUpdateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$productId = $em->getRepository('ShopBundle:Product')->find($id);
$cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
$quantity = $em->getRepository(ShopBundle:Quantity')->findOneBy(['quantity' => $productId->getId()]);
var_dump($this->get('request')->request->get('quantity'));
$quantity = isset($_POST['quantity']) ? var_dump($_POST['quantity']) : false;
// $quantity->setQuantity(/* Code for finding correct product to update quantity */);
// $em->persist($quantity);
// $em->flush();
return new Response ("This has been successful!");
}
twig / ajax & jQuery:
<script type="text/javascript">
$(".spinner").spinner();
$('input.spinner').on('spinstop', function(){
min: 0
console.log('spinner changed');
var $this = $(this);
var value = $('spinner').val();
var request = $.ajax({
url: "{{ path('product_quantityUpdate', {'id': prodId }) }}",
method: "POST",
data : {
quantity: value
}
}).done(function(result){
console.log('success', result);
}).error(function(err){
console.log('error');
});
});
</script>
Change
var value = $('spinner').val();
to
var value = $('.spinner').val();
Your selector is having problem as I see that is missing.
If you have multiple elements with same class then better use this.value;

Filtering dropdown menu's with ajax and PHP

I have a CodeIgniter MVC application.
I have a model called city that has a method:
<?php
class Cities_model extends Model{
function Cities_model(){
parent::Model();
}
function get_cities($id = null){
$this->db->select('id, city_name');
if($id != NULL){
$this->db->where('country_id', $id);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->city_name;
}
return $cities;
}else{
return FALSE;
}
}
...
Controller:
function Post(){
$this->load->helper('form');
$this->load->model('cities_model');
$this->load->model('country_model');
$this->load->model('field_model');
$data['cities'] = $this->cities_model->get_cities();//optional $id parameter
$data['countries'] = $this->country_model->get_countries();
$data['fields'] = $this->field_model->get_fields(); //subject field
$this->load->view('post_view',$data);
}
This method is used to fill the contents of a dropdown list. I have a similar model for countries, which also has a dropdown.
You can see that the get_cities method is set up to accept a country_id. This would be used to filter the results if a country was selected.
My question is I need help calling this method using Ajax (preferably jQuery). I'm new to ajax and have never done anything like this before.
Any help most appreciated!
Billy
UPDATE
I've added jquery library and have created method in my controller:
function get_cities($country){
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
here is my javascript on my view:
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>home/get_cities/"+country_id,
data: ({country : country_id}),
success: function(cities){
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
});
});
});
This is the json reply:
[{"2":"Accra"}]
So it is successfully retriving the correct data. the only problem is it's adding blank values/text to the drop down. and each time I change the city the data is being added on, so I guess i'd have to clear the dropdown first?
extending Alpesh's answer:
you should have a controller's function which return cities filtered by country:
/controller/get_cities/<country>
i'm assuming that your controller's function will return a json object, you can obtain it by doing:
function get_cities($country)
{
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode(array($this->cities_model->get_cities($country))));
}
then on the view you'll have 2 select boxes:
one filled up with the contries
one empty and to be filled up with the cities retrived via ajax
now, you have to write something like Alpesh did in order to retrive the cities of the selected country; URL will be
url: '/controller/get_cities/'+country_id
while the success function would be something like
success: function(cities)
{
$('#cities').empty();
$.each(cities,function(i,city)
{
var opt = $('<option />');
opt.val(city.value);
opt.text(city.text);
$('#cities').append(opt);
});
}
UPDATE
in your ajax success function you are dealing with a json objects, infact you are doing this:
opt.val(city.value);
opt.text(city.text);
where city is a json object and value and text are its properties.
when you generate the json via php you have to respect what you use in jquery so your model should return an array like this:
array
(
array("value"=>"2","text"=>"Accra"),
array("value"=>"3","text"=>"Kumasi"),
....
);
the json_encode that array and it should work. Maybe you don't need to wrap the model call into an array but i'm not sure depens on how you return the array
echo(json_encode(array($this->cities_model->get_cities($country))));
or
echo(json_encode($this->cities_model->get_cities($country)));
You can do it this way by jquery -
lets say you have 'country' as an id for the select for country -
then on change of country you can bring it's specific cities as follows -
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "the url you want to call",
data: ({id : country_id}),
success: function(cities){
//populate the options of your cities dropdown here.
}
});
});
});
you can refer detailed documentation here -
JQuery
Ajax API
Ajax

Categories