accessing a PHP object (in another file) within a jquery code. Help - php

I have a json object in a PHP file and I want to access it from a JQuery.js file, which both located in an index.php page.
Do you have an idea how to do that ?
index.php
<?php
include('theFileThatContainsJson.php'); // say it's $json
?>
<html>
<head>
<script language="javascript" src="jquery.js" type="text/javascript"></script>
</head>
<body>
.............
</body>
</html>
and here, what we have in jquery.js file, you can see my work (which doesn't work ;) ):
$.getJSON(<?php echo '$json'; ?>, function(data){ .... }
How to solve the puzzle <<< at least for me at this moment :) ?

One way (nasty!) would be to do something like this..
<script language="javascript" src="jquery.js.php?data=<?php echo base64_encode($json) ?>" type="text/javascript"></script>
.. and on your jquery.js.php file:
$.getJSON(<?php echo base64_decode($_GET['data']) ?>, function(data) { ... });
Of course, this is terrible practice and shouldn't really be done.. The best ways could include:
Have theFileThatContainsJson.php to simply echo the JSON, and have jquery.js just do an AJAX request to get the data
Have theFileThatContainsJson.php actually print out a <script></script> tag that contains a Javascript variable which you can use

if json not big:
$.getJSON('<?php echo '$json'; ?>', function(data){ .... }
or even
$.getJSON('<?php include('theFileThatContainsJson.php'); ?>', function(data){ .... }
in second case theFileThatContainsJson.php should echo that json.
in both cases should be in body of page
anyway I would not suggest to make it like that (use ajax for example)

Related

interaction between jquery and php using GET

I want to write a web page and use jquery to GET a small amount of data from php at the server, but in the same file, when i click a button. I want to send ?nm=bill and answer with 'bob'. i press the button but it doesn't seem to arrive at the server. I get the contents of the file i am sending the query to. I clear the browser, firefox, history before i press the button. Here is the code.
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("a_foo.php?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
var_dump($_SERVER["REQUEST_METHOD"]);
if ($_SERVER['QUERY_STRING']) {
echo "bob";
}
}
?>
</body>
</html>
but in the same file
So all of the code shown is in one file? If that's the case then any request to that file is going to receive the entire response.
I get the contents of the file i am sending the query to.
That's expected behavior. The very first thing this file does is emit all of the HTML at the start. Then it executes some PHP and conditionally emits a single value at the end.
Putting these things into separate files would be the ideal approach. One file is the UI, the other file is the service that handles the AJAX request and returns just the expected data.
But if you really want them to be in the same file then you'd need to conditionally return all of that HTML. Since the only difference between the requests at this time is whether or not a query string is present then your whole PHP file would look something like:
<?php
if ($_SERVER['QUERY_STRING']) {
echo "bob";
} else {
/>
<!-- ALL of your other HTML goes here -->
<?php
}
?>
As you can probably imagine, this structure gets pretty ugly and difficult to maintain pretty fast. Which is why the preferred approach is to separate these things into their own files. Each PHP file would do just the one thing it needs to do, rather than having one big PHP file which conditionally does multiple different things.
The current target of request is a_foo.php i fix it and show bob if the get nm is bill else show html
<?php
$_nm = $_GET["nm"];
if($_nm == "bill"){
echo "bob";
}
else
{
?>
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
</body>
</html>
<?php
}
?>

Integrating JQuery into php file

I am trying to tweak a website so users will be able to swipe through the photo galleries on their mobile devices. I tried doing this by using JQuery. The website was not written by me, so I can't really explain the choices the previous programmer made regarding their code.
Currently, users can change pictures by clicking (tapping) on the current picture. The code for this is found in a php file called home.php. This is it:
<?php
...
$main_content .= "\n <div class='main_image'>
<a href='$next_slideURL' style='display:block'>
<img src='$root/$item_path/$slideFile' alt='$slideCaption from $projectTitle\n [xxxxxxxxxxxxx]' style='max-width:832px; max-height:500px' title='$projectTitle: $slideCaption. \nclick for next slide ($next_slideCaption). '></a>
</div>\n";
...
?>
To add swiping capabilities, I added the following code right after the one above:
echo "<script type='text/javascript'>";
echo "(function(){
$(\"div.main_image\").on(\"swipeleft\", swipeleftHandler);
$(\"div.main_image\").on(\"swiperight\", swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage(\"$next_slideURL\", {transition: \"slideleft\", changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage(\"$previous_slideURL\", {transition: \"slideright\", changeHash: false});
}
});";
echo "</script>";
While I'm not sure exactly why this isn't working, I have a few possible reasons (which might all be true unfortunately).
1) Since the div class='main_image' is done as a variable declaration, the JQuery line "div.main_image" doesn't have a reference (i.e. it doesn't know what main_image is). I'm not sure why the div is created as a variable declaration ($main_content keeps being added on throughout the php file, and in the end it's echoed along with a bunch of other variables).
2) I need to include the following code for JQuery but I have it in the wrong place:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
right now I have it in the header section of index.html file. Is this wrong?
3) I've never used JQuery before, so any number of things might be wrong about the short script I wrote.
Sorry about the long post, I'm not sure how to explain this in a simpler way.
I'd appreciate it if anyone could help me either with this approach, or propose a different one.
Cheers!
Use $ while writting ready function
<?php
echo "$(function(){
// ---^--- use $ here
....
....";
echo "</script>";
?>
If $ conflicts then your can use jQuery like,
Full Code:
<?php
echo "<script type='text/javascript'>";
echo "jQuery(function(){
jQuery('div.main_image').on('swipeleft', swipeleftHandler);
jQuery('div.main_image').on('swiperight', swiperightHandler);
function swipeleftHandler(event){
$.mobile.changePage('".$next_slideURL."', {transition: 'slideleft', changeHash: false});
}
function swiperightHandler(event){
$.mobile.changePage('".$previous_slideURL."', {transition: 'slideright', changeHash: false});
}
});";
echo "</script>";
?>
Looks like you need to put your javascript in the $main_content variable, like the other code.
But to be honest you should seperate your javascript from the html/php.
Best way is to break out of php tags
and change this (function () to $(function ()
<?php
//php code
?>
<script type='text/javascript'>
$(function () {
$("div.main_image").on("swipeleft", swipeleftHandler);
$("div.main_image").on("swiperight", swiperightHandler);
function swipeleftHandler(event) {
$.mobile.changePage("$next_slideURL", {
transition: "slideleft",
changeHash: false
});
}
function swiperightHandler(event) {
$.mobile.changePage("$previous_slideURL", {
transition: "slideright",
changeHash: false
});
}
});
</script>;
<?php
//php code
?>

jQuery post() to php page

I'm learning php/javascript so don't smile...
I try from page1.php to post 3 variables to page2.php.
I'm not sure what's wrong...
Here is the code (simplified mode):
page1.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = post_text;
function post_text() {
test1="111";
test2="222";
test3="333";
$.post("page2.php", { test1:test1 , test2:test2, test3=test3 });
}
</script>
</body>
</html>
page2.php
<?php
$a=$_POST['test1'];
$b=$_POST['test2'];
$c=$_POST['test3'];
echo $a.$b.$c;
?>
$.post("page2.php", { test1:test1 , test2:test2, test3:test3 });
Since you are learning, you might try to isolate problems by writing shorter chunks of code and seeing if they work first. In this case your first problem is an ordinary typo (test3=test3, instead of test3: test3) so your whole JS does not parse. You should be seeing the relevant error message in the firebug console (or chrome console).

How to get dynamically-generated JSON into PHP

I've got a JSON value that has been converted from a JavaScript object using JSON.stringify. I'm trying to parse the contents of the JSON using PHP, but I haven't had any luck. I'm sure I'm doing something really basic wrong.
In file1.php, I've got something like:
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src='/json2.js'></script>
<script>
var irxmlnewsreleases = new Array();
irxmlnewsreleases[0]={
"attachmentfileid":12039
};
var news_release = JSON.stringify(irxmlnewsreleases);
$(document).ready(function () {
$("#response").text(news_release);
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
I'm then trying to read this data from file1.php using json_decode in file2.php.
I tried first (wrongly) using file_get_contents and have been bashing at this for a while without success. I guess the issue is obviously that the JSON value doesn't exist until the JavaScript is run, so PHP is of course never able to read the value of the jQuery-generated div content. What I don't know is how to get that value.
The JSON is being generated successfully in file1.php and is valid JSON (I've run it through jsonlint).
What's a better way of getting the value of that dynamically-generated JSON into PHP?
$(document).ready(function () {
$("#response").text(news_release);
$.post('file2.php', { php_post_var1: news_release }, function (data) {
//do something with the PHP script output here if you want
});
});
Then in your PHP script file2.php do something like
<?php
$news_release = $_POST['php_post_var1'];
echo 'PHP received ' . $news_release;
?>

Ajax calls in JQuery always return successfully but 'data' parameter is an empty string

I am just trying to test a simple ajax call on my server using jquery
I have a HTML file like this
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#connect_button").click(function(event){
$("#placeholder").load("http://mysever/AjaxResponse.php");
})
});
</script>
</head>
<body>
<button id="connect_button" type="button">Connect</button>
<span id="placeholder">This has not worked</span>
</body>
</html>
AjaxResponse.php, which works when accessed from the browser statically, looks like this
<?php
echo "This now works";
?>
The code runs and the replace happens the only problem is that the page returns a blank string causing the span to be empty
If I change the code to use another jQuery call such as $.get() the callback is sent back the textStatus of "Success" and a data value of ""
What am I missing here? Do severs need to be set up to respond to Ajax calls. Am I misusing jquery?
Is your AjaxResponse.php on the same domain? Ajax calls won't work cross-site.
If you want, you could check if the loaded page has anything in it like this:
$(function(){
$('#connect_button').live('click', function(){
content = $.get('test.php',function(data){
content = data;
if (content != ""){
$('#placeholder').html(content);
}else{
$('#placeholder').html('This has not worked');
}
});
});
})
That way if the returned data is empty, it will put "This has not worked" in the placeholder id.

Categories