Execute php script from html - 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>

Related

Passing Javascript Variable To PHP Using Ajax Echo's Undefined Index

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

change php variable with ajax

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.

Unable to fill input value with PHP variable

I have two files, landing.php and test.php. Landing.php has a form that is submitted via ajax using the post method to test.php. If the ajax call is successful, the browser loads test.php, at which point I am having an issue. I cannot figure out what I am doing wrong in my attempts to display the value of the post data that is sent to test.php.
The following is the ajax call from landing.php. I am reasonably sure that this is working correctly from having looked at the post data in Firebug.
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function() {
window.location.href = "test.php";
}
});
});
Here are the contents of test.php.
<?php
$bar = $_POST['barcodeID'];
echo "<html>";
echo "<body>";
echo "<p>*" . $bar . "*</p>";
echo "</body>";
echo "</html>";
?>
If I were to take the asteriks out of the line with the <p> from test.php, I would be presented with a completely blank screen when I arrived at test.php in my browser. With them there, however, I am presented with "**" on my screen. The most confusing part is, however, that if I include
echo $bar;
in test.php, I see the value of $bar (00-00102 - exactly as it should be) in Firebug's response tab on the post data viewer.
After some research, I read that post was the method of choice for when you do not want to display query strings in the URL bar, as well as the method to use when you have a large amount of data to send (which will be the case for me, it'll end up being around five to six hundred characters when all is said and done). I've looked at other stackoverflow posts and articles, attempted to replicate what was recommended, and still cannot get this right.
Am I doing something completely wrong or attempting to use these methods in a way in which they are not intended to be used?
Don't change the window location in the success of your ajax call. The call is posting the data to test.php and you are getting your response back there. Then you are redirecting to the page with a blank post which results in just the asterisks.
If you only want to display the results from test.php change your $.ajax call to the following:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Or if you do want to change the page, forget about the ajax and just post the form to test.php
You are reloading the window after the AJAX succeeds, there is no POST information at that point.
You can do something like this though:
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php', // <-- POST exists during this call
data: data1,
type: 'POST',
dataType: 'html',
success: function(data) {
$('html').replaceWith(data);
}
});
});
The AJAX POST will be finished in one turn. That means, the values you had posted to test.php
through ajax will be present only through that request. What you are doing is, you are redirecting to test.php upon receiving response from test.php. This is a fresh request, and it does not have any POST values. Hence, there is nothing in $_POST['barcodeID'];
Also, in your code, you are having $('#barcodeID').val() twice. Try removing the last one.:
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' +
$('#barcodeID').val();
$('#barcodeID').val();
If you are trying to use AJAX to replace the content of the page with the result of the form submission to test.php then you would need to change the AJAX call in landing.php to:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Otherwise I would suggest not using AJAX and just do a regular form submission using HTML by setting the action attribute of your form as such:
<form method="post" action="test.php">
You are passing the variables to the test.php file as a POST request, which means that the test.php file will get that data and act on it. Then after that request is successfully completed you are redirecting to test.php without passing any variables.
If you really want to submit a form (with the redirect that comes with it), do that using html:
<form action="test.php" method="post">
<input type="text" name="barcodeID" />
</form>
If you don't need the redirect, do what others have suggested and show the output on the same page instead (someDiv is the html element where you would like to display the response from test.php):
$('#searchForm').submit(function(e) {
e.preventDefault();
var data = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.post('test.php', data, function(response) {
$('someDiv').html(response);
});
});
If you must do it using JavaScript and a redirect, append a hidden dummy form to the page and submit it:
$('<form action="test.php" method="post">' +
'<input type="hidden" name="barcodeID" value="123456789" />' +
'</form>')
.appendTo('body')
.submit();

How can I use a jQuery var in some php code?

I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.

PHP Not Getting Information from Javascript Jquery

I have a javascript page that is supposed to send the username that the user enters to a php script on the server. The javascript page comes from http://192.168.1.4/login.html and it tries to access a php script at http://192.168.1.4/GetInfo.php. I think that I cannot access the username in the php script from the javascript page because of the same origin policy in firefox however, I'm not sure how to confirm this suspicion so please forgive me if I am wrong. I have only just begun to learn javscript and php. I was wondering if there is a different way to pass this information then. The code is below. Thanks!
The javascript:
<html>
<head>
<title>Login Page for SplitAuth</title>
</head>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script language="Javascript">
function getUsername()
{
var username = window.prompt('Please Type Your Username');
var temp = document.getElementById('temp');
temp.innerHTML = username;
jQuery.ajax(
{
type: "POST",
url:"GetInfo.php",
data: username,
success: function(msg)
{alert("data Saved: "+msg);}
});//ends the jQuery send
}//ends the GetUsername function
</script>
<body onLoad=getUsername()>
<div id="temp">This will show text</div>
<body>
</html>
The php script:
<?
$inFile="MyID.config.php";
$handle=fopen($inFile, 'r') or die ("No credentials could be gotten because the file MyID.config.php would not open.");
echo $_POST['msg'];
fclose($fh);
?>
You should prepend your data: with "msg=".
...
data: "msg="+username,
...
and the reason is that jQuery.ajax expects a query string or an object, which means that
...
data: {msg: username},
...
would also work.
Take a look at the jQuery.ajax Documentation. Specifically the data-section
You are using POST method and data that you are sending is wrong. You need to build data to be sent. Take a look at jquery page in ajax method. This is what it says for data attribute.
http://api.jquery.com/jQuery.ajax/
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Your script should look like this.
$.ajax({
type: "POST",
url: "GetInfo.php",
data: "{name:"+ username + "}"
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
And your php script isn't getting the username value. The "msg" used in your $_POST['msg'] will alert nothing because it is not having any value. The "msg" varaible is meant to store the value of the returned value to your html page. I will recommend you read more of from www.jquery.com

Categories