JQUERY ajax to update field in laravel doesn't work - php

I am trying to update a field in laravel and it doesn't do anything, I tryed to trace the error checking if the fields are correct and the routes but I don't really know.
//js file
$(document).on('blur','#dato-anyadir',function(){
var atributo=$(this).parent().attr('name');
var id=$(this).parent().parent().attr('id');
var valor= $(this).val();
if($(this).val() == ''){
$(this).parent().html($(this).attr('placeholder'));
}else{
if(!comprobacionModificacion(atributo,valor)){
alert("hola");
alert(id);
alert("atributo " + atributo);
alert("valor " + valor);
$.ajax({
//This is the url
url: "/listar/modificar/"+id+"/"+atributo+"/"+valor,
method: "GET",
});
}
$(this).parent().html(valor);
}
});
//web routes
Route::get('/listar/modificar/{id}/{atributo}/{valor}', 'AnimalController#modificarAnimal');
//Controller php
public static function modificarAnimal($id,$atributo,$valor){
$animal = Animal::find($id);
$animal->$atributo = $valor;
$animal->save();
}
Any idea? It doesn't do anything when it reaches the controller

Firstly if you dont put this route in except list in VerifyCsrfToken middleware, you must to use:
$.ajaxSetup ({
headers: {
'X-CSRF-TOKEN': $ ('meta[name="csrf-token"]').attr ('content')
}
});
and ensure you have meta tag csrf-token on header
Then your ajax code not doing anything after get, valor not changed. so please lookup jquery ajax done method

I finally know what's happening, it was my fault ofcourse.
I didn't had the migrations so laravel tried to update the 'animals.updated_at' . A field that is created when you do the migrations.
My fault.
Thanks for the help!

Related

Laravel 5.2 return with errors - how to tell which form is submitted

I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!

AJAX request delete column base on their id.

