Adding Item to Database in Laravel with AJAX and then showing Item - php

After hours of Googling, I can't seem to find an answer to this seemingly simple problem. I can't add data to a database and show that data without refreshing the page. My goal is to be able to create an object from a form to upload to a database, and then show all the items in database (without the page refreshing). I have tried to get AJAX working many times, but I can't seem to do that. The application works by adding stars to students, so basically I would want to be able to update a students star count without reloading the page. But right now I can't even console.log the submitted form data. My Controller code is like so:
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
return Redirect::back();
}
And my form:
{{Form::open(array('action'=>'HomeController#addStar','id'=>'addStar','method'=>'post'))}}
{{ Form::hidden('id', $student->id, array('id'=>'id_value')) }}
{{ Form::hidden('user_id', $student->user_id, array('id'=>'user_id_value'))}}
{{ Form::submit('+')}}
{{ Form::close() }}
And my extremely poor attempts at AJAX:
$('#addStar').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: '/addstar',
data: $('#addStar').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
The code works fine if I settle for allowing page reloads, but I don't want that. So essentially, my question is, how do I add data to a database and show it without the page reloading? Thanks so much!

Your controller is doing a redirect after the logic, ajax won't be able to do anything with the response. A one take would be, after adding a start returning the new star rating.
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
$star_count = //get new star count;
return Response::json(['star_count' => $star_count]);
}
Since controller now returns a json response, the success callback on $.ajax can grab it and do something (update the star count).

#codeforfood,
If you want to grab the response and show it immediately in the page without a reload then you may go with returning a JSON reponse and then handle that response at the client side Javascript for Success or Failure conditions.
Can try something like this if you want:
In the controller addStar() method response:
$data = ['star_count' => 'COUNT OF STARS'];
return json_encode($data);
In the View for that specific Star Div:
<script>
$('#stardiv).on('submit', function (e) {
$.ajax({
type: 'POST',
url: "{{URL::to('xxxxx')}}",
data: $(this).serialize(),
dataType: "JSON",
success: function (data) {
Handle the success condition here, you can access the response data through data['star_count']
},
error: function (data) {
Handle the error condition here, may be show an alert of failure
}
});
return false;
});
</script>
After all this is just one approach, you may try different one which ever suits your need.

Related

PHP Clickable Row that display data of details?

How can I do clickable tab that display data?
I want to fetch the data from mysql row to the row in the table dynamically and when i open her i will see the details of all the the row in my database. Like in this picture.
https://ibb.co/m0Zmk7
If I didn't get your question wrong, you want to display some data from database when user will click on a row.
You need to call a function on every row just like this:
<tr onclick="somefunction(id)"></tr> OR <div onclick="somefunction(id)"></div>
Also you have to create a div where your data will be populated.
<div id="display_data"></div>
And then JS function would be just like:
<script>
function somefunction(id){
$('#display_data').remove(); //it will remove all the data before loading new record.
$.ajax({
url: "pathOfYourFile/function/",
type: "post",
data: {
id: id
},
success: function (data) {
if(data.status==1){
alert("success");
$('#display_data').show();
$('#display_data').append(data.message);
}else{
alert(record error);
}
},
error: function (data) {
console.log(data);
}
});
}
<script>
And in the end you have to write a function in php that will get your data from database. Just make sure that you will return data just like this:
$data['json_data'] = array('status' => 1,
'message' => $record
);
I Hope this will work in your case. Please do not hesitate to ask a question if there is any confusion.

How can I return view inside actual view (in same page)?

I'm learning Laravel and I have a view with a contact list and inside of this table I have a button to display more details about the clicked item. I want to return a view inside the actual view, I don't want to go to another page.
Someone can explain me how can I do that and show me examples of that if it is possible?
I already try do that using ajax but I don't now how can I return a view without go to other page.
$("#detailsItemSize").click(function()
{
var itemId = $(this).attr('data-id');
alert("details");
alert(url);
$.ajax
({
method: 'GET',
url: url + "/" + itemId,
data: {'itemId': itemId, _token: token }
});
.done(function (msg)
{
console.log(msg['message']);
});
});
Best regards
The basic premise is to have a route that renders your partial view:
Route::get('item/{item}', function($itemId){
$someitem = Item::findOrFail($itemId);
return view('partial', compact('someitem'));
});
//partial.blade.php
<h1>Items id is {{$someitem->id}}</h1>
//main view
<div id="details></div>
//js
$.get('/item/27', function(response){
$('#details').html(response);
});
the #details div in the page will contain <h1>the items id is 27</h1> when the ajax call returns

