jQuery post() to php page - php

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).

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
}
?>

executing jquery code from php

$("#bt-potrdi").click( function(e) {
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
when i click on button this jquery code is executed and works fine. Can i execute this code without click event?
I want to execute this code from php when some data is executed successfully like for example
if ($ok) {
?>
//execude ajax code
e.stopPropagation();
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
<?php
}
is this possible? PHP is server side code so i didn't find any good example if this is possible
Similar to the other suggestions, but this doesn't rely on having 2 copies of the same code...
if ($ok) {
?>
<script type="text/javascript">
$(function() {
$("#bt-potrdi").trigger("click");
});
</script>
<?php
If you ever change the click event handler, this will still work. This means that you won't need to make any future changes in 2 places.
If I understand the question, you want to execute some javascript on page load if $ok is true. To do that, you should be able to do something like:
if ($ok) {
?>
<script type="text/javascript">
//execute ajax code
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
EDIT: Also, e.stopPropagation(); is not going to work because e is not defined anywhere.
What happens is when your PHP script is executed, if $ok evaluates to true, then your jquery code is included in the generated document, and is omitted if it doesn't. But at this point, there is no event, so the following line will not work.
e.stopPropagation();
However, as jdwire suggested, you can wrap your javascript in a script tag, and have it executed that way, without being triggered by an event. So... like this:
<?php
if ($ok) {
?>
<script type="text/javascript">
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
</script>
<?php
}
?>
I would design my code so that i could add classes and set z-indexes straight up when html is rendered, but if you want to do those with jquery, jsut wrap them in <script> and $(document).ready(function({}); so they will be executed when dom is ready.
eg.
if ($ok) {
?>
//execude ajax code
<script>
$(document).ready(function{
$("#belina").css({"z-index":200}); $("body").addClass("ext");
$("#vpisok_frame").css({"z-index":250}).fadeIn(200);
});
</Script>
<?php
}
edit
Okay i assumed e.stopPropagation(); is set somewhere before since it was in questions example aswell. removed it for now.
You can echo out the code in <script/> tags and it will be run as JavaScript, or with the code you have, just place it between tags and it should be fine :)
But you cannot do this "live". Only when the page is requested ONCE.
You can also do it this way to pass PHP variables over to javaScript. I think it's a lot cleaner.
$check = 1;
?>
...
<script type="text/javascript">
var check = <?= $check; ?>;
...
if (check)
{
$("#bt-potrdi").trigger("click");
}

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

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)

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.

Jquery error "u is undefined"

Why am I getting an error in Firebug "u is undefined"?
My page consists of a display of photos and photo gallery as a special separate section in the PHP code divided using the "break".
Photos and photo galleries are displayed using the "Fancybox.js".
The first time when I try to open a photo, everything works fine but when I do it again after I refresh the page the Firebug display error "u is undefined".
The Jquery for the menu that I'm using for display these separate part of the page:
$(document).ready(function(){
$(".menu_rfr").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
location.replace($(this).attr('rel'));
});
$(".menu_clickable").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
$("#main").load($(this).attr('rel'), function(event) {
});
$(".menu_clickable").unbind("click");
});
});
The simplified PHP code looks like:
<?
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
?>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=2">Photos</div>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=3">Gallery</div>
<div id="main"></div>
<?
break;//photos
case 2:
?>
<script type="text/javascript">
$("a.group").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/1.jpg" border="0">
<?
break;
case 3: // photo gallery
?>
<script type="text/javascript">
$("a.groupg").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/2.jpg" border="0">
<?
break;
}
?>
As I said this is a simplified code, and probably there are some errors in it. I just wanted to show where and how I'm using Fancybox.
Is there a conflict between the jquery code for the menu at the top of the page and this for fancybox or there is some other reason why I keep getting an error in Firebug "u is undefined" after opening the other part of the PHP page and attempts to re-opening photos?
View your HTML source and make sure you don't have FancyBox declared twice. I just had the exact same error pop up in firebug and this is what I found in my source:
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
<link rel="stylesheet" href="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.css" type="text/css" media="screen" />
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
Not sure exactly why it happened, but if you nest your include and require_onces in your PHP like I unfortunately did, you can wind up with some very funky Javascript references.
You probably have the fancybox.js script included twice which is causing the issue. Please check all your files and remove the the ones that are not required.
I have this same bug as well - I think it is due to the the 'loading' divs being reset by the cleanup code. I have a VERY nasty fix:
Change:
if ($("#fancybox-wrap").length) {
return;
To: (To skip the multiple-init check)
if (false && $("#fancybox-wrap").length) {
And add:
$.apzFancyboxInit = fancybox_init;
after 'fancybox_init = function() {'
What this does is allow us to call the initialisation routine multiple times; and saves the function pointer to this routine in a global variable. All we have to do now is make sure we call the $.apzFancyboxInit function every time a fancybox is closed. The best place to do this is in the onClosed function handler; so (in my case), my calls look like this:
$.fancybox(
{
'showCloseButton' : true,
'type' : 'ajax',
'onClosed' : function()
{
$.apzFancyboxInit();
},
If you are using a "ripped" template you may find that there are the fancybox generated div written in tho the html template right above the </body> tag.
check if your html output has a div with the id of fancybox-wrap if you have JavaScript disabled, and remove that.

Categories