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.
Related
Hi I am new to Laravel having a situation like: I have a HTML form and loading some HTML like "partial.blade.php" using AJAX in Same form, that is working perfectly with static HTML but,
I want to send a JS Array of object with AJAX Request to Dynamically loading HTML Content like: Drop down in same form
Could any Guide me how Can i Pass JS Array to that piece of HTML so i can Render that Array in "partial.blade.php"
here is my code
this is main form HTML & Array i want to pass with this AJAX Request
var dataArray = $('#data1').val();
code included at last in HTML Form Page
$.ajax({
url: "add-property/residential",
type: 'GET',
dataType: 'html',
data: { dataArr: dataArray },
contentType: false,
processData: false,
success: function(response) {
console.log(response);
$('#dynamicForm').html(response);
//alert(response);
},
error: function(response) {
console.log(response);
alert('Error....!');
}
});
here is my Route
Route::any('admin/add-property/residential',function() { return view('admin.residential'); });
all i want to receive that JS array in this piece of HTML that is dynamically loading
When you want to return the contents of a view() to an AJAX request, you can store the view as a variable and return in a JSON response:
public function apiResponse(){
$html = view("admin.residential")->render();
return response()->json(["html" => $html]);
}
In your AJAX request, you can access this as response.html:
success: function(response) {
$("#dynamicForm").html(response.html);
}
To pass a variable from AJAX to the view, you can use the request object. At the top of your routes/api (or routes/web.php, whichever you're using) add use Illuminate\Http\Request;, then in your Route inject that into the function:
<?php
use Illuminate\Http\Request;
...
Route::any('admin/add-property/residential',function(Request $request){
...
});
Not that $request is available, you can access the data being sent in the AJAX request via $request->input("dataArr");, and pass that to the view partial using ->with();:
Route::any('admin/add-property/residential',function(Request $request){
$dataArr = $request->input("dataArr");
$html = view("admin.residential")->with(["dataArr" => $dataArr])->render();
return response()->json(["html" => $html]);
});
According to this
Instead of return view('admin.residential');
You need to do this: return (string) View::make('admin.residential');
Edit
If you want to receive data from the ajax, and then load the view, you could do something like this:
Import the Request.
use Illuminate\Support\Facades\Response;
Make your rote point to a specific method on a controller.
Route::any('admin/add-property/residential',"YourController#returnView");
Make your function to handle the data
public function returnView(Request $request){
$data = $request->all(); // Here you will have all the data you send via AJ
//Make sure the $data has all the necessary parameter to load the view
$view = View::make('my_view', $data);//Here you will pass the data to the view
return response()->json(["html" => $$view->render()]); // Using #TimLewis return
}
i am trying to insert data to a database table using ajax in yii2. but i don't really know how to go about it i want to send the post data to the controller the problem seems to come from the ajax script .it is meant to show me the value of rate which is 'up'. instead the alert show me.
this is my view class
<?php
use yii\widgets\ListView;
use yii\data\ArrayDataProvider;
use app\models\MyProfile;
use app\models\LikeDiscussion;
use yii\widgets\ActiveForm;
use common\models\Topic;
use common\models\Thumbs;
use common\models\Comment;
use common\models\Candidate;
use yii\widgets\Pjax;
use yii\helpers\Html;
use frontend\assets\AppAsset;
$this->title = 'My Yii Application';
?>
<button id="save" name="save" class="readmore">up</button>
this is my js file.
var fac= document.getElementById("save");
fac.onclick = function fun(){
$.ajax({
url: '/index.php?r=site%2Fblog',
type: 'post',
data:{"rate": 'up'},
success:function(data){
alert(data);
}
});
};
this is my contoller class
<?php
public function actionBlog(){
$thumbs= new Thumbs();
if(isset($_POST['rate'])){
$thumbs->user=Yii::$app->user->identity->email;
$thumbs->topic_id = 1;
$thumbs->rate = $_POST['rate'];
$thumbs->load($_POST);
$thumbs->save();
}
return $this->render('blog');
}
this is what i get as the alert
Try this:
<?php
public function actionBlog(){
$thumbs= new Thumbs();
if(isset($_POST['rate'])){
$thumbs->user=Yii::$app->user->identity->email;
$thumbs->topic_id = 1;
$thumbs->rate = $_POST['rate'];
$thumbs->load($_POST);
$thumbs->save();
if(Yii::$app->request->isAjax)
return $thumbs->rate;
}
return $this->render('blog');
}
I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/
I am building an application with symfony2 on the backend. I am thinking about using AngularJS on the frontend, but I would still like to use symfony forms. I have setup the form with the correct modules and everything, but the problem occurs when the data is actually submitted.
Problem
When Symfony renders the form, it sets the inputs 'name' attribute to an array, like user[username], and this is the format that it expects to receive the data once it is submitted. I can't figure out how to get Angular to submit the data in this format. This is what I have:
<body ng-app="formApp" ng-controller="formController">
{{ form_start(form, {'attr':{'id': 'registerForm', 'ng-submit':'processForm()'}}) }}
{{ form_row(form.username, {'attr':{'ng-model':'formData.username'}}) }}
{{ form_row(form.password.first, {'attr':{'ng-model':'formData.password'}}) }}
{{ form_row(form.password.second) }}
{% for address in form.userAddresses %}
{{ form_row(address.postalCode, {'attr':{'ng-model':'formData.postalCode'}}) }}
{% endfor %}
<div><input type="submit" value="Save" /></div>
{{ form_end(form) }}
</body>
and the controller:
function formController($scope, $http) {
$scope.formData = {};
$scope.processForm = function() {
$http({
method : 'POST',
url : submit,
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
alert(data.message);
});
};
}
When I submit, obviously the name-value pair uses the formData variables, so username=testuser instead of user[username]=testuser.
I tried to set the formData variable like formData.user[username], but that didn't work at all.
So is there a way to either use the inputs 'name' when submitting, or do something so that the form is submitted in the correct format? Any help would be great!
You can build the object symfony expects in a $scope function that you would bind to your form's submit with ng-click. So:
<input type="submit" value="Save" /></div>
would become
<input type="submit" value="Save" ng-click="submitForm()" /></div>
and in your controller you would add a function on the $scope object
$scope.submitForm = function() {
var user = [];
user['username'] = $scope.formData.username;
//etc
};
I think you should keep Angular form logic. You should use ng-model to bind data. To do this, you can create a Twig Form Theme to add ng-model attributes to your inputs, take a look at this gist.
Then you could pass input values to a $scope.data var in your controller like this:
$scope.var = {};
You should serialize data with the function provided in this article at line 109 or use jQuery.param() if you use jQuery.
Then create a submit method like this:
$scope.submit = function(){
$http.post(
'http://www.myurl.com',
this.serializeData($scope.data),
{ headers: {
'Content-Type': 'application/x-www-form-urlencoded' //Fix for Symfony
}
})
.success(function(data) {
//
})
.error(function (data){
$log.error(data);
});
}
I solve it using server side code. before handling of the request and validation i call the following function i created to change the format:
/**
* Format the request content with the form name
* #param Request $request
* #param $formName
* #param null $content
* #return Request
*/
public function formatRequestWithForm(Request $request, $formName, $content = null)
{
if ($content === null) {
$content = $request->getContent();
}
$contentArray = array($formName => json_decode($content, true));
$request->attributes->add($contentArray);
$request->request->add($contentArray);
return $request;
}
You could use {'data-ng-model': 'formData["user[username]"]'}.
To post formData you should pass it through jQuery.param().
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'] ?>" />