Get the class name from returned value of POST in Ajax

I have two dropdown lists and on selecting the data I used ajax to send it to a php file where I retrieved a table and send the whole table contents as per my query fields and I display it via
jQuery("div#tablecontent").html(returnval);
But now i want to edit, delete the table view I displayed and I tried to get the class of the row I returned. But couldn't please guide me in how to get the class of the field I returned as whole table.
EDIT : Adding the code i ve done
jQuery(document).ready(function(){
jQuery("#select1").change(function(){
jQuery.ajax({
type: "POST",
url: "<?php echo $base_url;?>?q=search/won",
error: function(returnval) {
alert("Failure");
},
success: function (returnval) {
// alert(returnval);
jQuery("select#fileds_content").html(returnval)
//alert("Sucess");
}
})
//
jQuery("#fileds_content").change(function(){
if(jQuery(this).val()){
var datawon = jQuery(this).val();
jQuery.ajax({
type: "POST",
url: "<?php echo $base_url;?>?q=getbases/won",
data:{ datawon : datawon},
error: function(returnval) {
// alert(returnval);
// alert("Failure");
},
success: function (returnval) {
// alert(returnval);
jQuery("div#tablecontent").html(returnval);
//alert("Sucess");
}
})
I am not entirely sure what you actually want to do, but from what I understood is that you cannot select a newly created element by its class. In that case, you cannot select a newly created elements because js does not know about it yet, thus, you can use something like .ajaxComplete(), this will make sure to run a function After an ajax call got completed.

how to perform multiple ajax queries within an ajax block

am working on a project in which i use ajax, jquery, php and sql to manipulate data.
function fetchComments(commentOnId, commentOn){
if(!isNaN(commentOnId) && commentOnId >=0){
$.ajax({
type: 'POST',
dataType: "json",
url: 'get_comments.php',
data: 'commentOnId='+commentOnId+'&commentOn=blogArticle',
success: function(data){},
error: function(){
}
});
}
}
the above function uses the 'commentOnId & commentOn' passed to it to fetch all comment on that that particular blog id in json format.
the result/rows in my comment table are as follows.
id
commentOnId
commentOn
commentText
authorId
created
what i want to do is get the values of these rows and in this same function run another ajax query which i will pass the authorId to a php file that returns an authors's full name from a table called authorDetails,
and also use the id value to run another ajax query to return all replies on this comment id or null if there is no reply. and finally update a html div '' with the result.
please, i will appreciate your quick comprehensive assistance. thank you.
You can use SQL joins to get all your needed data in one request if you don't want other details on user iterative basis.
If I were you, I would fetch everything in a single Ajax call rather than perform another Ajax call.
If you want multiple Ajax calls, you can do the following.
function fetchComments(commentOnId, commentOn){
if(!isNaN(commentOnId) && commentOnId >=0){
$.ajax({
type: 'POST',
dataType: "json",
url: 'get_comments.php',
data: 'commentOnId='+commentOnId+'&commentOn=blogArticle',
success: function(data){
$.ajax({
type :'post',
url : 'get_auth_details.php',
data : 'authorId=' + data.authorId,
success : function(data) {
Update div logic goes here
}
}
},
error: function(){
}
});
}
}

$this->data empty after performing an ajax call

I am implementing a function populatig a select box using data from another select box.
//views/users/ajax.ctp
$.ajax({
url: url,
type: "GET",
dataType: "html",
data:"arr=" + result,
success: function(data){
document.getElementById(child).innerHTML = data;
}
});
As you can see from the code above the data passed by the call should be accessible in the getSectors() function under the data variable:
//controllers/users_controller.php
function getSectors() {
$this->set('data', $this->data);
$this->render('/users/ajax_data');
}
In the corresponding view I try to see the content of the data passed:
//views/users/ajax_data.ctp
<?php var_dump($data); ?>
The $data is null.
Debugging that in Firebug shows that the call is invoked properly (status 200 ok) and that the XMLHttpRequest contains parameters and values.
Do you have any suggestions what could be possibly wrong?
In order for Cake to populate the $this->data variable, the data being send needs to follow the format data[Model][field], or at least be part of the data[..] array. If it's plainly named arr, Cake won't put it in the $this->data variable.

Categories