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);
Related
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";
I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
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.
This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
I'm having a weird issue when returning variables from PHP To Javascript I have a ajax call to a function as seen below(I am using CodeIgniter):
public function automaticEnd(){
$this->load->model('test_model');
$this->test_model->addResult("common");
$id = $this->input->post('id');
echo "success/";
}
In my AJAX call I simply want to see an alert box appear with success/
$.ajax({
type: "POST",
url: "/project/main/automaticEnd",
data: data,
success: function(msg){
alert(msg);
}
});
however I am seeing an output such as:
"0:12:14success/"
anyone seen this issue before? any help would be much appreciated
I believe the problem relies in the addResult() method of your test_model.
Check to see if there is another echo statement in there.
The string before "success/" looks like time. Maybe you echo a value there for testing purposes.