I am trying to add comment using AJAX technology but I have an error:
Failed to load resource: http://localhost:8888/blog/public/comment/add the server responded with a status of 500 (Internal Server Error)
Here is my code:
View:
{{ Form::open(array('method'=>'post','class'=> 'col-md-6','url' => '/comment/add', 'id'=>'comment')) }}
<input type="hidden" name="post_id" value="{{$id}}">
<div class="row">
<div class="inner col-xs-12 col-sm-12 col-md-11 form-group">
{{Form::label('name', 'Imię')}}
{{Form::text('username', null, array('class'=>'form-control', 'id'=>'name', 'name'=>'name'))}}
</div>
<div class="inner col-xs-12 col-sm-12 col-md-12 form-group">
{{Form::label('message', 'Wiadomość')}}
{{Form::textarea('message', null, array('class'=>'form-control', 'id'=>'message', 'name'=>'message', 'rows'=>'5'))}}
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12 submit form-group">
{{Form::submit('Wyślij', array('name'=>'submit', 'class'=>'btn btn-orange'))}}
</div>
</div>
{{ Form::close() }}
Controller:
public function addComment()
{
$this->layout = null;
//check if its our form
if(Request::ajax()){
$name = Input::get( 'name' );
$content = Input::get( 'message' );
$comment = new Comment();
$comment->author = $name;
$comment->comment_content = $content;
$comment->save();
$postComment = new CommentPost();
$postComment->post_id = Input::get('post_id');
$postComment->comment_id = Comment::max('id');
$postComment->save();
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return 'yea';
}else{
return 'no';
}
}
AJAX:
jQuery( document ).ready( function( $ ) {
$( '#comment' ).on( 'submit', function(e) {
e.preventDefault();
var name = $(this).find('input[name=name]').val();
$.ajax({
type: "POST",
url: host+'/comment/add',
}).done(function( msg ) {
alert( msg );
});
});
});
And the last one routes:
Route::post('comment/add', 'CommentController#addComment');
Anyone have an idea where is the problem and why I can't submit my form?
You are not posting any data,
$.ajax({
type: "POST",
url: host+'/comment/add',
}).done(function( msg ) {
alert( msg );
});
The error you are getting is that the columns in DB cannot be null.
Try to change your ajax call to this:
$.ajax({
type: "POST",
url: host+'/comment/add',
data: { name:name, message:message, post_id:postid },
success: function( msg ) {
alert( msg );
}
});
Change this
var name = $(this).find('input[name=name]').val();
to
var name = $('#name').val();
and fetch the message and the post id:
var message = $('#message').val();
var postid = $('#post_id').val();
Complete ajax block:
$('#comment').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
var message = $('#message').val();
var postid = $('#post_id').val();
$.ajax({
type: "POST",
url: host+'/comment/add',
data: {name:name, message:message, post_id:postid}
success: function( msg ) {
alert( msg );
}
});
});
And finally, add an ID to the hidden field:
<input type="hidden" name="post_id" id="post_id" value="{{$id}}">
Send data back from Laravel controller, eg.
// ........
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response); // <<<<<<<<< see this line
}else{
return 'no';
}
}
This will send the data in your response back to your ajax request.
Then, alter your ajax success function:
// .......
success: function( msg ) {
$("body").append("<div>"+msg+"</div>");
}
// ..........
You will now see that a new div was created in your <body> including the created response. If you want to show the newly created post, just create it as the ajax response and append it to any element in your page.
Just modifying the ajax block of baao's answer. You can pass data as serialized.
$('#comment').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: host+'/comment/add',
data: $(this).serialize(),
success: function(msg) {
alert(msg);
}
});
});
All the field values of the form can be passed using the serialize() function.
Related
I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
To preface this question, I have a basic understanding of PHP and AJAX. I was asked to design a simple form that would ask the user to select one of two car manufacturers, which would return all models of the selected make from the multidimensional array created in the data.php file. So far this is what I was able to come up with:
index.php
<body>
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="Submit" type="submit" id="submit">
</form>
<h2>Models:</h2>
<div id="results"></div>
</body>
data.php
<?php
$data = array(
array('make' => 'Ford', 'model' => 'Fiesta'),
array(''make' => 'Ford', 'model' => 'Focus'),
array('make' => 'Ford', 'model' => 'Mustang'),
array('make' => 'BMW', 'model' => '320'),
array('make' => 'BMW', 'model' => 'X3'),
array('make' => 'BMW', 'model' => 'X5'),
);
?>
ajax.php
<?php
require_once( 'data.php' );
$myJSON = json_encode($data);
echo $myJSON;
?>
function.js
$(document).ready(function() {
"use strict"
console.log("Document loaded...");
$('#submit').click(function( event ) {
event.preventDefault();
console.log("Submit button was clicked");
run_ajax();
});
var run_ajax = function() {
var results = $( '#results' );
var formData = $( '#make' );
$.ajax({
type: 'get',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
console.log("Before Send");
},
success: function( response ) {
console.log("Success");
},
});
var xmlhttp = new XMLHttpRequest();
var carModel;
xmlhttp.onreadystatechange = function() {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
console.log("testing");
carModel += myObj[x].model + "<br>";
document.getElementById("results").innerHTML = carModel;
};
};
};
});
I am able to get the Success message to display in the console but I cannot get anything to display in the 'results' div in index.php. Does anyone know where I am going wrong? I have searched related topics but couldn't find anything regarding pulling data from a local file. Thanks in advance for any and all help!
Got it working now, thanks for the help everyone!
function run_ajax(make) {
var results = $( '#results' );
var msg = "";
$.ajax({
type: 'get',
url: 'ajax.php',
data: make,
dataType: 'json',
beforeSend: function() {
console.log("Before Send");
},
success: function( response ) {
console.log("Success!");
for(var x in response) {
if(response[x].make == make) {
msg += response[x].model + "<br>";
}
}
if(msg == "") {
msg = "No matches found!";
}
document.getElementById("results").innerHTML = msg;
},
});
};
I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}
I have a Like Status button that sends data using AJAX to the controller.
When I click the button, the button changes from "like" to "dislike" and all the classes and form action get changed as well.
The problem is, if I like the status, I see the changes reflected, but if I decided to dislike it without reloading the page, I get this error
GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)
If I reload the page and click dislike, my vote gets removed from the database and the button changes back to "like"
It works if I reload the page.
If I remove the get() request to retrieves the likes count, nothing happens and console.log() returns an empty row, I don't see any data being returned.
I opened laravel.log and I saw this error
local.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object' in C:\xampp\htdocs\socialnet\app\Http\Controllers\FeedController.php:140
which is this line in getlikesCounter() method
return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
I am using Laravel 5.2
The form in the view
#if(\App\StatusLikes::where(['status_id' => $status->id, 'user_id' => Auth::user()->id])->first())
{!! Form::open(['action' => 'FeedController#dislikeStatus', 'id' => 'dislike_form', 'class' => 'dislikeform']) !!}
<button type="submit" class="btn btn-danger btn-xs dislike" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="dislike-status">
<i class="fa fa-thumbs-down"></i> <span class="dislike-button-text">Dislike</span> <span class="dislike-button-counter">({{ $likes_count }})</span>
</button>
{!! Form::close() !!}
#else
{!! Form::open(['action' => 'FeedController#likeStatus', 'id' => 'like_form', 'class' => 'likeform']) !!}
<button type="submit" class="btn btn-info btn-xs like" data-user="{{ Auth::user()->id }}" data-status="{{ $status->id }}" id="like-status">
<i class="fa fa-thumbs-up"></i> <span class="like-button-text">Like</span> <span class="like-button-counter">({{ $likes_count }})</span>
</button>
{!! Form::close() !!}
#endif
The methods in the controller for like, dislike, and get likes count
public function likeStatus() {
if (Input::has('like_status')) {
$status = Input::get('like_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->create([
'user_id' => Auth::user()->id,
'status_id' => $status
]);
$response = [
'status' => 'success',
'msg' => 'You have liked this status',
];
return Response::json($response);
//return redirect(route('feed'));
}
}
public function dislikeStatus() {
if (Input::has('dislike_status')) {
$status = Input::get('dislike_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->where('user_id', Auth::user()->id)->delete([
'status_id' => $status
]);
$response = array(
'status' => 'success',
'msg' => 'You have disliked this status',
);
return Response::json($response);
//return redirect(route('feed'));
}
}
public function getlikesCounter($id) {
$status = Status::find($id);
return Response::json(['count' => StatusLikes::where('status_id', $status->id)->count()]);
}
The javascript form likeform and dislikeform
$('.likeform').submit(function(e) {
e.preventDefault();
var submitBtn = $(this).find('.like');
var form = $(this).find('.likeform')
var likeText = $(this).find('span.like-button-text');
var likeCounter = $(this).find('span.like-button-counter');
var status_id = submitBtn.data('status');
var user_id = submitBtn.data('user');
var token = $('input[name=_token]').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: 'http://localhost/socialnet/public/likeStatus',
method: 'POST',
cache: false,
data: { like_status: status_id, user_id: user_id, _token: token },
success: function(data) {
submitBtn.removeClass('btn-info').addClass('btn-danger');
submitBtn.find($(".fa")).removeClass('fa-thumbs-up').addClass('fa-thumbs-down');
submitBtn.closest("form").removeClass('likeform').addClass('dislikeform').attr('id', 'dislike_form').attr('action', 'http://localhost/socialnet/public/dislikeStatus');
submitBtn.closest("form").find("input[name=like_status]").attr('name', 'dislike_status');
submitBtn.removeClass('like').addClass('dislike');
submitBtn.find($(".like-button-text")).removeClass('like-button-text').addClass('dislike-button-text');
submitBtn.find($(".like-button-counter")).removeClass('like-button-counter').addClass('dislike-button-counter');
likeText.text('Dislike');
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
likeCounter.text('(' + data.count + ')');
});
console.log(data);
},
error: function() {
console.log('error');
}
});
});
$('.dislikeform').submit(function(e) {
e.preventDefault();
var submitBtn = $(this).find('.dislike');
var form = $(this).find('.dislikeform')
var likeText = $(this).find('span.dislike-button-text');
var likeCounter = $(this).find('span.dislike-button-counter');
var status_id = submitBtn.data('status');
var user_id = submitBtn.data('user');
var token = $('input[name=_token]').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: 'http://localhost/socialnet/public/dislikeStatus',
method: 'POST',
cache: false,
data: { dislike_status: status_id, user_id: user_id, _token: token },
success: function(data) {
submitBtn.removeClass('btn-danger').addClass('btn-info');
submitBtn.find($(".fa")).removeClass('fa-thumbs-down').addClass('fa-thumbs-up');
submitBtn.closest("form").removeClass('dislikeform').addClass('likeform').attr('id', 'like_form').attr('action', 'http://localhost/socialnet/public/likeStatus');
submitBtn.closest("form").find("input[name=dislike_status]").attr('name', 'like_status');
submitBtn.removeClass('dislike').addClass('like');
submitBtn.find($(".dislike-button-text")).removeClass('dislike-button-text').addClass('like-button-text');
submitBtn.find($(".dislike-button-counter")).removeClass('dislike-button-counter').addClass('like-button-counter');
likeText.text('Like');
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id, function(data) {
likeCounter.text('(' + data.count + ')');
});
console.log(data);
},
error: function() {
console.log('error');
}
});
});
GET http://localhost/socialnet/public/likestatusCount/undefined 500 (Internal Server Error)
Means :
status_id is undefined
Because, you have :
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..
Indeed , you have status_id got from :
var status_id = submitBtn.data('status');
And you have submitBtn is got from :
var submitBtn = $(this).find('.dislike');
However, you change the CSS class of submitBtn when there is an action (like/dislike)
Thus ,
.dislike is bad selector here, you need a selector that match the button either it is like or dislike
Assign value to submitBtn & update status_id just before calling your ajax.
$.get("http://localhost/socialnet/public/likestatusCount/" + status_id//..
Currently posting data from a drop-down menu. I am trying to basically the form that is returning and then insert it into the page.
Select Drop-Down
<form method="POST" style="display: inline;">
<select name="event_added" class="selectpicker">
{% for subscription in form.peerEventSubscriptions %}
<option value='{{typeDefEvent[loop.index0]}}'>{{ form_label(subscription.eventTypeHumanized) }}</option>
{% endfor %}
</select>
<input type="submit" class="btn btn-default" id = "addEventButton" data-rel="tooltip" title="AddEvent" value="Add Event" style="line-height: 1.5" />
</form>
Ajax/Jquery
var addEvent = $("#addEventButton");
addEvent.click(function(){
$.ajax({
method: "POST",
url: "{{ path('_add_new_sub_event') }}",
contentType: 'application/json; charset=utf-8',
data: { postVars: "EVENT_CLASS_JITTER EVENT_JITTER" }
})
.done(function( msg ) {
console.log( "Data Saved: " + msg );
window.stop();
});
});
Controller
return this data, the form is valid.
return array(
'form' => $form->createView(),
);
Getting a 500 internal server error. I just want to basically take this form and then render it to the current page, no refreshes.
I invite you to use FOSJsRoutingBundle,
Look at my example of my jQuery Ajax call:
$('#addNewVariant').on('click', function(event){
var hidden_input = $('#hidden_input').val();
hidden_input++;
$.ajax({
type: "get",
dataType: 'json',
url: Routing.generate('admin_products_addNewVariant', {'number' : hidden_input }),
beforeSend: function(){
$('.loadingGif').show();
$('#loadingModal').modal('show');
},
success: function( returnedData ) {
$('#hidden_input').attr( 'value', hidden_input );
$('#ajaxVariantAdded').append('<li class="dd-item" data-id="'+returnedData.id+'"><div class="dd-handle"><a data-id="'+returnedData.id+'"><i class="fa fa-hand-o-right"></i> {{"tab.variant"|trans}} '+returnedData.name+'</a><a data-id="'+returnedData.id+'" data-toggle="modal" class="pull-right" href="#modal'+returnedData.id+'"><i class="glyphicon glyphicon-minus-sign"></i></a></div></li>');
$( '.ajax' ).append( returnedData.form );
$('.variant').hide();
$('.variantItem'+returnedData.id).show();
$('.loadingGif').hide();
$('#loadingModal').modal('hide');
},
error: function( returnedData){
$('.loadingGif').hide();
$('#loadingModal').modal('hide');
}
});
});
This is my route:
admin_products_addNewVariant:
pattern: /addVariation/{number}
defaults: { _controller: "ProductsBundle:BackEnd/Products:addNewVariant" }
options:
expose: true
Finally this is my function:
public function addNewVariantAction($number){
$entity = new Variant();
$form = $this->createForm(new VariantType($number), $entity)->createView();
$response = new JsonResponse(array(
'form' => $this->renderView('ProductsBundle:Administration:Products/NewFormVariant/new.html.twig',array(
'form' => $form,
'number' => $number,
)
),
'name' => $number+1,
'id' => $number,
));
return $response;
}
I hope that my answer give a help.