Facebook js SDK send with ajax variabiles to PHP - javascript

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
}

Related

How to write php include inside div with jquery

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.

Sub Total is not getting the changed value from database to input box

I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}

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

Run PHP Query with Ajax return data in modal

This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.

How do you assign values to the results of a jquery/ajax post?

I'm posting data to a php page using jquery. I want to then have the response from the page be able to be put into php variables on the original page. I don't want to append a DIV or show the results in the HTML. (This seems to be the only thing people do with post.)
Here's the jquery:
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval},function(result))};
});
});
PHP page2.php:
<?php
$valtoworkwith = $_REQUEST['incomingval'];
......../// do something
?>
I want to then do something on page2.php then send specific values back to the jquery to work with. How? How do I assign them a name or separate them out??
EDIT
My jquery needed a number and not text.
Here's the jquery:
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval},function(result){
if(result != 1){ ///could not put result !="hello" or != hello
$("#signup").overlay().load();
}
)};
});
});
Simply go here, it's as clear as it can get...
https://api.jquery.com/jQuery.ajax/
That's the documentation page for $.ajax, and if you scroll down you will have excellent examples you can start from.
Use JSON to get your inter-connectivity going, meaning the data exchange between client and server entirely through AJAX. Here's a link to a StackOverflow answer which goes into detail about how to make that happen, using PHP for the back end:
jQuery AJAX Call to PHP Script with JSON Return
Are you trying to do something like that?
if (!empty($_POST['incomingval'])){
$valtoworkwith = $_POST['incomingval'];
//do some stuff
echo $valtoworkwith;
}
Or if you want to sent back a JSON
<?php
function doSomeStuff($input) {
//instead of that do some stuff and return back something that makes sense
$output = $input;
//
return $output;
}
if (!empty($_POST['incomingval'])){
header('Content-Type: application/json');
$valtoworkwith = $_POST['incomingval'];
$res = doSomeStuff($valtoworkwith);
$data = array('incomingval' => $valtoworkwith, 'response' => $res);
echo json_encode($data);
}
?>
I hope that helped you because the answer it self was kind of vague.
Tested with postman
The in JS you can do with a promise
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval})
.then(function(data){ //look how awesome the promise looks
console.log(data.response); //do something with it
})
});
});

Categories