I use ajax to update a table based on the entries of the user.
$('#user').change(function(){
var user= $("#user").val();
if (user !='None'){
$.ajax({
type: "GET",
url: '/getUserAccounts/' + user,
success: function (data) {
$.each(opts, function(i, d) {
console.log(d);
});
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
I write the code in a <script> tag, all work fine. now i prefer to organize the javascript code in files and import them into my .blade.php file.
the problem: the data passed from the controller is not recognized in my javascript file.
it's not possible to use controller data from a javascript file because they're not blade templates. What I usually do is have a hidden field on the page (or a meta header) that allows me to store the data I need and then I get the value I want from my JS files from those fields, example:
<input id="user_id" type="hidden" value="{{user_id}}">
In your javascript file:
var user_id = $("#user_id").val();
possible by creating pass value function
sample.js
function runCode(url) {
// your code process
}
in blade.php
...
include sample.js here
<script>
runCode('{{ $user_id }}');
</script>
Related
I have JS code:
var pobTeamId = document.getElementById('team_a_id').value;
var query = "<?php echo Sport::find(Team::find(pobTeamId)->sport_id)->id; ?>";
I need insert value pobTeamId in variable query.
I don't know how I can add this variable. I trying using this:
...Team::find(pobTeamId)...
...Team::find($pobTeamId)...
...Team::find(?>"pobTeamId"<?php)...
but Laravel returned only errors.
You approach is wrong! PHP won't be able to get the value of pobTeamId.
Use ajax to send the value to the Controller
var pobTeamId = document.getElementById('team_a_id').value;
// Initiate an Ajax either on page load or on button click
$.ajax({
url: '', // path you defined in your routes file
type: '' // either POST or GET
data: {
"pobTeamId": pobTeamId
},
success: function (data) {
}
});
and in the Controller you would have access to the pobTeamId
public function yourFunction(Request $request)
{
$pobTeamId = $request->input('pobTeamId');
$sport_id = Sport::find(Team::find($pobTeamId)->sport_id)->id;
}
you would need to reference the Sport Model in your controller and add an appropriate route
Do it like this:
<form method="get" action="{{ route('get_sport_id') }}">
<input id="team_a_id" value="" name="team_a_id"/>
<button type="submit"> Fetch </button>
</form>
Then in your controller:
public function getSportID()
{
$sport_id = Sport::find(Team::find(request()->get('team_a_id')->sport_id)->id;
return back()->with('sport_id', $sport_id);
}
With a corresponding route that's something like this:
Route::get('/sport-id', 'SportController#getSportID')->name('get_sport_id');
Now your view will have access to $sport_id. Of course, you should check isset($sport_id) before attempting to use it in the view.
I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.
In trying to cleanup my code base, I moved all of my javascript from script tags to their own javascript file. After doing that, all of my ajax calls are failing.
Here's the javascript, this is EXACTLY how it was in the *.cshtml file, excluding the script tags:
$(function () {
$("#weightList").change(function () {
var weight = $("#weightList").val();
var conference = $("#conference").val();
$("#wrestlerAList").prop('disabled', true);
$("#wrestlerBList").prop('disabled', true);
$.ajax({
url: '#Url.Action("GetByWeight", "Wrestler")',
data: {
weight: weight
},
type: 'POST',
success: function (data) {
var wrestlers = "<option></option>";
$.each(data, function (i, wrestler) {
wrestlers += "<option value='" + wrestler.Value + "'>" + wrestler.Text + "</option>";
});
$("#wrestlerAList").html(wrestlers);
$("#wrestlerBList").html(wrestlers);
$("#wrestlerAList").prop('disabled', false);
$("#wrestlerBList").prop('disabled', false);
},
error: function (error) {
alert("An error occurred retrieving the wrestlers for this weight.");
}
});
});
});
I've tried removing the "$(function () {...});" but that didn't work. Is there other syntax required when the javascript is not directly on the cshtml page?
Edit: I'm loading my javascript file at the very end of the cshtml file, right before the closing tag.
Also, I'm getting a 404 back. If the code stayed the same, why would it now be getting a 404?
url: '#Url.Action("GetByWeight", "Wrestler")',
that line needs to be rendered on a cshtml page. it doesnt get processed in a .js file.
The problem is with the way you are setting the ajax url
url: '#Url.Action("GetByWeight", "Wrestler")'
The ASP.NET MVC tag helper #Url.Action() will not work inside a .js file.
You could place the url in a hidden form field and read it from there.
Place this somewhere in the .cshtml preferably outside of any forms so it is not posted back in the form for any reason.
#Html.Hidden("ServiceUrl", Url.Action("GetByWeight", "Wrestler"))
Then use the code below to set the jQuery ajax url
url: $('#ServiceUrl').val(),
I have an HTML form which i populate from a database. On submit we load a page called "viewgame.php". Now what i want is here to run some scripts to populate some tables with data but how exactly can i pass the variable which i got from the form ex. $_POST['gameNo'] to the other php file though JavaScript?
Below is some of my code
JS function
function refreshGameinfo() {
var load = $.get('gameinfo_sc.php');
$(".gameinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
// do something here if request failed
});
load.success(function(res) {
console.log("Success");
$(".gameinfo").html(res);
});
load.done(function() {
console.log("Completed");
});
}
How can i pass the $POST_['gameNo'] to the gameinfo_sc.php file so that i can get the correct results?
Try this
var load = $.get('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_GET['gameNo']
For post method use
var load = $.post('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_POST['gameNo']
You are trying to post $POST_['gameNo'] to gameinfo_sc.php but $.get isn't the right method for post, its actually for http get. you can also do this by using $.post http://api.jquery.com/jquery.post/
function refreshGameinfo() {
$.ajax({
type: "POST",
url: "gameinfo_sc.php",
data: {gameNo: data},
cache: false,
success: function(html){
console.log( "Success" );
$(".gameinfo").html(res);
},
error:function(html){
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
}
});
}
try this
You can do it like this:
(in html layout):
<input type="hidden" id="gameNo" value="<?=$_POST['gameNo']?>" />
(in js file):
var gameNo = $('#gameNo').val();
var load = $.get('gameinfo_sc.php', {gameNo: gameNo});
....
UPDATE:
If your server doesn't support short open tags, you can write:
<input type="hidden" id="gameNo" value="<?php echo $_POST['gameNo'] ?>" />
I am developing an application using Symfony2 and Jquery as a JavaScript FW. I am using Twig for the templates. I render a template from the controller and after making a selection using the cursor in the template I would like the value of the selected tag to be returned to the controller when submitting using a submit button in the mentioned template.
I use the next Jquery function:
$("MatchedTag").click(function ()
{
$(this).toggleClass("highlight");
var IdOfTag = this.id;
$.ajax({
url: "{{ path('AcmeAcmeBundle_myaction') }}",
type: "POST",
data: { "tag_id" : idOfTag },
success: function(data) {
//(success) do something...
//variable "data" contains data returned by the controller.
}
});
});
I guess in the controller, in myaction I should use something like $_POST["tag_id"] or getrequest() , bindrequest() to get the value but I dont really know how. Could someone give me an example. Thanks.
You can try to get this parameter by :
$request->request->get('tag_id');
Update
simple action
namespace Acme\HelloBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloController
{
public function indexAction($name)
{
$myParam = $request->request->get('tag_id');
// write your code here
}
}