jquery post php undefined index - php

This is my html with script
<div id="info" class="container-fluid">Here is some text</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
$.post("testPHP.php", {name: "John"}, function(data)
{
$( "#info" ).html( data )
})
</script>
and the php code
<?php
$name=$_POST['name'];
echo $name;
?>
In html I may see the name John displayed in the div with id info.
But when I run the php file I get this error
Notice: Undefined index: name in C:\xampp\htdocs\ticketing\testPHP.php
on line 2
How can I send a variable via Ajax to a php file and echo this?

Ajax in pass some extra data like type:"ajax"
and file in check
<?php
if (isset($_POST['type']) && $_POST['type']=='ajax') {
$name = $_POST['name'];
echo $name;
} else {
echo "You access with direct URL";
} ?>

Try to check if there is a post request in your testPHP.php
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
// do something else here
}

It won't send any data because there is no form in it. No object will be serialized(input, select, etc.).

Related

Send variable from PHP to JQUERY to other PHP file

I have an image and after clicking this image I take this game id by JQuery code and then a new PHP tap opens this PHP take should display this image id
Here is the JQuery code:
$(".selected").click(function(){
$.post("bookinfo.php", { id: $(this).attr('id') }, function (response) {
alert(response);
});
});
and here is the PHP code
<?php
$id = $_POST['id'];
echo $id;
?>
and here is the error that i get
Notice: Undefined index: id in C:\xampp\htdocs\bookstore\bookinfo.php on line 2
I have tried AJax request and get but the same error happens..
I have been trying for this error for about 2 hours so please help me!
You can do something like this:
Edited:
jQuery
<script>
$(document).ready(function(){
$(document).on('click','.selected',function(){
var id = $(this).attr('id');
window.location.replace("bookinfo.php?id=" + id);
});
});
</script>
PHP
<?php
if(isset($_GET['id']) && !empty($_GET['id'])){
$id = $_GET['id'];
echo $id;
}
?>
in your php you have to return a json to get it from AJAX. just try changing your php code like this.
<?php
header('Content-Type: application/json');
if(isset($_POST['id']))
{
$data = array($_POST['id']);
echo json_encode($data);
}

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 to inject javascript code that uses php variables into php page

I created a php page and javascript code that contains some variables from the PHP page, this is a code that inserts php variables into the database using Javascript :
<?php
$id = "Kevin";
$user = "Calvin";
?>
<!-- include jquery library file-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: <?php echo json_encode($id); ?>, to: <?php echo json_encode($user); ?>},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
</script>
and in the full.php page
<?php
mysql_connect("localhost","root","");
mysql_select_db("db");
$to=mysql_real_escape_string($_POST['to']);
$from=mysql_real_escape_string($_POST['from']);
$msg=mysql_real_escape_string($_POST['msgg']);
$to = mysql_real_escape_string($to);
$from = mysql_real_escape_string($from);
$msg = mysql_real_escape_string($msg);
if(empty($msg)){
exit();
}
$query=mysql_query("INSERT INTO `message`(`user`,`who`,`message`) VALUES ('$to','$from','$msg')");
if($query){
echo "Perfect!";
}else{
echo "Failed!!";
?>
so is there any way to put the Javascript code into another page and inject it using ajax?
Assign PHP variable's value to java script variable :
<script type="text/javascript">
var json{
"id":<?php echo $id;?>,
"user" : "<?php echo $user;?>"
};
</script>
Change this line from your code :
$.post('full.php', {msgg: msg, from: json.id, to: json.user}
Now you'll have separate js file like:
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: json.id, to: json.user},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
Say this file is myjs.js now include it in php file:
<script type="text/javascript" src="myjs.js" />

testing a php session variable on page load with Jquery

I have a session variable that is set when the user submits a form with a certain option selected. When the page refreshes I need to test this session variable and if it exists then make some of the form read only. This is my code so far, php:
<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Submitted</H2><p>";
connect('final');//connect to DB
$fName = $_POST['addFname'];
$lName = $_POST['addLname'];
$address = $_POST['address']
$dropdown = $_POST['field']; // yes or no option
$fName = htmlspecialchars($fName);
$fName = mysql_real_escape_string($fName);
$lName = htmlspecialchars($lName);
$lName = mysql_real_escape_string($lName);
$address = htmlspecialchars($line2); // stop HTML characters
$address = mysql_real_escape_string($line2); //stop SQL injection
if($dropdown== "no"){
$_SESSION['name'] = "$fName";
}
?>
'field' is the name of my dropdown with 2 options yes and no.
MY JS for getting the variable:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type = "text/javascript">
var session;
function multi(){
$.ajaxSetup({cache: false})
$.get('getSession.php', {requested: 'foo'}, function (data) {
session = data;
});
}
</script>
I use that to get the variable from the session, getSession.php has the following:
<?php
session_start();
if (isset($_GET['name'])) {
// return requested value
print $_SESSION[$_GET['name']];
} else {
print json_encode($_SESSION);
}
?>
finally I have this function to disable the text fields
<script language="JavaScript">
<!--
function enable_text2()
{
if (session !=""){
status = "true";
document.add.addFname.readonly=readonly;
document.add.addLname.readonly=readonly;
}
}
//-->
</script>
the rest of my html is just a form, this is all in one document with the php code at the top, and the javascript functions in the head tag.
I call a wrapper function in the body onload tag, which then calls both of those functions, I thought the first function would get the session variable if it existed from the php document and then the second function would test if it was not empty, if it wasn't then it would make the fields read only.
However when I select no in the drop down and submit the form, the page refreshes and nothing happens, the fields are not read only.
Why You are using javascript for it??
session_start();
if (isset($_GET['name'])) {
$disable=true;
} else {
$disable=false;
}
<input type="text" name="addFname" <?php if($disable) { ?> readonly="readonly" <?php } ?>
Here i have taken "addFname" .you can disable any element inside that php if condition
Assuming PHP is generating the page you've got this "must be disabled" form on, there's no need for an ajax call - PHP can output a JS variable when it builds the page, e.g.
<script type="text/javascsript">
var disableForm = <?php echo (($_SESSION['somevar'] == 'whatever' ? 'true' : 'false') ?>;
if (disableForm) {
...
}
</script>

jQuery variable to php variable

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.

Categories