PHP file never called from jQuery - javascript

I have the following script in a HTML file that is called when the document is loaded:
<script>
$(document).ready(function(){
setInterval(function() {
$.get('check_session.php', function(data) {
alert('Load was performed.');
});
}, 5000);
});
</script>
The alert message will be called on the interval, but the PHP is not actually called because nothing is echoed.
PHP file: check_session.php
<?php
//check_session.php
session_start();
echo '<script language="javascript">';
echo 'alert("successful")';
echo '</script>';
echo $_SESSION['user_token'];
if(isset($_SESSION['user_token']))
{
echo '0'; //session not expired
}
else
{
echo '1'; //session expired
}
?>
Essentially, I am trying to call the PHP file, check_session.php, on a five second interval. This is one of my first times implementing jQuery, and after much research, I am still lost.
Any suggestions as to why the php file is not called are appreciated.
---UPDATE:
From Network tab:

Check data parameter
<script>
$(document).ready(function(){
setInterval(function() {
$.get('check_session.php', function(data) {
alert('Load was performed.');
console.log('data: '+data)
});
}, 5000);
});
</script>

the problem might be here: $.get needs URL and other optional params. you are simply giving filename. I think you should add appropriate path also. try it !!

Related

Is it legal to combine JS and PHP ... Is that PHS or JHP?

Here I have an example... It works fine, but is it legal?
<script>
setTimeout(function() {
$('.hide_3sec').fadeOut('fast');
<?php
if(isset($_GET["msg"])){
?>
window.history.replaceState({}, document.title, "/admin/" + "?tab=accounts");
<?php
}
?>
}, 3000); // <-- time in milliseconds
</script>
Yes, it's actually a quite common practice in order to pass server variables into the UI. Is it the best practice? I'm not qualified enough to answer that.
Example:
<script>
pageNumber = <?php echo $PAGE_NUM ?>
</script>
In your case, you have an entire if statement print out. It would be simpler to make the if statement always print out, but the boolean that's checked be printed by PHP.
<script>
setTimeout(function() {
$('.hide_3sec').fadeOut('fast');
if(<?php echo var_export(isset($_GET["msg"])); ?>){
window.history.replaceState({}, document.title, "/admin/" + "?tab=accounts");
}
}, 3000); // <-- time in milliseconds
</script>

AJAX Post Successful but PHP not responding

