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');
}
Related
I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];
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 have the below code on href click I'm calling a javascript code in which an ajax is being called which returns the value of array $ss in json format . Now I want to know how can I update the value of $ss via ajax.
<div class="white" id="white" style="display:none">
<?php
foreach ($ss as $key => $value){
?>
<a href='javascript:void(0);' onclick='callAjax('<?php echo $key; ?>')'>
<?php
echo $value;
?>
</a>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({a: id }),
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
And ajax.php files return array values for $ss.
I understood how to update data of normal div through ajax but encountering problem to pass the data returned by ajax call to update array value.
1- Lets be clear javascript will not replace the content of a php variable. 2- Even if so you will not be able to regenerate the html you need this way.3- after you receive your variable you need to update the html instead.
PS: Surely you can update the variable on the server side when you receive that ajax call,that also needs some requirements(the variable is global and accessible inside the php file...),but from what I have understood you want to change it with javascript which is not possible.
Your ajax must like this...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
I think you can't.
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it.
$ss = 'ss value';
if exists($_POST['ss']) {
$ss = $_POST['ss'];
}
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 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'] ?>" />