Call do_action using JavaScript/jQuery - javascript

I have an AJAX function that sends information to the userpro_ajax_url after successfully logging in through Facebook.
I am trying to get the success block to run a do_action function using
<?php
ob_start();
do_action('userpro_social_login', <email needs to go here>);
ob_clean();
?>
Right now if I pass the email address manually it works fine, however the only way I can get the email dynamically is through the current response which is in JavaScript.
The full function is:
FB.api('/me?fields=name,email,first_name,last_name,gender', function(response) {
jQuery.ajax({
url: userpro_ajax_url,
data: "action=userpro_fbconnect&id="+response.id+"&username="+response.username+"&first_name="+response.first_name+"&last_name="+response.last_name+"&gender="+response.gender+"&email="+response.email+"&name="+response.name+"&link="+response.link+"&profilepicture="+encodeURIComponent(profilepicture)+"&redirect="+redirect,
dataType: 'JSON',
type: 'POST',
success:function(data){
userpro_end_load( form );
<?php
ob_start();
do_action('userpro_social_login', );
ob_clean();
?>
/* custom message */
if (data.custom_message){
form.parents('.userpro').find('.userpro-body').prepend( data.custom_message );
}
/* redirect after form */
if (data.redirect_uri){
if (data.redirect_uri =='refresh') {
//document.location.href=jQuery(location).attr('href');
} else {
//document.location.href=data.redirect_uri;
}
}
},
error: function(){
alert('Something wrong happened.');
}
});
});
I tried running the php action using:
jQuery(document).trigger('userpro_social_login', response.email);
Neither of these work... what am I doing wrong?

Modify your php function userpro_fbconnect trigger the code there or create another ajax request after this one is done

You can't execute PHP code from your JS and vise versa. But the following may help you:
<?php
// Some php code goes here...
?>
<script>
// JS code...
ob_start();
do_action('userpro_social_login', <?php <email needs to go here> ?>);
ob_clean();
</script>
And if you want to execute a method from your JS, and that method in defined using PHP, and it to the global scope, then simply call it from JS my_global_method()
I hope that helps fixing your problem.

Related

Run php script inside JavaScript at regular intervals using ajax or any method

I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";

Getting data from database on pageload jquery php

can any one help me please
What Im trying to do is a phone app using HTML5, JQUERY, Json and PHP. I cannot use PHP pages in this as I will be packaging it with Phone Gap Cloud Compliler.
I have tried using many scripts and suggestions that I have researched on the internet but cannot seem to get this to work.
On the page I need to retrieve data from the database there are 6 text boxes or divs I wish to populate using a on page ajax request to a PHP processing page that gets the required data and forms it into a Json string, the following scripts will show where I am at presently.
PHP Page:- this works as far as getting the data from the database and from the research I have done succssefully parces it into a Json format
PHP Script **********************************************
<?php
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
session_start();
$return_arr = array();
$sql = "SELECT * FROM `autumnTerm`"; //query
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$row['term1start'] = date('d-m-y', strtotime($row['term1start']));
$row['term1finish'] = date('d-m-y', strtotime($row['term1finish']));
$row['term2start'] = date('d-m-y', strtotime($row['term2start']));
$row['term2finish'] = date('d-m-y', strtotime($row['term2finish']));
$row_array['term1start'] = $row['term1start'];
$row_array['term1finish'] = $row['term1finish'];
$row_array['term2start'] = $row['term2start'];
$row_array['term2finish'] = $row['term2finish'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
this returns the following json :-
[{"term1start":"01-04-15","term1finish":"02-04-15","term2start":"03-04-15","term2finish":"04-04-15"}]
which I believe to be the right format.
The Jquery:-
<script>
I think I am right in believing that document ready should run the jquery script on page load
$(document).ready(function() {
the processing page address which is associated to a variable
var url = "http://www.newberylodge.co.uk/webapp/includes/retrieveAutumn.inc.php";
The ajax request defining the request elements
$.ajax({
type: "POST",
cache: false,
url: url,
dataType: "json",
success: function(data) {
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
If anyone would be so kind as to helping me figure this out I would be most greatful, I have been trying to resolve this for over a week now
I havent posted the html trying not to swamp the question with code, but if its needed I will put it up on request
try this:
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "json",
success: function() {
console.log()
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
and try to see the console is there any error?
you should try for the error Cross-Origin Request Blocked to put proper header
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
header('Access-Control-Allow-Credentials: true');
the rest code its ok

PHP request through AJAX fails

This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);

ajax in wordpress and wp_query

In my funcitons.php file i have function that response to ajax call and return posts:
functions.php:
function returnPosts(){
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
get_template_part('content', get_post_format());
}
} else {
get_template_part( 'content', 'none' );
}
exit();
}
add_action('wp_ajax_returnPosts', 'returnPosts');
add_action('wp_ajax_nopriv_returnPosts', 'returnPosts');
Javascript (in index.php):
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url("admin-ajax.php"); ?>",
data: {"action": "returnPosts"},
success:function(results){
// Work with results
}
});
But when i call this function via JS i always get content from content-none.php file.
It looks like you're assuming the AJAX call will know what post is being displayed on the page already, since you're checking have_posts() without creating your own WP_Query. But an AJAX call comes in as a separate HTTP request, and the only things it knows about the previous page are the things you tell it.
In additon to passing your "action" name in the AJAX call, try passing the current post's ID. I'm not in front of a real computer to test this, but this should work assuming you're inside a Loop when that jQuery code is output:
data: {"action": "returnPosts", "p": "<?php the_ID(); ?>"},
Quick fix is to:
include("../../../wp-load.php"); <-- guessing at the location of the wordpress file.
at the top of the php file.

"Continue" a PHP redirect with AJAX?

I have an HTML form that is processed via PHP, and it's a simple login script. This works fine, but I want to catch the error with AJAX. Basically, if the PHP function to check the login returns false, it should write that error onto the DOM via jQuery. However, if I catch the form submission with AJAX, it will stop the PHP file from doing the redirect. I want to stop the form from redirecting only if the PHP file returns false. Any help would be much appreciated. Here's some code to illustrate what I'm talking about:
controller_login.js
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
errorHandle(response);
}
});
return false;
});
});
function errorHandle(error)
{
console.log(error);
}
This is the file that will eventually modify the DOM if there is a PHP error. For now, it just logs.
checkLogin.php
if($verifySqlRequest==1){
session_register("loginUsername");
session_register("loginPassword");
header("location:http://localhost/asd/dashboard.html");
echo "login success!";
}
else{
echo "Wrong user name or password...";
}
This is just a snippet of the login authentication, but essentially I want that last echo to be communicated to controller_login.js, but it should continue the redirect if the login is successfully authenticated. Any help would be much appreciated!, thanks!
The browser isn't going to respond to a 302 or 301 (redirect) from an Ajax call. You can still certainly respond with that code, but, you'll have to handle the redirect manually via script:
window.location.replace("http://localhost/asd/dashboard.html");
or you can do it like this
> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';
and
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response_element').html(response);
}
The point of using Ajax is to avoid reloading the page. If the user is going to be redirected upon login you may as well just submit the form synchronously and let PHP display the error.
Just for the sake of argument, if you wanted to do an Ajax function and display a message returned from the server you would NOT do:
<?php
echo 'this is the message';
?>
You would do
<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>
However, you can't redirect AND return data.

Categories