I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.
HTML FILE
<head>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid }
});
</script>
</head>
<body>
<?php include("serverSide.php"); ?>
</body>
serverSide FILE
<?php
$btid = $_POST['btid'];
echo($btid);
?>
DESCRIPTION
So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.
I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.
Your ajax call is not doing anything with the value that is being returned.
I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).
When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.
Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.
If I understood what you are trying correctly, your code should look more like this:
HTML FILE
<head>
</head>
<body>
<div id="response"></div>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid },
success: function(res) {
$('#response').text(res);
}
});
</script>
</body>
What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).
Related
I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.
I'm trying to connect to my SQL server to get some data in a html table.
To do this, I have a php script with the necessary code.
The issue is to execute the script.
How can I tell html (or javascript) to execute the script?
I can tell you, these methods didn't work for me
Javascript
$.get("testConnection.php");
(I have no idea where to put this next code)
AddType application/x-httpd-php .htm .html
I've read that it's possible to send a request via Ajax, but how can I connect to my server (example: mysql5.test.com) and database (databaseForTesting).
Also, I don't have any experience/knowledge in Ajax.
Thanks!
To use ajax, you must first include jquery in the head of your doc, then put the following code below at the end of the body tag (right before </body> tag)
You can then edit the data variable to send your data as $_POST. To access the data this script sends to your php script, you just call the $_POST variables. Ex: to access var2, put in your php script $_POST['var2']. If you use GET instead of post, remember to use $_GET['var2'] in your php script to get that variable.
var data = 'var1=value&var2=value2&var3=value3';
$.ajax({
type: "POST", //can be POST or GET
url: "URL_TO_SCRIPT_GOES_HERE.php",
dataType: "html", //or json
data: data, //data to send as $_POST to script
success: function(response) {
//Once data received, do this
alert(response);
},
error: function(response) {
}
});
The database connection line should just be put in the php file. It has nothing to do with the jquery ajax script.
To execute the ajax call, you can just run it how I have here (it will load on page load) or you can put it in a javascript function and call it according to an event:
function my_ajax_call() {
var data = 'var1=value&var2=value2&var3=value3';
$.ajax({
type: "POST", //can be POST or GET
url: "URL_TO_SCRIPT_GOES_HERE.php",
dataType: "html", //or json
data: data, //data to send as $_POST to script
success: function(response) {
//Once data received, do this
alert(response);
},
error: function(response) {
}
});
}
A onclick button trigger:
<a onclick='my_ajax_call()'>CALL AJAX</a>
You can use inclue php funcion to include your file into HTML like below
<html>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
include 'testConnection.php';
?>
<b>Here is some more HTML</b>
<?php
//more php code
?>
</body>
</html>
I know this has been covered a few times, but I'm completely a noob when it comes to javascript so I have no idea what I'm doing. I am running a javascript that sends variables to a php file and that info is ajaxed into the current page using innerhtml. Here is that part of the code...
function givingHistory(dyear,did)
{
var divname="giving" + dyear;
$.ajax({
url: 'finance/givinghistory.php',
type: 'POST',
data: {
year: dyear,
id: did
},
success: function(givedata) {
document.getElementById(divname).innerHTML = givedata;
}
});
}
</script>
In the givedata function response from the php file there is a call to another javascript function that is already loaded in my common .js file (so both javascript functions are loaded when the page loads). How do I get the onClick that is added via innerhtml to work? Inside the php file, I check to see if id = a php session variable. If it does it spits out the text that includes the onClick.
If you use a specific id/class/identifier when the page loads in the $('*') function then the action will only bind to that. To get the action bind to anything ever try using $(document).on('click', **selector**, function() {});.
Previously there was bind/live that bound to elements as and when but on is the function now.
Also why are you mixing the $.ajax (jQuery) with document.getElementById(divname).innerHTML (regular javascript)? If you are already using jQuery you could just use $('#'+divname).html(blahbahblah);
I am current have the following script. I want pass a value from javascript to php by using AJAX. What's wrong with my code?
<script type=" text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.post("index.php",{host:document.referrer},function(data){});
});
</script>
<?php
$dataString=$_POST['host'];
echo $dataString;
?>
Since the PHP is executed first, you will never see the echo $dataString from your AJAX request. This code will post your request to the server, but you'll never see the result.
Right now here is what is happening:
Your web server renders out your page.
Your browser posts a request to index.php, and ignores the result
From the docs you can see this:
$.post('index.php', function(data) {
$('.result').html(data);
});
The data in that function will return what echo $dataString; outputs from your script.
Also, your post isn't configured correctly. You need to put data: before {host:document.referrer}
I am creating a PHP site and have ran into the following problem, i would like to be able to click a hyperlink on a page, send a small data item to a php script, have the script perform its function and then return the results.
I am using AJAX with this site to have each page load into a div section of the site, all pages, data and responses load into this central div, like so:
<html>
<body>
<div id="topMenuBar">
<div id="contents">
//ALL DATA IS LOADED HERE...//
</div>
</div>
</body>
</html>
So, when a page is selected from the top menu i simply have the following code run:
$('#topMenuBar a').click(function(e)
{
e.preventDefault();
$('#contents').load($(this).attr('href'), function()
{
});
});
Now that pages load into the content section, I am loading a page called "results.php" which connects to a DB, queries it, and the creates a HTML table with the results. Each table row has a small hyperlink which when clicked is intended to send a value to another PHP script and then clear the contents div and then repopulate the div with the response from this script (getInfo.php). For example, a row will have the following PHP code generate a link:
<label class="moreInfo"><a name="test01" onClick="getInfoFromPHP(<?php echo $data[$id]; ?> )">Get Info</a></label>
So when the table is generated by PHP it, the link when clicked passes a JS function the value.
What i now need to do is to send the value to a PHP script which will again query the DB, and have the results inserted into the "contents" div. I have been trying the following function.
function getInfoFromPHP(myVar){
var netID = myVar;
$.ajax({
url: "getInfo.php",
type: "POST",
data: {
networkID: netID
},
success: function(html) {
$('#contents').empty();
$('#contents').load(html);
}
});
};
When i call the function it does seem to send the data to the script but i get the following error from firebug:
POST http://127.0.0.1/private/networks/includes/leave_a_network.php - 200 OK -15ms
GET http://127.0.0.1/%3Ch2%3EHello 403 Forbidden 21ms
"NetworkError: 403 Forbidden - http://127.0.0.1/%3Ch2%3EHello" Hello
The PHP script is only doing the following:
<?php
session_start();
$networkID = $_POST['networkID'];
echo "<h2>Hello World</h2>";
?>
What is the best way to send data to a PHP script and have it load into a div?
Thanks for any feedback.
In the success function, put $('#contents').html(html); instead of load.
success: function(html) {
Is returning html as a string that does not need to be 'load'ed again like you try here -
$('#contents').load(html);
Change that line to this
$('#contents').html(html);
A better way is using $.ajax to send the request. On the success callback, you can analyse the result, and do what you want with :
http://api.jquery.com/jQuery.ajax/