Good day. I'm working on a admin page basically it is a content management system. I want to delete the data based on their id. But unfortunately i've encounter a error on the htpp request. here is the error.
Request URL: admin/ajax_delete
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:144.76.136.165:8181
VIEW FILE:
<span class="glyphicon glyphicon-trash"></span>
$("#delete_tpi").click(function() {
alert("Are you sure you want to delete?");
var tpi = $('.datatpi').val(); //package includes
var did = $('#data-id').val();
$.ajax({
url: '<?php echo site_url('admin/ajax_delete'); ?>',
type: 'POST',
datatype: 'html',
data: {id: did, tpi: tpi},
success:function (b){
if (b == 'Success') {
$('.#data-id').val('');
$('.datatpi').val('');
location.reload();
}
}
});
});
$('body').on('click','.edit-content-modal',function(){
var id = $(this).attr('data-id');
$('#data-id').val(id);
});
Controller file:
public function ajax_delete(){
$did = $this->input->post('id');
$ptpi = $this->input->post('tpi');
$update = $this->products_model->row_delete($did,$ptpi);
var_dump($update);
echo ($update)?'Success':'Fail';
}
MODEL FILE:
function ajax_delete($did,$ptpi){
$this->db->where('id',$did);
$this->db->delete('products',$ptpi);
return $this->db->affected_rows() > 0;
}
Because <a></a> element does not expect a value tag. You can get the ID of the clicked #delete_tpi link by using attr():
var did = $("#delete_tpi").attr('data-id');
Your POST request to admin/ajax_delete returns 500 Internal Server Error. This is a server-side error. If you use codeigniter, take a look at application/logs/*.log files that will give you detail information about the error.
I think, your problem is calling a non-existing function from model:
In your controller, you have:
$this->products_model->row_delete($did,$ptpi);
But your model, contains:
function ajax_delete($did,$ptpi){
....
}
Do you have row_delete() function in your model?
Once again, i suggest you to look at logs file, because many problems can result in server-side error.

Sending variable by ajax in use of laravel

I am trying to send two variables through ajax into the php script in laravel.
It is actually not clear to me how to move these variables.
Would you mind guys to give me some advice on it? the newComment contains some string, and id is just a number.
var newComment = document.getElementById('newComment').value;
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id},
success:function(){
alert('success');
},
error:function(){
alert('failure');
}
});
});
Here is my route:
Route::any('/editcomment/{id}/{newComment}', 'HomeController#editComment');
And here goes the function in homecontroller:
public function editComment(){
$aaa = Input::all();
return $aaa;
}
I am struggling with this for last 2 days, constantly looking at documentations and tutorials but have no idea how to do this.
You don't need to add the variables to the url for this request. The data you include in your ajax request will be send to the server as a post body.
Try changing the route to Route::any('/editcomment', 'HomeController#editComment');
And use
public function editComment(){
return Input::all();
}
This should display the id and the newComment
you have to change your route file like this :
Route::any('/editcomment', 'HomeController#editComment'); because yo dont need to ajax request parameter to send in route file.
And yes in your controller method editComment change like this:
public function editComment(){
if(Request::ajax()) {
return Input::all();
}
}
We have to check that requested by ajax call.
Try,
$_GET['newComment'] and $_GET['id']. This will work.
Thank you :)

sending form data to server by ajax

I am new with ajax and want to make a to-do-list.
for add-form submit method() ,I have an if-else .the else works and give me alert in its situation but if doesnt work I think it's about my post method.
by the way it's my jquery code :
$('#add_task').submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var title = $('#task_title').val();
if(title){
//ajax post the form
$.post("/add", {title: title}).done(function(data) {
$('#add_task').hide("slow");
$("#task_list").append(data);
});
}
else{
alert("Please give a title to task");
}
});
and when I click on my add btn the console output shows me a 404 not found error and refer to this line of my jquery main file that I download from http://code.jquery.com/jquery-latest.min.js: it is :
f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&& (e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();
it's my controller :
public function postAdd() {
if(Request::ajax()){
$todo = new Todo();
$todo->title = Input::get("title");
$todo->save();
$last_todo = $todo->id;
$todos = Todo::whereId($last_todo)->get();
return View::make("ajaxData")
->with("todos", $todos);
}
}
and my route:
Route::controller('/', 'TodoController');
thanks for time
Change "submit button" to simple button and change as below.
$('#add_task').click(function() {
var titleField = $('#task_title');
if(titleField.length > 0){
$.post("/add", {title: titleField.val()}).done(function(data) {
$('#add_task').hide();
$("#task_list").append(data);
});
} else {
alert("Please give a title to task");
}
return false;
});
I think you have an problem with routing in Laravel. This routing should work:
Route::post('add/',array('uses' => 'TodoController#add'));
404 HTTP Status errors in AJAX are only related to the URL you are sending your data. Change /add with something your backend can handle, like a simple PHP file, because /add means you need some htaccess/nginx rewrites to be done.
Anyway, it's a simple tutorial, and I'll downvote you for copying code claiming to be yours from: packtpub
You should do a simple ajax request like this:
$.ajax({ url : 'ajax.php', data: {title:title}, type: 'POST', success:
function(response) {
// exec success code
}
});
Never do internet tutorials if you have no idea about programming because you'll never get them to work. It's just a simple php file that you need to code, and change it's url from that tutorial in your Route:: controller, though, that tutorial is way too complex for a to-do list.
I fixed it just by changing:
$.post("/add", {title: title})
to:
$.post("http://localhost/Blueprints/to-doListWithAjax/public/index.php/add", {title: title})
it didnt found localhost://add so I gave it complete addrerss
.
THANKS ALL FOR REPLIES

Codeigniter Ajax request appeared twice in view and database

I have created a comment library to handle comments all over my website developed by CI
I am adding comments using ajax so i have came up with practice to have the function located in MY_Controller that handle the ajax
public function comment_add()
{
echo $this->comments->add();
}
and in AJAX Jquery code noting that category is one of controller names as any controller will havethe access to comment_add() found in parent controller
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
and in my Comments library
public function add()
{
$post_id=$this->get_post_id();
$post_type=$this->get_post_type();
if(!$post_id || !$post_type || !$this->user_id)
return false;
$id=$this->ci->comments_model->comment_add($this->user_id,$post_id,$post_type);
if($id)
{
return $this->_markup($id);
}
else
return false;
}
and comments model
function comment_add($user_id,$post_id,$post_type)
{
$data['comment_user_id']=$user_id;
$data['comment_post_type']=$post_type;
$data['comment_post_id']=$post_id;
$data['comment_text']=$this->input->post('comment_new');
$this->db->insert('comments', $data);
if($this->db->affected_rows()>0)
return $this->db->insert_id();
else
return false;
}
Problem is that Comment is inserted twice and as well in database twice, i have been tracin this for hours even with x-Debugg found that he go through echo $this->comments->add(); twice dunno why he would do that, thanks for your help
maybe it was submited twice. Try to unbind submit when you get ajax
success or just alet("something") so you will know if that problem is
javascript or php based.
Replace your submit function with:
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$(this).unbind("submit"); //so you will submit only once
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
The missing piece here is "snc/category/comment_add" controller ... are you sure you aren't calling from both that controller & also the MY_Controller?
Can you post the controller code as well?
Found out that I have loaded Jquery file twice, that was my bad, thanks guys

Categories