i give another codes for example
this is my some3.php code:(First file)
:
<head>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var who = $('input#who').val();
var why = $('input#why').val();
$('#geting').load('file2.php',{who:who,why:why},function(applyData){
if ( applyData == 'YEY . Ye have hi' ){
alert('OKKK data is ok ');
} else{
alert('Nooo We dont have requested output');
}
});
});
});
</script>
</head>
<body>
<p> click </p>
<input type="text" id="who">
<br>
<input type="text" id="why">
<div id="geting" align="center">
</div>
</body>
i this my file2.php:
<?php
echo "1";
echo "2";
if($_REQUEST['who'] == "hi"){
$myVariable = "YEY . Ye have hi";
echo $myVariable;
} else{
$myVariable = "The out put is not Hi";
echo $myVariable;
}
?>
its not work why? becuse we have echo "1" and echo "2"
i want jquery just check $myVariable data not whole php callback ! i think i must use json but i dont know how
Well, assuming that you want to read the value with JQuery off the page you are posting to, you could do this, since you are echo'ing the value out in that page by doing the following: echo $myVariable;
Now this is how I generally read a value off another page with JQuery which is by using JQuery's get() method.
$.get("thepagetoretrievefrom.php", function(retrievedvalue) {
alert("Here's the data you requested: " + retrievedvalue);
if (retrievedvalue == 1) {
//print out something here
alert("The retrieved value was 1.");
}
});
And that should retrieve the value from the PHP page. "thepagetoretrievefrom.php" is the page where you want to retrieve the information from. function(retrievedvalue) just indicates that whatever output you're requesting from the page via JQuery will be put into retrievedvalue. Then, using JQuery, you may decide whether you want to do a new call to another page depending on what the "retrievedvalue" was.
This, however is not the best method to achieve this, since this will print whatever may be in that page, but if you are requesting one specific value from that page, then it shouldn't be an issue.
Related
delete_define.php has the following code snippet:
<?php
session_start();
?>
<form action="delete_now.php" target="upload_target" onsubmit="return my_func_1();">
<input type="submit" name="my_submit" class="my_submit" value="submit"/>
<iframe id="upload_target" name="upload_target" src1111="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
<script type="text/javascript">
function my_func_1(){
//alert("from within my_func() =" +<?php echo $_SESSION['my_session']; ?>);
alert(" my_func_1");
return true;
}
function my_func_2(){
alert("my_func_2 =" +<?php echo $_SESSION['my_session']; ?>);
return true;
}
</script>
delete_now.php has:
<?php
session_start();
$_SESSION['my_session']=rand();
?>
<script type="text/javascript">
alert("from within delete_now.php = " +<?php echo $_SESSION['my_session']; ?>);
window.top.window.my_func_2();
</script>
The problem is my_func_2() does not give the same output for the session variable as the alert box in delete_now.php gives.
Why is that?
EDIT: CHANGED THE CODE SAID TO BE IN delete_define.php
That's because when the delete_define.php was loading the Session var was one, then it's become another, but in you JS stored previous value.
You should store session var into JS var, and then in JS in delete_now.php reset it with the fresh value.
How to refresh value from frame and other situations
Add to first php file's JS something like:
var session_var = '<?php echo $_SESSION['my_session']; ?>';
And then in your delete_now.php's JS:
parent.session_var = '<?php echo $_SESSION['my_session']; ?>';
And change function my_func to alert session_var JS variable.
Think so...
Explanation:
Then result page js will be:
function my_func_2(){
alert("my_func_2 = 13513513513513");
return true;
}
So when you call it, whatever is in the $_SESSION is, there will be old, static value.
Overall process description:
Load delete_define.php
Javascript var, containing actual filename initialized
From submits
Script delete_now.php is runing
Javascript var in main window refreshes
You call my_func_2() which use you global JS var, containing fresh filename.
you have assigned random number, so based on the order you run the page will give alert,
if you start from delete_now.php two consecutive alerts will be same . first assign some static value and then check
<html>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
<body>
<?php
$x = 8;
if($x ==10){
echo "Hi";
}
else{
echo 'show_alert()';
}
?>
</body>
</html>
How do I get the echo to output the value of show_alert() ?
Change
echo 'show_alert()';
to
echo '<script>show_alert()</script>';
so that the browser knows to treat show_alert() as a function call and not regular HTML text.
You need to wrap it in a script tag:
if($x ==10){
echo "Hi";
}
else{
echo '<script type="text/javascript">show_alert();</script>';
}
Note, this will not wait until the page has finished loading to call show_alert(). The alert will be displayed as soon as the browser reaches this point in the page rendering, which may be otherwise incomplete behind the alert box. If you want it to wait until the whole page is loaded, place the condition to be called in <body onload>
<body <?php if ($x != 10) {echo 'onload="show_alert();"';} ?>>
<?php
if ($x == 10)
{
echo "Hi!";
}
?>
</body>
If you mean call showAlert() when the browser renders/evaluates that line:
echo '<script type="text/javascript">show_alert();</script>';
If you mean get the value of showAlert() in PHP, you can't - PHP is a server-side language.
This:
echo 'show_alert()';
will simply print "showAlert()" on the page, unless you have already opened a <script> tag.
I think you may be confused about the difference between client side and server side code.
HOWEVER, if you are using the two correctly, and you want to make it appear:
echo '<script type="text/javascript">show_alert();</script>';
It depends largely upon when you want the show_alert() javascript function to be called. Guessing by the PHP code that you're using, I am going to assume that you want the javascript function to be called as soon as the page loads, in which case you might want to use PHP before the body loads, and add an "onload" attribute event handler to your body tag:
if($x ==10){
echo '<body>';
}
else{
echo '<body onload="show_alert();">';
}
i have a problem when it comes to retrieving value from jQuery to php.i was able to get the value of my select and pass it to my php but i can't pass it back to php.
here is the code...
<script>
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
alert(m);
});
});
</script>
<div>
<select id="months">
<option value='00'>Month...</option>
<option value='01'>Jan</option>
<option value='02'>Feb</option>
<option value='03'>Mar</option>
<option value='04'>Apr</option>
</select>
<select id="years">
<?php
for($yr=10; $yr<=$year; $yr++)
{
echo "<option value='".$yr."'>".$years[$yr]."</option>";
}
?>
</select>
</div>
now i have to get the m variable from the jQuery code and echo it on my php.
You need to post or get the page again, passing "m" as a parameter and reading it inside php.
Php and jquery can communicate with each other only using http posts/gets, cause they run on two different computers (php on your server, jquery on your users browser)
Unfortunately, to answer this question completely would mean teaching client-server from the basics.
The jQuery code will run on your user's browser. You need to send m via POST (or GET) to your PHP script upon change.
Try this:
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
$.ajax({
type: 'POST',
url: "http://example.lan/your.php",
data: {m: m},
success: function(){alert("updated")}
});
});
});
and on your PHP code, do something about m if it is set:
<?php
if (isset($_POST['m'])) {
// do stuff with M here
}
?>
PHP and Javascript may appear in the same file, but they are far from being executed by the same machine. For example, take this simple script :
<?php
$foo = "Hello world!";
?>
<div id="mydiv"><?php echo $foo; ?></div>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
When you access this script from your browser, the server actually only parse this :
<?php
$foo = "Hello world!";
echo $foo;
Because everything else is not PHP, thus not processed by the engine (skipped at parsing time). Therefore, the document that is uploaded by the server to your browser is
<div id="mydiv">Hello world!</div>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
As you see, at this point, there is no PHP at all in what's outputted by the server (what is received by the client), so there is no way that you can reference anything PHP at that point. The only way you can do this is by calling the same script again! (or any other PHP script)
PHP may receive parameters from external sources via $_GET and $_POST. Thus, modifying our code would be like
<?php
if (isset($_GET['foo'])) {
$foo = $_GET['foo']; // we received our param like
// '?foo=Hi!` from the HTTP request
} else {
$foo = "Hello world";
}
?>
<div id="mydiv"><?php echo $foo; ?></div>
<form action="" method="get">
<input type="text" name="foo" value="" />
<input type="submit" name="submit" />
</form>
<script type="text/javascript">
$(function() { alert( $('#mydiv').text() ); });
</script>
And you can communication in both directions. For XHR with jQuery, there is no need to send a whole bunch of HTML with the query, we need to modify the source a little:
<?php
if (isset($_GET['foo'])) {
echo "Message got : " . $_GET['foo'];
exit; // do not execute any more code from now
} else {
$foo = "Hello world";
}
?>
<div id="mydiv"><?php echo $foo; ?></div>
<script type="text/javascript">
$(function() {
alert( $('#mydiv').text() );
// note : assuming the code is in file "example.php"
$.get('example.php', {foo: "Hi!"}, function(data) {
alert(data); // will show "Response got : Hi!";
});
});
</script>
In the last example, the file is parsed and processed twice by the server, the code is actually executed in this order :
the browser makes a first query to the PHP script
the server parse the file and sends the HTML,
the client receives the HTML
the Javascript code is executed
alert : "Hello world!"
create and send a GET XHR with parameter foo=Hi!
the server receives another request and parse the file
the $_GET['foo'] argument is found
echo "Response got : Hi!"
the client receives the XHR response and invoke the callback function
alert : "Response got : Hi!"
Now, this last example may seem a bit more complicated, but really as simple as the other code :
<?php
$dataFile = 'data.txt';
if (isset($_POST['text'])) {
file_put_contents($dataFile, $_POST['text'];
echo "Saved!";
exit;
} else if (file_exists($dataFile)) {
$text = file_get_contents($dataFile);
} else {
$text = '';
}
?>
<a id="lnkSave" href="example.php">Save</a>
<script type="text/javascript">
var text = '<?php echo addslashes($text); ?>';
$(function() {
$('<textarea></textarea>').attr('id', 'text').appendTo(document).val(text);
$('#lnkSave').click(function() {
$.post($(this).attr('href'), {text:$('#text').val()}, function(data) {
alert(data);
});
});
});
</script>
I'll let you figure this one out; what it does and how it works.
I am dealing with a View and Controller for a webpage, and I am trying to figure out how this would work:
Controller will initially define variables used in view upon page-load.
Once a user submits a form, it does an onclick jQuery function, which posts back to the controller.
The controller returns back to the View true or false, depending on whether the vote was successfully inserted into the database.
The View's jquery function continues, determining what to do next: if it was successful, perform another jQuery function.
the next jQuery function performs a $.get back to the controller, which determines the relevant variables to be used in the view.
Right now, mine works in terms of submitting the vote. However, I never see the alert pop-up when i'm running it, which leads me to worry that the set-up I have isn't working the way it should be.
Here is code from my PHP website controller:
if(!isset($_POST['poll'])) //UPON PAGE LOAD
{
//define relevant variables to be put into the view
}
if(isset($_POST['poll'])) //UPON jQuery $.Post() back to controller
{
if($_POST['poll']=='done')
$vote = 2;
if($_POST['poll']=='no')
$vote = 1;
$id = $_POST['id'];
$result = vote($user_id, $id, $vote); //inserts vote into Database
if( !$res )
echo json_encode(array('success'=>true, 'text'=>'success'));
else
echo json_encode(array('success'=>false, 'text'=>'fail'));
//I want ^this json data to be sent back to the jQuery of my view
}
if(isset($_GET['newListing']))
{
//code that would redifine relevant variables to be put into view
}
if(isset($_GET['newListing']) || !isset($_POST['poll']))
{
//code that does something--both upon page load and when needing to retrieve
//and define variables to put into view.
}
include('view.php');
Here is code from my HTML/jQuery website view:
<html>
<body>
<form name='poll' id='poll' >
<INPUT TYPE="radio" name='poll' value='done'checked/>Done it.<br/>
<INPUT TYPE="radio" name='poll' value='no'/>No.</br>
<button id='submit-vote' onclick="postVote();">Submit</button>
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</form>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function loadListing(){
$.get('controller.php?newListing=yes',function(data){
if(data.response == 'success'){
//something}
else{
return false;}
});
}
function postVote(){
$.post('controller.php', { poll: $('input:radio[name=poll]:checked').val(), id: $('input:hidden[name=id]').val()} , function(data){
if(data.success){
alert('data.text');
loadListing();
return true;}
else{
alert(data.text);
return false;}
},
"json");
}
</script>
</html>
Any help/suggestions appreciated!
EDIT:
From my View code:
the HTML:
<fieldset id='poll'>
<INPUT TYPE="radio" name='poll' value='yes' checked/>Yes!<br/>
<INPUT TYPE="radio" name='poll' value='done'/>Done it.<br/>
<INPUT TYPE="radio" name='poll' value='no'/>No.</br>
<button id='submit-vote'>Submit</button>
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</fieldset>
the jquery:
jQuery(function($){
$("#submit-vote").click(
function(){
alert("HELLO");
$.post('controller.php', { poll: $('input:radio[name=poll]:checked').val(), id: $('input:hidden[name=id]').val()} ,
function(data)
{
alert("THIS FUNCTION WORKS");
}, "json");
}
);
});
The controller is pretty much the same. When I click on the submit button now, the alert("HELLO"); is executed, and according to the Firefox's Firebug the $.post() does take place. However, the alert("THIS FUNCTION WORKS"); does NOT get executed.
I need help figuring out why that may be....
Thanks!
The problem is that json_encode creates a string. In your Javascript, however, you're trying to access it as if it's an object (data.success). You'd need to first use window.JSON.parse() to turn it into an object:
var dataObj = window.JSON.parse(data);
After doing that, you should be able to access dataObj.success.
To be honest though, I'm not sure why you're making it that complicated. Why not just return a simple string, such as "success" or "failure"? Then you don't need to encode the object in php or decode it in JavaScript. You'd simply do:
PHP
if( !$res )
echo 'success';
else
echo 'failure';
JavaScript
if(data === 'success'){
//do your stuff
}else{
//do other stuff
}
Edit in response to OP's first comment on this answer
Your JavaScript will regain control once the PHP script ends. In the code you posted, you include a view.php file at the end of the PHP script. I don't know what's inside view.php, and it's quite possible that including this file will cause your JS alert() to still not fire even if you make the changes I described above. That's because if there is any output (i.e. echo, print, etc.) that runs in the view.php file, that will get appended to the string created by json_encode. The result will be a string that can not be parsed by window.JSON.parse().
If you want the script to end after echoing "success" or "failure" (or your json_encoded version), simply put return; after the echo statement:
if( !$res ){
echo 'success';
else
echo 'failure';
}
return;
the include('view.php'); should ONLY to be put into the if(!isset($_POST['poll'])) //UPON PAGE LOADcode.
I'm drawing a complete blank why this isn't working. I can do it with one variable passing through, but not two. When I use actually numbers like getnt(1,2) it works. It's just not working with two PHP variables.
<script type="text/javascript">
function getnt(nid,pnid) {
window.location = "nt.php?nid=" + nid + "&pnid=" + pnid;
}
</script>
<body>
<?php
echo "<a href='#' onclick='getnt($nid,$pnid)'>VIEW</a>";
?>
</body>
I can make the code work with echo "<a href='nt.php?nid=$nid&pnid=$pnid'>VIEW</a>";, but that's no good if I want to add in alerts and javascript commands.
If the ID and pnID are strings, enclose them with brackets like this.
<body>
<?php
echo "VIEW";
?>
</body>
If still not working, You can debug your code
View the source code in browser,
make sure it generates correctly.
Put some alert messages in the
javascript function. Install Firebug
if you have Firefox or see
Javaascript console if you get any javascript errors.
You could always try:
<script type="text/javascript">
function getnt(nid,pnid) {
window.location = "nt.php?nid=" + nid + "&pnid=" + pnid;
}
</script>
<body>
VIEW
</body>
Your question is probably best answered by looking at the rendered HTML source.
In any case, here's how I'd do it using graceful degradation
<script type="text/javascript">
function getnt(element) {
var href = element.href;
var nid = element.getAttribute("data-nid");
var pnid = element.getAttribute("data-pnid");
return true;
}
</script>
<p><a href="nt.php?nid=<?php echo $nid ?>&pnid=<?php echo $pnid ?>"
data-nid="<?php echo $nid ?>"
data-pnid="<?php echo $pnid ?>"
onclick="return getnt(this)">VIEW</a></p>