Eloquent only updates the first record via ajax - laravel

i have a problem updating via ajax and eloquent.
I am making an .ajax in jquery :
$('#button-acept').on("click",function(event) {
event.preventDefault()
$.ajax({
url: '{{ URL::to('/')}}/note_acept/{{$note->id}}',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.message);
$('#alert-acepted').show();
$('.navbar-hide').hide();
}
});
});
and the action of the url:
public function acept_note($id){
$note = Noticia::find($id);
$note->acept = true;
$note->save();
return Response::json(array('message'=>"The note has been acepted"));
}
The strange thing it's that when de note id it´s 1 it updates the acept field correctly, but if the note has any other id ( what it's obvious) it doesnt work.
I also tried with the query builder and it updates correcty but i also have a problem about giving points to the users.
This it's working:
DB::table('notes')
->where('id', $id)
->update(array('acept' => true));
but when i try to use other eloquent update at the same function it doesn't work.

I had this problem and its actually simply because you are using an id instead of a class. So when ajax runs, it expect only one element to be clicked. It will only care for the first row of your table.
Instead of using #, use .
Rename your '#button-acept' to '.button-acept'.. In your html, change your button to use class= instead of id=
I hope i'm not too late to answer this!
Cheers!

Related

Print fetched data with ajax in codeigniter

I am trying to make chat room with ajax. Till now I am able to store data in db without page load. And also able to fetch data and display onscreen using ajax. Here is what I did with ajax
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val(); //chat message from input field
var chatroomid = $("#chatroomid").val(); //hidden input field
$.ajax({
url: baseurl+'User_dash/chatmessage', //An function in ctroller which contains only insert query
type: 'post',
data: {chatmsg:chatmsg, chatroomid:chatroomid},
dataType: 'json',
success: function (argument) {
if(argument['status']){
$("#chatting").append(" <li id='"+getvalue+"'>"+argument['msg']+"</li>."); //Here I am printing chat message which resently submitted in database
}
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
This method with ajax is working fine. But issue I faced here is that, this display chat message only to current user. Not to other side of user whome message is being sent via chat.
To solve this issue I come up with one idea which doesn't seems to be working as I planed. Here it is how I modified my previous ajax code..
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val();
$.ajax({
url: baseurl+'User_dash/chat', //controller function which contains insert query, after that select query to fetch chat data from db and store in view
type: 'post',
data: {chatmsg:chatmsg},
dataType: 'json',
success: function (argument) {
if(argument['status']){
//Not doing anything here this time
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
In updated version of script I thought If I will call a controller function which is storing data in view (chat page) then It will run query and print data without page load.
But with this method, I am getting chat onscreen only after page load, although it is getting submit in db with ajax fine.
Here is controller code for my second method with ajax if needed
public function chat(){
if(!empty($_POST['chatmsg'])){
$chatdata = array('CHAT_ROOM'=>$_POST['chatroomid'],
'VENDOR'=>$this->session->userdata('USER_ID'),
'BUYER'=>49,
'MESSAGE'=>$_POST['chatmsg']
);
$this->db->insert('tbl_chat', $chatdata); //inserting data
}
$data['chatroom'] = $this->db->where('CHAT_ROOM', 1)->get('tbl_chat')->result_array(); //fetching data from db
$this->load->view('userDash/chat', $data);
}
How do I achieve to run insert and then select query and print data on screen without page load?
Where I am getting wrong?
I solved my issue earlier, What I did was, just added this jquery script which keep refreshing (every second) a certain div inside page in which I have put query to fetch chat from db and printing them.
setInterval(function(){
$("#chatting").load(location.href + " #chatting");
}, 1000);

How to pass variables from Controller to View without refreshing the Web Page in Laravel?

Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}

Ajax data not being sent to controller function (CodeIgniter)

I have an anchor tag and would like its data-id to be sent to a function in the controller which would in turn retrieved data from the database through the model.
However the data is not getting past the controller. The ajax response is showing that the data was sent but controller shows otherwise.
Here is my ajax code:
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url();?>Designs/business_cards",
type:"POST",
data:{sub_item_id:sub_item_id},
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I had set datatype:"json" but the data was not being sent so I removed the datatype and it worked,the ajax part that is.Or atleast the response showed that data was sent.
My controller code is:
function business_cards(){
$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id);
$this->load->view('category/business-cards',$data);
}
My model code is:
public function get_quantities($sub_item_id){
$this->db->select('quantities');
$this->db->where('id',$sub_item_id);
$query = $this->db->get('sub_products');
return $query->result_array();
}
HTML Code which includes the anchor tag
<?php foreach ($results as $object):?>
View Prices
<?php endforeach?>
The data-id is displaying the correct value as per the iteration.
When I check the result array of the model code it is an empty array showing that the $sub_item_id was not passed in the controller. What could be the problem?
I just copied your code and I was able to get the value in the controller.
In your controller function do var_dump($id). Then in your developer tools (F12) check the console. Since you have console.log(data) that var_dump should be in the console. It won't show on the screen.
Some other things to check:
Does your db have records with that ID? Could your db result array be empty because it actually should be?
Are you sure that the data-id actually has a value when you click the tag?
it is not passed to the controller because you forgot to put a parameter inside the function of your controller.
Note: you cannot use input post because you're not using form.
function business_cards($id){ //put a parameter here, serve as container of your passed variable from **ajax**
//$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id); //pass the id to your model
$this->load->view('category/business-cards',$data);
}
change your ajax code to this..
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url('Designs/business_cards/"+sub_item_id+"');?>", //pass the id here
type:"POST",
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});

Ajax function, live call?

I have a little box in my sidebar populated by ajax. I have 2 ajax function: one adds items to the list and the second deletes them if the user clicks on the delete button. My html is a simple unordered list like so:
<ul id="listaruta" class="lista">
<li>Item</li>
<li>Item</li>
</ul>
Everytime I call any of the two functions they will replace the ul list with an updated one (selecting the items from the database after inserting or deleting). They work fine until I want to delete right after I inserted an item to the list.
My ajax function for inserting (the other one is very similar):
var valor=$("#alcrearuta").attr('class');
$("#alcrearuta").click(function(){
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "url=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
My ruta.php file gives me another ul list with the same structure as the original, just with the items updated.
As far as I understand this, since I update the ul via my ajax function, the other function doesn't know that the list was updated, it only "remembers" the older list so it does nothing. If I refresh the page, it wil delete with no problem. I'm guessing this would be solved by using live()? But I have no clue...
EDIT: Ok so now I can get my ajax call to work, except that when I delete right after I update, the value that I'm passing to the ruta.php file (the variable that will help me find the field I need to delete from database) will be set to 'undefined' giving me a query like so: Select id from poi where url='undefined'
Again, if I reload, it will work. The change I did to the ajax function was:
$("#alcrearuta").live('click',function(){
$.ajax({
....
});
});
The problem is that you are saving the value of the attribute at the beginning of the request, you should save it in the click event:
$("#alcrearuta").click(function(){
var valor=$(this).attr('class');
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "url=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
Hope that helps.

CI + AJAX, Double posting + refreshing of page

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..
Just realised I was using a input type="submit", rather than input type="button".
Doh!

Resources