I have a button that when you click it, it will show a confirmation box. If the user clicks 'ok', the word 'reached' would display inside of the div named 'EventData'.
So far the confirmation box shows when I click the button but 'EventData' won't show the word 'reached' when I confirm it.
*the 'event_id' has a value
I think the problem is with the url part where it won't go in the function
Route:
Route::post('/ArchiveEventPosts','AdminController#ArchiveEventposts')->name('ArchiveEventposts');
Script:
$(document).on('click', '.archive', function() {
var event_id = $(this).attr('event_id');
var x = confirm("Are you sure you want to archive this record?");
if (x) {
$.ajax({
method: "POST",
url: '{{ route("ArchiveEventposts") }}',
data: {
event_id: event_id
},
success: function(data) {
$('#EventData').html(data);
alert('Record Archived');
}
});
}
});
Function in the controller:
public function ArchiveEventposts(Request $request)
{
echo 'Reached';
}
You might need to change the way your route is assigned. What you are doing is assigning a plain string to the URL with a single quotation mark. Try like this:
var archiveEventpostsRoute = "{{ route('ArchiveEventposts') }}";
and below
url: archiveEventpostsRoute,
Also, make sure that your controller is returning the proper data, as stated in the other answer:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
Your controller method is not returning any data; it's simply printing the word "Reached".
You'll need to change the function to something like this:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
Related
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.
I am trying to pass data from a view to a controller using parameters.
Now I am running a few difficulities. I am trying to pass those parameters once I select a row from a table and press on a button which has a onclick method to ShowTasks()
The C# controller:
[Route("/service/delivery/{id}/{shopdoccode}/{regdate}")]
public ActionResult Delivery(string id, string shopdoccode, string regdate)
{
//do stuf
}
The Javascript function when user clicks on button:
function ShowTasks() {
//Dear Stackoverflow > This works, this is for selecting a row in the table
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
var dcColumn = 0;
var rdColumn = 1;
var shopdoccodeColumn = 3;
//assigning name to the colomn value
var id = $selectedRow[0].children[dcColumn].innerText.trim();
var regdate = $selectedRow[0].children[rdColumn].innerText.trim();
var shopdoccode = $selectedRow[0].children[shopdoccodeColumn].innerText.trim();
//ajax
if (id && regdate && shopdoccode) {
$.ajax({
type: 'POST',
url: '#Url.Action("service", "delivery" ,new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
data: { id, regdate, shopdoccode },
success: function (data) {
if (data.success) {
console.log("Succes");
}
},
error: function (data) {
console.log("Error");
}
});
}
}
}
What have I done so far? Sitting for hours trying to find a way to give the parameters to my controller so I can invoke a SQL stored procedure.
Unforntunately I can not simply use a hidden form for this.
Also this was quite helpful:
Url.Action parameters?
#sleeyuen
Looks to me like your Url.Action has its parameters in the wrong order. Change it to:
url: '#Url.Action("delivery", "service", new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
Here's the appropriate overload that you want:
Action(String, String, Object) with actionName, controllerName, and routeValues, in that order.
You can not *.js or *.html file wrtie razor code.
#Url.Action(string actionName,string controllerName,object routeValues)
The above code can only be used *.cshtml file.
test with Url.RouteUrl instead of Url.Action
I have a link when pressed it requests a page from a controller via render ajax, Previously i used to pass only the id but now i would like to pass an extra parameter to the controller, how do i achieve this,
This is what i have tried
This is the link' which only passes a single parameter to the controller
Html::a('click me', ['#'],
['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed
'id' => 'perform']);
This is the controller code expecting 2 parameters:
public function actionChecktruck($id,$category) //it expects 2 parameters from above link
{
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
This is my jquery code of another button that depends on the above controller during post request
$("#postbutn").click(function(e) {
$.post("checktruck?id="+truckid, //here i would like to pass 2 params
{checked:checked,unchecked:unchecked,truckid:truckid}
)
}
This is the jquery code when there is no post
How can i pass an extra parameter in the link or even the $.post request for the controller
First of all, as you are using JQuery ajax to submit the form, there is no need to set value for the link
Html::a('click me', ['#'],['id' => 'perform']);
using this id you can submit the request as follows
$this->registerJs("$('#perform').click(function(event){
event.preventDefault(); // to avoid default click event of anchor tag
$.ajax({
url: '".yii\helpers\Url::to(["your url here","id"=>$id,"param2"=>param2])."',
success: function (data) {
// you response here
},
});
});");
There is no need to mention method attribute as 'POST', you want to send through GET method
And finally in your controller, you need to accept parameters as follows
public function actionChecktruck() //it expects 2 parameters from above link
{
$id = Yii::$app->request->queryParams['id'];
$param2 = Yii::$app->request->queryParams['param2'];
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
Try this one,
In View file
$this->registerJs("$('#postbutn').click(function(){
$.ajax({
url: '".yii\helpers\Url::to(["u r URL"])."',
method: 'POST',
data: {id:id, truckid:truckid },
success: function (data) {
},
});
});");
I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');
First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();
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.