Call laravel controler from an ajax request with get / put / delete method - javascript

I am having a javascript like this which will call two different controller in two diff situation ....
Now the problem is it is one get method and one is destroy method ... when the call is generated, the controller functions never triggered. No idea wheather the url method is right or not. It is giving the 500 error.
I am also not sure about the response back from the controller. but before that I need to execute the database operation in the controller ... which is not going to execute. advance thanks for the help :)
JS code below :-->
function follow_or_unfollow(id,action)
{
//var dataString = "id=" + id;
if( action == "follow" ) {
myUrl = "{{ action('FollowsController#show', 'id') }}" ;
myMethod = "GET";
}
else
{
myUrl = "{{ action('FollowsController#destroy', 'id') }}" ;
myMethod = "DELETE";
}
var dataString = "id=" + id;
$.ajax({
type: myMethod ,
url: myUrl,
//data: dataString,
beforeSend: function()
{
if ( action == "following" )
{
$("#following"+id).hide();
$("#loading"+id).html('<img src="loading.gif" align="absmiddle" alt="Loading...">');
}
else if ( action == "follow" )
{
$("#follow"+id).hide();
$("#loading"+id).html('<img src="loading.gif" align="absmiddle" alt="Loading...">');
}
else { }
},
success: function(response)
{
if ( action == "following" ){
$("#loading"+id).html('');
$("#follow"+id).show();
}
else if ( action == "follow" ){
$("#loading"+id).html('');
$("#following"+id).show();
}
else { }
},
error : function(xhr, textStatus, errorThrown ) {
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
allert('ok');
}
});
}
</script>
1st edit
get a point after the firefox tool check up (as suggested by Chinnu)
It is showing
`[18:38:47.658] GET http://localhost/ffdd/public/follows/id [HTTP/1.1 500 Internal Server Error 230ms]`
that means ! the id is not been generated as digit or id variable, it is just going as "id" string. Now need a specific solution , how to send the value of id there .... at the controller througn the JS.
2nd edit
If I put the digit or value of id instead of mentioning it by 'id' that means if the value of id can be print directly there it will work . What will be the easier way to do that ?
myUrl = "{{ action('FollowsController#destroy', <the value of id>) }}" ;

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Ref: http://api.jquery.com/jQuery.ajax/
NOTE: You can able to find this errors using in Firefox Tools->Web Developer ->Error Console or CTRL+SHIFT+J

You are trying to access a javascript variable inside a php helper function will not work. I'm not sure what's passing id into that function, but if it's being passed into the view via PHP, then you should use {{ action('FollowsController#show', array($id)) }}
If it's not being passed into the view, then you would have to use myUrl = '/follow/'+id and make sure you have routes for both GET and DELETE.

Related

laravel, ajax call from input to controller function 500 error

I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.
The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.
The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.
I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?
What else does it look like I could be doing wrong here?a
service.php
public function getSearch($query)
{
return $this->get("/search/search?query={$query}" );
}
I also set a new route for the controller and function
Route::post('autocomplete','Controller#autoComplete');
controller.php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
//$search_result = "test"; /*this hard coded value works for passing*/
$searchResults = $service->getSearch($search_result);
return $searchResults;
}
view.blade.php
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
Add this to your head
<meta name="csrf-token" content="{{ csrf_token() }}">
and pass the token to ajax:
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
"_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.

javascript not show results on success

I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.

Syntax difficulties in ajax

I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id,
userId: userId},
success:function(data){
if(data.success){
$(".newCommentForm" +id).replaceWith("<span id='" + id + "' class='limitedText'>" + newComment + "</span>");
$(thisId).data("PinComment", newComment);
}
else { alert('error');},
error:function(){
alert('error');
}
});
}
external file (i have added the return arrays here):
public function editComment(){
$userId = Input::get('userId');
if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){
$id = Input::get('id');
$newComment = Input::get('newComment');
DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
return array('success' => true);
} else {
return array('success' => false);
}
}
You have a typo here else { alert('error');},, you need another closing brace to close the success function.
You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery
Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');

AJAX - Button Submit to update a form

I'm attempting to learn to make use of AJAX. I removed most of the complexity of the program to just isolate the problem I'm having. So I have a text area and beneath that a div that has "STATUS" printing out. On button submit using AJAX I want to change the word "STATUS" to the value of my variable, status, which in this case should be "SUCCESS".
What happens instead when I click is it prints out the word STATUS. It appears like nothing is happening when I click my submit button. Any ideas what I am doing wrong?
$(document).ready(
function () {
$('#sub').live('click',
function () {
url = 'http://whatever.php'
success = "Success!"
$.ajax({
url: url,
type: 'POST',
data: null
dataType: 'xml',
async: false,
success: function (data, statusText, reqObj) {
status = $(data).find('status').text()
if (status == 'SUCCESS') {
$('#succ').html(status)
} //if( status == 'SUCCESS' ) {
else {
msg = $(data).find('msg').text()
alert('NOT ADDED: ' + msg)
return
} // else
} //function()
}) //$.ajax( {
} /* function */ ) //live(
} //function()
) //$(document).ready
HTML:
<div id="buttonArea">
<textarea name="txtarea" cols=80 rows=30>>THIS TEXT BOX
IS USED FOR THINGS I WILL WORK ON LATER
</textarea><br/>
<input type=submit value='Submit Textbox Info!' id='sub'>
</div>
<div class="float-left" id='succ'>STATUS</div>
I think your find is empty. Try to replace with
status = $(data).text()
I'm not sure you use .find() the right way. it's used on html elements and expects to be passed a jquery selector or element or jquery object.
here's more details http://api.jquery.com/find/
what you want is to get your response text, so assign your ajax call to a variable:
xmlhttp = $.ajax({
then on success use your response text:
status = xmlhttp.responseText;
Your code works fine for me, on the proviso that:
(i) you add the missing comma from the line:
data: null,
(ii) the content-type returned by your php handler is text/xml

How to export a model function from a controller to a view in Laravel 4

I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.

Categories