I'm having trouble with an AJAX POST to PHP call.
JS in an PHP file (tableOutput.php)
var changedArr=[];
var undoRedoArr=[];
//For editing data, http://tabulator.info/docs/3.3
$("#tabulator").tabulator({
cellEdited:function(cell){
//this is called whenever a cell's value is edited.
var value = cell.getValue();
var theID = cell.getRow().getIndex();
var ip=cell.getRow().getData();
var field = cell.getField();
var x=Object.values(ip);
console.log(ip);
changedArr.push(x);
},
});
//called when I hit a button
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(){
alert("SAVED!");
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<?php
include "getInfo.php";
?>
PHP code in a different file (getInfo.php)
<?php
if(!empty($_POST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Post")';
echo '</script>';
}
if(!empty($_REQUEST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Request")';
echo '</script>';
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
</html>
Earlier in the files, I have a GET command that works.
HTML in tableOutput.php
<div class=form>
<form onsubmit="fillTable()" >
<input type="submit" name="deny" value="Denied" />
<input type="submit" name="permit" value="Permitted" />
</form>
</div>
getInfo.php
$test="'CREATE'";
if( isset( $_GET['deny'] )){
$test="'DENY'";
}
if( isset( $_GET['permit'] )){
$test="'CREATE'";
}
Tried on Fedora and Windows. Code is on a server. Browser: Firefox
The Ajax posts successfully. I get an alert box saving "SAVED!", but nothing echos on the page. If I use window.location.href instead, then the getInfo.php echos to the page. The problem is that I get redirected to the getInfo.php page, which I don't want.
How do I get the Ajax to post to the getInfo.php file? Why is it not working?
It looks like you are trying to mix two different mechanisms here (AJAX and post-back). When you use AJAX, simply echo-ing output will not insert that content into the DOM (like it does when using a full post-back). Your echo statement puts data into the output stream that is then consumed by your success function. And it will stay there unless you programmatically (using javascript/jQuery) insert it into the DOM. You can manually insert that into the DOM. There are many ways of doing that. The key is looking at your response object. This is one possibility:
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(response){
alert("SAVED!");
//add the script element to the DOM body
$(response).appendTo('body');
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
It is important to understand that when including a php file (like getInfo.php), the output is written on the client side and cannot be accessed by php anymore.
What you want is to request the getInfo.php, get its response the write it on the client side.
Client:
<script>
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(textResponse /* you MUST use this parameter*/){
alert("SAVED!");
// textResponse is the string the server sends. do whatever you want with this
document.getELementById("out").innerHTML = textResponse;
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<div id="out"></div>
At the server side, it is important you do not include any <head> or <body> tags, otherwise you will have a new document inside your <div id="out"></div>! You should write just pure text, or something that can be put inside a div element, like a table.
Server: getInfo.php
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
}
?>
or write pure html closing the php tags (a nice trick):
<?php
if (isset($_POST['ipString'])) {
?>
A request has been made
<?php
}
?>
If your getInfo.php file needs to have its <head> and <body> tags, you must exit() the script so the rest of the file will not be sent.
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
exit(); // exit here so ajax doesn't get the rest of the file
}
?>
<html>
<head></head>
<body></body>
</html>
Finally, if you want to be flexible and have your client do stuff based on what the server sends, you should try JSON which converts objects to strings and vice versa.
The problem was not with the code posted.
At the beginning of getInfo.php, I forgot to add "php"
It was:
<?
instead of:
<?php

How to alert box from ajax php function

I have function frm_trigger_entry_update this is the php function which is run in background i mean this is ajax php function.
In this function i have write some jquery or javascript function which will alert some text message.
In bellow snippet code you can see my function code.
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
}
?>
I have tried bellow snippet logic but its not work for me mean the alert box is not showing after calling this function.
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
?>
<script>
jQuery(document).ready(function($){
alert("my message");
});
</script>
<?php
}
?>
So how can alert the box in this php function any one have any idea.
Use JS and Php Separately.
First ajax call from your JS file:
$.ajax({url: "frm_trigger_entry_update function's Url",
success: function(result) {
alert(result);
}
});
In php Function, from where you should send your message:
function frm_trigger_entry_update($atts) {
echo "my message";
}
Consider following is your ajax call
$.ajax({url: "URL to frm_trigger_entry_update",
success: function(result)
{
alert(result);
}
});
Your PHP function
<?php
function frm_trigger_entry_update($atts)
{
echo "my message";
}
?>
Try this:
echo "<script>alert('test');</script>";
Note : The best practice to do this with Ajax because function is in
server side so you should call it to server from Client using Ajax
Create one file eg: "frm_trigger_entry_update.php"
IN "frm_trigger_entry_update.php" put your function
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
echo $atts;
}
// Call to that function
frm_trigger_entry_update("ATTRIBUTE_VALUE");
Write Ajax on your HTML
$.ajax({
type: 'get',
url: 'PATH to frm_trigger_entry_update.php',
success: function(data) {
alert(data);
}
});
You will get output Alert as ATTRIBUTE_VALUE
In your php function you need to return the output :
<?php
function frm_trigger_entry_update($atts)
{
return "<script>
jQuery(document).ready(function($){
alert('my message');
});
</script>";
}
And then where you want to apply this script you can display the output of your function :
<?php
...
$script = frm_trigger_entry_update($ats);
echo $script;
However in my opinion, this is not a good practice, you should put your javascript in a js function, in a js file and include your js file in your document or call it when needed.
Calling a php function via ajax is really impossible because ajax uses a url for php file and not a php function.
Though your code works and will alert if you call it via php.The code below will alert what ever string you put in the parameter of your function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<?php
function frm_trigger_entry_update($atts)
{
//here i have some php code which run properly
?>
<script>
jQuery(document).ready(function($){
alert("<?php echo $atts;?>");
});
</script>
<?php
}
//calling the function and passing a simple string
frm_trigger_entry_update("Alert Message");
?>
</body>
</html>

How to echo javascript into current html page from external php file

Let's say I'm currently browsing mypage.html, which in its header has a link to the following js file:
<script language="JavaScript" type="text/javascript" src="jsfile.js"></script>
In jsfile.js, there's a function keyup() that is executed when the user types something into #searchbar, whose value is then stored in search = $(#searchbar).val();
I then pass this value on to search.php as follows:
$.post( "search.php", { searchval: search }, function(sentdata){
console.log(sentdata);
});
where the content of search.php reads:
<?php
if(isset($_POST[searchval])){
$search = $_POST[searchval];
echo "input value is $search";
echo "<script type='text/javascript'> alert('its working') </script> ";
}
?>
However, instead of an alert pop up (or anything else that would normally be executed in JS), the second echo simply prints " alert('its working') " into the console.
How can I modify search.php to allow it to inject actual js into myfile.html? Note that I've also tried wrapping the js code in tag.
Related question: why is it that when I omit console.log(sentdata), search.php does no longer echo anything into the console?
How I can modify search.php to allow it to inject actual js in myfile.html?
First of all, you need to modify your javascript file:
$.post( "search.php", { searchval: search }, function(sentdata){
eval(sentdata);
});
And no need for javascript tags, just echo a valid Javascript code:
if(isset($_POST[searchval])){
echo "alert('its working');";
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval
you can do this
$.post( "search.php", { searchval: search }, function(data){
alert(data); // this will alert the data which will print on search.php
});
and in the php file echo the data you want to print like
if(isset($_POST[searchval])){
echo 'its working. i got'.$_POST[searchval];
}

Failed to send data via the callback function argument to $.post method in javascript from a php file

My javascript posts a request and after it succeed, the response(the echo statement in php file) is send to the .html() method in the call back function (so that I can use it to display on the webpage). But the data I tried to send from the php file never seems to appear in the var 'recData'. Please help me to find the problem.
JavaScript Code:
$.post(php_file_url, function(response) {
$( "#Trend" ).dialog({modal: true,
width: 900,
height:550 });
$( "#Trend" ).html(response);
});
Php Code:
.....;
$arrayVar;
echo"<script>
var recData = <?php echo json_encode($arrayVar); ?>;
...*use recData *...;
</script>";
php is backend language so you can't do it
var recData = <?php echo json_encode($arrayVar); ?>;
true is
echo"<script>
var recData = ".json_encode($arrayVar).";
...*use recData *...;
</script>";

Categories