jQuery variable to php variable - php

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.

Related

Passing data to PHP via Ajax without using a submit button

I've had a look around and unfortunately the solutions I've found on the site don't appear to address my issue below.
Basically I'm doing a project where I need to effectively set up a diary - the user writes in a textarea element and this is passed via PHP to a database and stored for the user. In the lecturer's video, it appears he's doing without using a submit button (even if he's not, I think it'd be an interesting thing to learn how to do).
I'm having some issues though. Here's my PHP:
<?php
session_start();
if(array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if(array_key_exists("id",$_SESSION)) {
echo "Logged in: <p><a href='secretDiaryFinal2.php?logout=1'>
Log out</a></p>";
} else {
header("Location: secretDiaryFinal2.php");
}
/* I'm putting in the database update later, for now I just wanted to check if I could
actually create the POST variable below*/
$msg = "";
if(array_key_exists('diaryEntry',$_POST)) {
$msg = $_POST['diaryEntry'];
} else {
$msg = "Some kind of PHP error";
}
?>
The relevant HTML:
<body>
<div id="testDiv">
<? echo $msg ?>
</div>
<div class="container" id="diaryArea">
<form method="post">
<textarea id="diary" value=""></textarea>
</form>
</div>
The relevant JQuery (I'm very weak on Ajax and I suspect there's a lot of issues here - also note the url I'm using is actually in the same script as the JQuery, I'm not certain if that works?) is below.
The basic idea is that every time the user types, the database should be updated (I realise this is a lot of calls to the server, I'll probably replace it with a timed command):
<script type="text/javascript">
$("#diary").keyup(function () {
var dataString = $("#diary").val();
$.ajax({
type: "POST",
url: "loggedInPageFinal.php",
data: ({diaryEntry:dataString}),
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
Many thanks in advance and apologies for my poor code!
var DataString = $("#diary").val();
$.post( "loggedInPageFinal.php",{dataString:DataString }, function( data ) {
console.log(data);
});
Your ajax script actually does work.
But your php code isn't returning anything. put exit($msg); at the end of the code and see what happens.

$.post not posting data

This is my code below for page.php file.
<?php session_start(); ?>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<script type="text/javascript" src="js/new-landing.js"></script>
<script type="text/javascript">
var ans1 = "home";
function aa(){
$.post("ajax.php", { "ans": "test" }, function(data){
alert("Posted");
}, "html");
};
</script>
<a href="#" id="q1" onClick="javascript:aa();" >click</a>
and this is where i want to see if my data is posted.
<?php
session_start();
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
when i click the anchor tag. the alert box is shown. but when i refresh the ajax.php page. it shows an error..Notice: Undefined index: ans in ajax.php on line 3
and the print of session is also empty.
Array(
[demo] =>
)
but when i refresh the ajax.php page. it shows an error
It sounds like you want to set the session variable when a value is posted, and get the session variable otherwise:
<?php
session_start();
if (isset($_POST['ans'])) {
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
}
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
$.post and $.get are just shorthand versions of the more structured $.ajax(), so I prefer using the latter. The additional structure keeps me straight.
Since you are using jQuery anyway, I would re-structure your code like this:
$('#q1').click(function() {
var test = "Hello there";
$.ajax(function() {
type: "POST",
url: 'ajax.php',
data: 'ans=' +test+ '&anothervarname=' + anothervarvalue,
success: function(recd_data) {
alert('Rec'd from PHP: ' + recd_data );
}
});
});
Note that the data: line is for example purposes and does not match with your code -- just showing you how to pass variables over to the PHP side.
Of course, the above includes removing the inline javascript -- never a good idea -- from your anchor tag HTML, thus:
<a href="#" id="q1" >click</a>
Also, on the PHP side, you can verify that things are working by adding a test at the top. Matching with the data: line in the example AJAX code, it would look like this:
ajax.php
<?php
$a = $_POST['ans'];
$b = $_POST['anothervarname'];
$response = '<h1>Received at PHP side:</h1>';
$response .= 'Variable [ans] has value: ' . $a . '<br>';
$response .= 'Variable [anothervarname] has value: ' . $b . '<br>';
echo $response;
Important: Note the use of echo, not return, to send values back to the AJAX script.
Also note that you must deal with the stuff returned from PHP in the AJAX success: function ONLY. If you need access to that data outside of the success: function, then you can stick the data into a hidden <input type="hidden" id="myHiddenInput"> element, like this:
success: function(recd_data) {
$('#myHiddenInput').html(recd_data);
}
Here are some additional examples of simple AJAX constructions:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

get variable to jQuery from php

this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
$('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
alert(data);
});
});
If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.
The inputfield:
<input type="hidden" value="<?php echo $error; ?>" id="errors" />
And the jQuery-Code:
var errors = $("input#errors").val();
You can't place PHP code inside "javascript" file, PHP code must be in PHP file.
The below code can work if it's placed in .php file:
<html>
<head>
<title>javascript test</title>
<script>
var error = '<?php echo $error;?>';
alert(error);
</script>
</head>
<body>
</body>
</html>
I am assuming that your $error will by different depending on the $_POST values.
If your response header is in HTML, then you can do something like this.
// in your JS codes.
$.post('settings.php', function(response) {
$('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});
// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); } die(); ?>
Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.
$.getJSON('url for the php file', function(data){}
And in the php file just echo the value
see http://php.net/manual/en/function.json-encode.php
Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute

how get php respone from jquery .load

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.

php inside javascript checkbox value

I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??
Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.
Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>
Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}
Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>
Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...
Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>
It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/
Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.

Categories