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
Related
I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms.
This form works with AJAX and won't refresh the page like it usually does.
I have everything set now and it is working. but..
So this is the form im talking about to help understand.
When you click on request a new password, i need the code to change on the input field.
I do change the code after requesting a password like this in newpass.php
$_SESSION['capcode3'] = $capcode3;
This is my javascript code:
<script>
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
});
</script>
So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value.
So if the code is ABC123 and the new code is DEF456 it wont change to DEF456
Is there a better way to send the new code back to the input field?
Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.
You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled
$.ajax({
type: "POST",
url : "data/newpass.php/",
success: function(data) {
//change UI here
document.getElementById("captcha").value = data;
},
});
Please add code in success of ajax because may be session value will be changed on ajax success.
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data,
success :function(data){
document.getElementById("captcha").value = data;
}
});
Please try with this.
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 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();
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 have some code
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
alert(response.id);
});
</script>
An alert screen appears and shows the value i want (response id). but i would like to assign this value to a php value called $id i know how to do this but because the value is in script it wont work, i have tried adding in the below code without success
</script> <?php $id ?> <script> response.id </script> <?php ; ?> <script>
this code is added just below the alert(response.id);
If you want to use the value on the server side the only way is to send it with AJAX to the server and after that store it in the Database or do something.
You can do something like this
<script>
FB.Event.subscribe('auth.login', function(response)
{
FB.api('/me', function(response) {
$.ajax({ type: "POST", url: "save-fb-id.php",data: {id: response.id} });
}
});
</script>
Forgot to mention this is jQuery implementation
In your PHP script do the following:
<?php
$fbID = $_POST['id'];
save_to_db($fbID);
?>
PHP code is executed by the server before it sends the page to the client. Anything in a script tag is executed by the client. In order to send a value back to PHP, you'll have to submit some kind of request back to the server - it could be a hyperlink (a href='page.php?id=whatever), a form with a hidden value, an ajax request, etc
To add the value to a database, you'll need a php page (eg mypage.php) to insert your entry, with something like
if (isset($_GET['insertme'])) {
mysql_query("INSERT INTO myidtable (id) VALUES ('{$_GET['insertme']}')");
}
And in your script, find some kind of ajax function and send a request to mypage.php?insertme=myid, where mypage is your database inserting page and myid is the id you want to insert.
Note that it's unsafe to insert values from $_GET directly into your database like that - you'll want to filter out single quotes first to prevent sql injection.