I use ckeditor as an inline editor and added a button to save the content using AJAX. Everything works if I link to a php file which does the job for me. Anyhow, I'm using YII and I want to do this save work in a controller or in a file that uses my app settings.
So in my javascript plugin I call:
$.post("index.php/pagina/update?id=1", {
dataType: "text json",
data : editor.getData(),
success : alert('Opgeslagen!'),
} );
In my paginaController in the actionUpdate I got:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$model->content = 'werkt';
$model->save();
}
Does anyone know what I'm doing wrong here?
I think you'd have to pass the url Yii style, so that it accepts a parameter that is called id.
var url = '<?php echo Yii::app()->createUrl(array("pagina/update", "id" => $model->id)); ?>';
$.post(url , { // rest of code
Also, you could use a Yii ajax function here that looks something like this:
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: info",
'type'=>'post',
'dataType'=>'json',
));
?>
Related
I have been trying to make multiple tables viewed and be editable from the site to the server in my site.
I tried to use jquery ajax and it seems like fail
is there other way or my code was just bad?
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".setitlive").click(function() { setitlive(1); });
});
function setitlive(value1) {
var id=value1;
jQuery.ajax({
type: "POST",
url: 'C:\Users\user\Desktop\interactionclientserverwithphpandjavascript.php',
data: {functionname: 'setitlive', arguments: [id]};
}
</script>`
Interaction Client Server PHP code:
<?php
header('Content-Type: application/json');
$id = $_POST['arguments'][0];
switch($_POST["functionname"]){
case 'setitlive':
public function setitlivee( $id )
{
$result = \IPS\Db::i()->update( 'cms_custom_database_26', array(
'field_113' => 'live' ), array( 'primary_id_field="'.$id.'"' ) );
header("Refresh:0");
}
break;
}
?>
HTML Header:
<form method="POST">
button
<li class="ipsButton ipsButton_medium ipsButton_importantipsButton_fullWidth12">
<a title='{lang="accept"}' name="setitlive" id="setitlive" type="submit" onclick=" setitlive(); ">
{lang="accept"}
</a>
</li>
To start with, a window path isn't a URL. Your web server probably doesn't know how to find a file on your desktop unless you have a crazy configuration.
Put the target file in root of your project directory where your other php files are and then call it just by the file name and maybe a sub directory.
Once you've done that, if there's any further problems, please post it as a new question.
Let's say your php files are all in c:\www. Put that file in that directly and then...
url : 'interactionclientserverwithphpandjavascript.php',
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.
Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.
Here is the code section that I need to pass $role to External JS file(in pastebin)
public function executeIndex(sfWebRequest $request) {
if (isset($_SESSION['empId'])) {
$role = $_SESSION['empRole'];
if ($role == "admin") {
$empId = $this->getUser()->getAttribute('empId');
$team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
$nc = new Criteria();
$nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
$resultset = PeDatesPeer::doSelect($nc);
So Can you guys give me a solution regarding this, since I am stuck with this for a long time.
Please see thepastebin code for php and external js file.
https://pastebin.com/kbkLjSFa - PHP File.
https://pastebin.com/M60Rg64U - JS file
Yes you can get the php variable into the js file.
Method I:
Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.
So, if you have some test.js file, rename it to test.js.php and use it in your page like this
<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply
var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
Method II:
Use an AJAX request.
var some_var, another_var;
$.ajax({
url : '/url-which-returns-session-vars', //return the session data in json from this url
asnyc : false,
dataType : 'json',
success : function(res){
some_var = res.some_var;
another_var = res.another_var;
}
});
//rest of the logic goes here.
Both of these methods work. But I prefer the first method, since I don't have to write extra code.
Edit:
Suppose the response of the ajax call looks like this
{
some_var : 'value here',
another_var : 'another value here'
}
So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,
some_var = res.some_var;
another_var = res.another_var;
and since these variables are global variables, you can use them anywhere in your code in this file.
?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
Global variable should be declared before external js file include . in js file access it using this variable name php_variable
After the above code . jquery external file should be included here
<script src="external.js" ></script>
external.js
consol.log(php_variable);
First of all thank you for your atention.
What I would like is to use the Facebook js SDK to get the user's name and id and send them to php in the same page (index.php). I manage to get the username and id and save them in 2 variables in JS (js_fb_id and js_fb_name), but when I try to make the ajax call and sent them to php, nothing happens.
So, on my index.php i have the ajax script
var js_fb_id = response.id;
var js_fb_name = response.name; //this variables are set after the user is loged in
$.post( 'index.php',
{
php_fb_id: js_fb_id,
php_fb_id: js_fb_name
},
function (data){
console.log(data);
}
)
Later on, I want to get the variables send via AJAX
<?php if ( isset( $_POST['php_fb_id'] ) ) {
echo $_POST['php_fb_id'];
}
?>
Is this possible? It works when I use a separate page to make the AJAX call, but I cannot get the php variables from there to my index.php page.
Thank you
So basically what is happening here is that the ajax script is triggered on page load.
However this is only after the dom has already been rendered.
To fix this you will need to trigger the ajax function on a specific event , for eg: button click.
Also note that since your entire page is in html you ajax function is returning the entire page as 'data' and not spacifically the php variables that you are trying to set.(You will be able to see this in the console)
Also note that if you want to print the values on the page you will have to modify the html in the callback function through ajax for eg:
$(document).ready(function() {
$('#post').click(function() {
$.post( 'text.php',
{
php_fb_id: js_fb_id,
php_fb_name: js_fb_name
},
function (data, status){
$("#txt").html(data); //you can print returned data
console.log(data);
}
)
});
});
This should go in a separate php file say text.php
<?php
if ( isset( $_POST['php_fb_id'] ) ) {
echo $id = $_POST['php_fb_id'];
}
?>
Your code looks fine, except that you passing php_fb_id twice in the parameter.
$.post( 'index.php', {
php_fb_id: js_fb_id,
php_fb_id: js_fb_name
},
Except this, parameter are passing into index.php and getting captured too. so you can go ahead with php operation there. Do let me know what is the problem you facing in this code? will definitely try to help
Do Something like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //check if it's Post request
if( isset( $_POST['php_fb_id'] && isset( $_POST['php_fb_name']) {
$name = $_POST['php_fb_name'];
$id = $_POST['php_fb_id'];
....
echo "OK";
}else{
echo "ERROR, need input";
}
else{
//Your Index Code Here
}
I have a requirement in a wordpress website (PHP) where on select of a dropdown, two radio buttons show up and depending on the radio button selected a select dropdown will be made available.
I reached the stage where I have the radio buttons are made available. I use jQuery ON event to identify which radio button is checked and have the respective value in a javascript variable. I am trying to pass this JS variable to my php using ajax. Success attribute of ajax works fine but $_POST['name'] does not show the value. I tried to use .html() inside the success attribute of ajax but that just replaces my div element with the value of javascript variable. I need this JS variable value in my PHP code so that I can run a condition based on which I decide which dropdown I need to display on the website.
I have been trying a solution since few days but not able to find a solution. Request some guidance
Edit:
Based on the suggestion received
I tried the following changes. I see the value in my input type=hidden elements but only if I use Inspect in Chrome. However using View Source does not show me these values.. What am I missing? Can someone please give some guidance..
Ajx-script.js
$.ajax({
type : "POST",
url : myAjaxData.ajaxurl,
data : {
action : "sProdOrRegion_ajax_action",
selectedProdReg : selectedProdReg
},
success : function(data) {
$("#radioValueHidd1").val(selectedProdReg);
// $('#stakeholderParentData').load( urlValue + " " +"#stakeholderData");
//$("input[id=radioValueHidd3][value="+ selectedProdReg +"]").html();
$("input[id=radioValueHidd2]").val(selectedProdReg);
}
});
functions.php
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('my-ajax', get_template_directory_uri() . '/library/js/ajx-script.js', array('jquery') );
wp_localize_script(
'my-ajax',
'myAjaxData',
array( 'ajaxurl' => admin_url('admin-ajax.php') )
);
});
add_action( 'wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion' );
add_action('wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion');
function callback_singleIdeaProdOrRegion() {
if(isset($_POST['selectedProdReg'])) {
$selectedProdReg = $_POST['selectedProdReg'];
$selectedProdReg1 = $_POST['selectedProdReg'];
die();
}
}
single-car.php
<div id="stakeholderParentData" class="stakeholderParentData">
<div id="stakeholderData" class="stakeholderData">
<?php $selectedProdReg = $wpdb->escape($_POST['selectedProdReg']); ?>
<?php
if (isset ( $selProdReg )) {
if ($selProdReg === "custom_post_prod_company") {
Using Ajax in WordPress is usually done in the following manners:
1- You have to submit your ajax data to the admin-ajax.php. Sometimes you can use the global js variable ajaxurl, predefined by WordPress for that URL. But more reliably I'd use the output of admin_url( 'admin-ajax.php' ).
2- Your data object must contain an action value that have a unique string to represent this ajax submission. I'll use AJAX_ACTION here: data = { action: 'AJAX_ACTION', your_var: 'your_val' };
3- Receive the data by using hooks that contain the action name that you've specified:
add_action( 'wp_ajax_AJAX_ACTION', 'callback_function' );
add_action( 'wp_ajax_nopriv_AJAX_ACTION', 'callback_function' );
4- Use your callback_function to receive the data:
function callback_function() {
// $_POST['your_var'] is accessible here
}
By the way, using echo inside the callback_function would result in the response being sent to the success function.
wp_ajax_nopriv_AJAX_ACTION is for submission for visitors that do not have the WordPress account or are not logged in, while wp_ajax_AJAX_ACTION is for logged in users.
Please check: WordPress Codex
I am not sure if these will help you but I have 2 ideas. First is you might be getting the value of radio button false. Second is maybe you should write your data like this.
data: { "selRegProd" : selRegProd },
I have a wordpress website en would like to create users with a button (to start with)
It works in pieces, but i can't get this two pieces to work together
i have this piece of code (works on functions.php , but not in my createaccount.php file)
$userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , 'me#mail.com'));
$userid->set_role('client'); //custom role 'client' already set
this on jquery //php file works when echo 'test';
$(document).ready( function() {
$('#newbtnaccount').click( function() {
$.post('php/createaccount.php', { } ,
function(data) {
alert(data);
});
});
});
i already tried a lot of options but nothings seems to work yet.
Anyone who can Help?
Thanks!
In wordpress you can make an AJAX request to admin-ajax.php and attach functions in your functions.php file with wp_ajax_my_action (for logged users) and wp_ajax_nopriv_my_action (for non logged users).
1. Set the admin-ajax.php url available as JS variable
In header.php add this in the head part:
<script type="text/javascript">
var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
2. Request the function through ajax
You need to add an action parameter to your request reflecting the function that you need to call in functions.php - let's call it create_user.
$.post(ajax_url, {action: 'create_user'} , function(data) {
alert(data);
});
3. Create the function in functions.php
Inside functions.php, add the following:
function ajax_create_user() {
$userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , 'me#mail.com'));
$userid->set_role('client');
// echo whatever you need to return
}
add_action( 'wp_ajax_create_user', 'ajax_create_user' );
add_action( 'wp_ajax_nopriv_create_user', 'ajax_create_user' );
Read more about AJAX in Wordpress