echo jQuery function in PHP as variable - php

Ok so I am trying to echo an function from jQuery inside of PHP.
I was searching a little bit, I did not found any exact answer but I found that I need to use ajax for it ?
I am not familiar with ajax so I have found this.
<?php
$status = "<script>
$.ajax({
url: '/',
data: {action: 'test'},
type: 'post',
success: function(output) {
notifyBox();
}
});
</script>";
?>
I also have this part somewhere on the page:
<?php if(isset($status)) { echo $status; } ?>
I am not quite sure if I need all of that to execute the function ?
But it works only if I put jQuery in head of the website.
I usually put all my scripts above </body> (at closing tag) and now it bothers me if I have to put all these scripts into head
Because of many pages I cannot separate all scripts now just cause of one page that bother me at the moment.
Can anyone please tell me, how do I call that function without getting console error of undefined '$' because jQuery is loaded at the end of the page.
Thank you in advance.

That should work so long as you make sure that you put your PHP if statement after the <script> tag that includes jQuery.

The problem is being caused by jQuery not being loaded when that variable is echoed. When Javascript sees a function call, it executes it right then and there. To prevent this, you will need to echo your variable after jQuery has been loaded.
Example:
<script type="text/javascript" src="path/to/jquery.js"></script>
<?php
echo $script;
?>
OR, you can put your AJAX call into a function that will be called later:
<?php
$script = '<script type="text/javascript">function myFunc() {
//Call AJAX here
}
</script>';
echo $script;
?>
Then later, you can call your function: myFunc();

Make sure jquery is loaded. This should work:
$status = "<script type='text/javascript'>
$(function(){
$.ajax({
url: '/',
data: {action: 'test'},
type: 'post',
success: function(output) {
notifyBox();
}
});
});
</script>";

$(document).ready() is also a jquery function, hence, try it with window.onload.

Related

basic question regarding $_GET with AJAX and PHP

Just playing around with ajax and php and I have a simple question.
These are the following relevant files.
file.php
<?php
$bla = $_GET['pid'];
echo $bla;
?>
HTML
HTML Code of example site URL: somesite.com/blabla.php?pid=3
(It contains a single button which when you click it is supposed to get the $_GET value from the URL which is 3)
<!DOCTYPE html>
<html>
<head>
<title>Some Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button class="fa fa-icon" onclick="someFunction()"></button>
</body>
</html>
JS:
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
success: function(result)
{
alert(result);}
});
}
</script>
As noted by the commenters below: I've also tried the following
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
data: {pid: 3}, // added this line
success: function(result)
{
alert(result);}
});
}
</script>
The alert is blank there is no 3 on it when the php file has echo $bla which is $_GET['pid'] and the pid in the url is = 3.
Can someone please explain why that is the case? I dont think I understand what is happening behind the scenes of the above codes to figure out why.
Please note that I'm not trying to solve a particular problem or anything just trying to understand why $_GET is not working in this very specific case.
You're not sending any data in the AJAX request, hence there's nothing for the PHP to read and send back. To fix this include a data property in the request which contains the pid key and the required value, for example:
function someFunction(){
$.ajax({
method: 'GET',
url: "file.php",
data: {
pid: 3
},
success: function(result) {
console.log(result);
}
});
}
Note that I'm using method: 'GET' here, which is important as you're using $_GET in your PHP, so a POST request won't work. Also note that I'm using console.log() to debug the value. alert() shouldn't be used for debugging as it coerces data types.

New to ajax and can't set the session variable with a post request

