How to write php include inside div with jquery - javascript

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.

Related

jquery ajax post request is successive but still not working

I want to do a simple ajax post request to another page, with the same code I've another time, but this time it does not seem to work, even though the alert I put at success works. The variables do not seem to transfer, but even disregarding the variables and used putting a simple request on the other page does not seem to help. This is my code now:
<script>
$(function(){
$('.sortable').sortable({
stop:function()
{
var ids = '';
$('.sortable div').each(function(){
id = $(this).attr('id');
if(ids == '')
{
ids = id;
}
else
{
ids = ids+','+id;
}
}),
$.ajax({
url:'<?php $_SERVER["DOCUMENT_ROOT"]. "inhoud/dashboard/change_order.php"?>',
data:{ids: ids, user_id: '<?php echo $user_id; ?>'},
type:'POST',
success: alert('yay')
});
}
});
});
</script>
Everything in the script seems to work. The ids array fills exactly how it is supposed to be, and also the user_id is rightly defined. I have tried every way to link to the document, but every way seems to fail. What is supposed to happen is that the call to the other page gets made, where the data given in the post requested is handled, but even though almost exactly the same code works in multiple other scenarios, this time it seems to fail.
You need to add a function inside the success
like this ->
success: function(){ alert('yay'); // do something }

Facebook js SDK send with ajax variabiles to PHP

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
}

Wordpress Add user by javascript

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

ajax importing json content from php to edge animate

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'));
?>

Ajax and rewrite engine

I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.

Categories