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
Related
I'm working with a service that automatically registers my user's devices with Onesignal.
I call the function on login by calling gonative_onesignal_info(); inside script tags (full function will be below). That registers devices perfectly fine with Onesignal.
Now, according to the service's documentation, I can POST it to my server via AJAX, which is what I'm struggling with. From the documentation for the service, if you call gonative_onesignal_info() like this:
function gonative_onesignal_info(info) {
console.log(info);
}
... info will look like this:
{
oneSignalUserId: 'xxxxxxx',
oneSignalPushToken: 'xxxxxx',
oneSignalSubscribed: true,
}
And here's my full function:
function onesignal_mobile_registration( $user_login, $user ) {
// Get user data
$user_id = $user->ID;
$user_email = $user->user_email;
?>
<script>
gonative_onesignal_info(info);
</script>
<?php
$oneSignalPushToken = ???;
update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);
}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );
So, how can I extract the oneSignalPushToken from that Javascript option, and store it in $oneSignalPushToken to be saved to my user? I think I need to use AJAX to pull it out, right? How would I do that?
You can't assign a php variable from javascript because php run in server but javascript run in browser. You must get $oneSignalPushToken value from a php source OR call a ajax from browser when send js data to php variable:
Script place:
<script>
var data = gonative_onesignal_info(info);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'test.php?oneSignalPushToken=' + data.oneSignalPushToken, true);
xmlhttp.send();
</script>
test.php
function onesignal_mobile_registration( $user_login, $user ) {
// Get user data
$user_id = $user->ID;
$user_email = $user->user_email;
$oneSignalPushToken = $_GET['oneSignalPushToken'];
update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);
}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );
It is important to understand what your code does:
The PHP part will render an HTML page
The JavaScript part will execute in the browser once the page is fully rendered and served
That means you won't be able to retrieve a JavaScript variable in the PHP thread that generates the page, for two main reasons:
JavaScript and PHP execution contexts are not shared at all
JavaScript will execute once the PHP thread has ended
What you have to do is expose an endpoint on your PHP server, let's say POST on a /token URL. You will call this endpoint from your JavaScript with some code like fetch('/token', { method: 'POST', body: info });, then retrieve the token from the $_POST global variable, and then execute your update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken); line
I need to write <?php include $this->_ script('admin/test.phtml'); ?> Using jquery within a <div> so that it works.
I have already researched and in all the responses recommend using load("file.php"), but it does not work in my case, because it is a framework and because of the routes this does not work.
I tried this and it did not work, it does include inside the script instead of doing in div:
<script>
$('.btn-group').on('click', '#btn-edit', function(e) {
e.preventDefault();
var id = $(this).attr('data-id');
$('#myModal').modal({
backdrop: 'static'
});
<?php $_GET['id'] = id;?>
var php = "<?php include $this->_script('admin/teste.phtml') ?>";
$('.modal-body').html(php);
});
</script>
I tried this code and it also did not work:
<script>
$('.btn-group').on('click', '#btn-edit', function(e) {
e.preventDefault();
var id = $(this).attr('data-id');
$('#myModal').modal({
backdrop: 'static'
});
<?php $_GET['id'] = id;?>
var php = "include $this->_script('admin/teste.phtml')";
$('.modal-body').html('<?php' + php + '?>');
});
</script>
The only way to get something like this to work is using jQuery to request the page back to the server to get the server processing PHP again.
However, as you've found, loading just the file doesn't work because the file likely included dependencies that are not present.
The way I would solve this problem (I happen to be using WordPress which might change your specific application of my answer) is this:
jQuery:
jQuery('.btn-group').on('click', '#btn-edit', function(e) {
jQuery.ajax({
type: "POST",
url: "/", //Or whatever the page you want to use to load this.
data: {"custom_php_action": "my_special_action"},
tryCount : 0,
retryLimit : 3,
success: function(res){
jQuery(".modal-body").html(res); //Div for my response
},
error: function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
jQuery.ajax(this);
return;
}
return;
}
}
});
});
PHP (This is where whatever you are using to build your page will change):
function my_custom_controller_function() {
if ( isset($_POST['custom_php_action']) && $_POST['custom_php_action'] == 'my_special_action' ) { //Tests for our AJAX conditions
//My Code Here -- Make sure whatever response is echoed and not simply returned.
//If the function returns a value, then echo it here.
//Example
echo 'My Response';
//Example
//Example 2
$data = my_function();
echo $data;
//Example 2
exit(); //Stop the rest of the page from loading.
}
}
add_action( 'wp', 'my_custom_controller_function' ); //Control when AJAX kicks in -- we don't want it firing too soon -- or too late.
This uses a WordPress action hook that fires after WordPress and plugins are loaded, but before any theme files have been processed (if I understand my hook order correctly). Depending on your framework will depend on how you include the code you are wanting to use.
This is how I have solved dynamic loading of information. Hopefully you can piece together a solution from this example that will work for you since I don't know the class/object combination you are using to locate the document you're trying to load/include and I don't know what the details of the platform you're building upon.
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 am working on this project in edge animate for a school assignment.
I have a database on my school webspace and I need to import some data from that database into my edge animate project.
I've been looking on the internet how to do this and these pictures show what I have so far. It still has a javascript error, but I can't figure out what. If I could just get that javascript error sorted, I can add code do some things with the array.
I collect the data from the database in a php-array and I want to save it in an array in javascript so I can display anything from inside that array on different places I want to.
thats because $.ajax is a jquery function, therefore you have to import this libary.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function Load()
{
console.log('start ajax query...');
var delivery;
$.ajax({
method: "POST",
url: "test.php",
data: { foo: "bar" }
})
.done(function( data ) {
delivery=data;
console.log(data);
console.log('...all fine');
});
}
$( document ).ready(function() {
console.log( "firing load function..." );
Load();
});
</script>
PHP Script
dont modify the header, simply echo the return of json_encode().
<?php
/**
* FILE test.php
*/
echo json_encode(array('foo'=>'bar'));
?>
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',
));
?>