I've been struggling with this for two hours now and I've narrowed down the issue to a simple test case. I've done plenty of research and finally settled on trying to reproduce the first answer from this question: Set session var with ajax.
When I push this button (lazy html, but that's not where the issue lies):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
This ajax request in jquery.js gets called:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
And finally the setSession.php file:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
The success message is printed to the console so I know I'm hitting the right file. Why isn't the session variable getting set? I have php 5.5.2 if that matters at all. Thanks for you help!
Like I suggested on the comments, do this to fix your code:
Reload the page on your success:
success: function() {
console.log("Successful request sent");
location.reload();
}
Make sure you have session_start() in all the pages that uses sessions:
session_start(); //this must be at the top, before you print anything
Might this can help you.
In setSession.php write echo $_SESSION["foo"] = $_POST["bar"];
In your ajax script do
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
now open browser console (F12). click on your button.update. Check if is there written bar in console.

load partial page using AJAX in PHP page

I'm trying to figure out how I can load a partial page (div) into another div using AJAX in my php page.
basically I have a div with some php output stuff, and I need to put that div's content into another one using ajax but my code doesn't do anything (it doesn't put the div's content into the other one).
this is my current code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
$("#issomeone").html($(response).find("#notis"));
setTimeout(load, 4000);
}
});
}
load();
});
</script>
so the #notis div holds the php output and the #issomeone div is the div that i need to put the stuff in using ajax.
is there something missing in my code or I'm just doing it all wrong?
any help would be appreciated.
Thanks
EDIT:
THIS DOESN'T DO ANYTHING:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
//$("#issomeone").html($(response).find("#notis"));
$('#issomeone').load("<?php echo $actual_link; ?> #notis");
setTimeout(load, 4000);
}
});
}
load();
});
</script>
You are finding the DOM element and then trying to set that as target element's innerHTML with html(). You in essence have a type mismatch.
You would need to get the innnerHTML of #notis to pass as the parameter to this function so:
$("#issomeone").html($(response).find("#notis").html());
Alternately, you could append the node if you want to keep the whole #notis element
$("#issomeone").append($(response).find("#notis"));
But really, since you are using a straight GET, you might be better off simply doing:
$('#issomeone').load('<?php echo $actual_link; ?> #notis');
This provides a more simple abstraction to what you are trying to do more manually with .ajax()
I would however encourage you to not get in the habit of loading full HTML pages and then scraping them for some particular element. It is better design architecture to have the AJAX target script serve up only content that is needed when possible.

PHP json_encode data to jQuery for AJAX call

I am having a problem in using json_encode function.I am putting a simplified version of the problem here.
Here is the file containing php and jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<?php
$test = "xxxxxxx";
?>
<p onclick="testAjax()">Click here</p>
<script>
var sendbody;
function testAjax(){
sendbody = "<?php echo json_encode($test); ?>";
$.ajax({
type: 'POST',
cache:false,
url: 'testAjaxCall.php',
data: {sendbody:sendbody},
success:function(data){
alert("1");
},
error:function(data){
alert("0");
}
});
}
</script>
And the ajax file simply contains
<?php
echo "testAjax";
?>
When I use json_encode function, the jquery code written after using the json_encode function stops working and the ajax function shows neither the success message nor the error message.
However if I write it as
sendbody = "<?php echo $test; ?>";
In this case the jquery code below this line works and shows success message.
When using json_encode, you don't have to quote the result, it's already quoted.
So change
sendbody = "<?php echo json_encode($test); ?>";
to
sendbody = <?php echo json_encode($test); ?>;
Otherwise you got:
// this cause syntax error
sendbody = ""xxxxxxx"";
First of all whenever you are expecting JSON to be returned to your AJAX call you have to tell it that by setting dataType: 'json', if not it tries to process it as text and obviously fails (your call is a success but the processing of the response isn't). The next best thing to do is use console.log(data) to get a better understanding of the response.

Need help in passing value form JS to PHP

I have some problem with passing value from javascript file to php file.
I make some calculations in JS, and after that i passing it to php.
This is a code of JS:
var price=100;// for example
$.ajax({
type: "POST",
url: "SecureRide.php",
data: { calculatedPrice: price }
});
And this is a code of PHP:
<?php
session_name("ridePrice");
session_start();
$_SESSION["calculatedPrice"]=$_POST["calculatedPrice"];
echo $_SESSION["calculatedPrice"];
?>
So what i do is a simple Ajax function that passes the value to php, very simple, but doesn't work!
When I do echo function there's nothing there.
Maybe there are another way to solve it?
Thank you very much!
Note : if you are put your ajax code in function and than call function from the "$(document).ready(function(){" then your code run perfectly
I write code in your .js file :
$(document).ready(function(){
functionName(price);
});
function functionName(price){
$.ajax({
url: 'SecureRide.php',
data:{calculatedPrice: price},
type: 'POST',
success:function(data)
{
alert(data);
},
error:function(data)
{
alert("mistake in your code");
}
})
}
And Code For PHP file for get .JS File Data
if(isset($_POST['calculatedPrice']) && !empty($_POST['calculatedPrice']))
{
$calculatedPrice1=$_POST['calculatedPrice'];
}

Categories