I've been trying to get this really simple example of using AJAX with JQuery and PHP to work with no luck (here's the page for the sample). I've had a look at quite a few posts with similar discriptions and none have helped...
I've copied the code exactly but my function that should be run on success is never called. As an experiment, in the call to $.post I commented out the data part ({sendValue:str}) and the JSON part and added an alert into the body of the success function to see if it was called and it was. So I'm guessing there's something wrong with how I've created my data? I also tried to display the data returned from the AJAX call in the alert and it came out as 'undeclared' (data.returnValue).
This is a copy of my code, you can see the full example via the link above and also a working example from the author of the tutorial here: http://www.devirtuoso.com/Examples/jQuery-Ajax/
JQuery:
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
function sendValue(str){
$.post("ajax.php",
{ sendValue: str },
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
PHP:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>
HTML:
<body>
<p>On keyup this text box sends a request to PHP and a value is returned.</p>
<label for="txtValue">Enter a value : </label><input type="text" name="txtValue" value="" id="txtValue">
<div id="display"></div>
</body>
Thanks!
EDIT:
I rewrote my $.post into a $.ajax with an error function in it. I'm definitely hitting the error function and the error is a parse error - I'm guessing it's coming from my PHP script when I call json_encode... here's a screenshot from firebug - anyone got any more ideas?:
Screenshot 1 - firebug console
Screenshot 2 - firebug watch window
Thanks for all the help so far by the way, really appreciate it.
I noticed that var str = $('#txt').val(); would give you an error because $('#txt') does not exist, it should be $('#txtValue').
After looking at your code, everything looks as it should, my next step would be trying to debug your code by using some console.debug() in JavaScript and some echo in PHP. I recommend you get Firebug for Chrome/Firefox and if using IE upgrade to IE9 and use their developer tools. Using the mentioned tools will give you a better idea of how your code is executing.
My first step would be to make sure that the keyup is firing:
$(document).ready(function(){
$('#txtValue').keyup(function(){
alert('keyUp');
sendValue($(this).val());
});
});
Second step would be to make sure sendValue is firing:
function sendValue() {
alert('sendValue');
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
alert('inside post');
$('#output').html(data.returnValue);
},
'json'
);
}
Without seeing more of what your various elements are outputting, I don't think I can tell you what to fix, but this example is similar to yours (although it's an all-in-one PHP file rather than two, as in your example). I also added a 350ms timeout to allow the user to type without having the page do an AJAX request every keystroke. As soon as they pause, it'll fetch the data.
Source to test.php
<?php
if(isset($_POST['sendValue']))
{
echo json_encode(
array('returnValue' =>
'Returned: ' . $_POST['sendValue']));
exit();
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Sample</title>
</head>
<body>
<input type="text" id="txt" />
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var tmr = null;
$(function () {
$('#txt').keyup(function() {
if(tmr != null)
clearTimeout(tmr);
tmr = setTimeout("sendValue()", 350);
});
});
function sendValue() {
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
$('#output').html(data.returnValue);
},
'json'
);
}
</script>
</body>
</html>
To anyone who gets here looking for an answer to a similar question:
I tried a few things to figure out what was going on, debugging the messages etc and everything looked fine. I then deployed my code to a virtual box running apache and to my web server to see if it was an environmental thing. My code worked on my web server and on the virtual box. I then realised that I had two conflicting installs of PHP on my dev system. I'm not sure why but this was causing the problem but rolling them both back and reinstalling WAMP on the dev system did the trick.
try this
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.post("ajax.php",{ sendValue: str }, function(data){
$('#display').html(data.returnValue);
},
"json"
);
});
});
Related
So as you can probably tell, I'm a bit amateur when it comes to jQuery. So if there's any better methods to do what I'm trying to do, please share kindly :) Here's what's happening. Everything works smoothly in the script when you substitute <?php echo $header_id; ?> for a given id that is compatible, say 17. Although $header_id is defined before this script, it must not be really outputting '17'.
I did research before this, not finding anything to help.
So I guess the main question is, does adding a PHP echo really work in this instance, or do I need another method, or is that not even the problem...
$(".vote-button-disabled").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
var quizid = "";
console.log(quizid);
$.ajax({
url: "scripts/vote-post.php",
type: "POST",
data: {
'quizid' : '<?php echo $header_id; ?>',
'upvote' : '1',
},
success: function() {
console.log('yes!');
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
Thanks in advanced!
Something to understand is that PHP is executed on the server side, and JavaScript is executed on client side.
PHP does not actually have any awareness of what is HTML, what is JavaScript, or what is plain text. It just knows that it's serving back some kind of content (maybe). So when you echo HTML or JavaScript code, you're really just creating a text file as far as PHP is concerned. You're creating a file that contains some text (that happens to be HTML + JS code) and sending that as the response to the HTTP request. Your browser interprets the resulting text in the response (which happens to be HTML + JS code). So one way you can think of PHP is as a HTML + JS generator. You can use PHP to output HTML + JS (and of course much more).
Once you understand that PHP is completely done executing by the time the page is sent back for the browser to interpret the HTML and JavaScript, the answer to what you can and can't do with JavaScript becomes much simpler. PHP is not interacting with JS, it's creating the JS code as text for your browser to read after PHP execution has completed.
So, as #charlietfl mentioned in the comments on the question, you should add the quizid to a data-quizid attribute on the button (assuming you're using HTML5), and then get the attribute for the specific element that was clicked, using var quizid = $(this).data('quizid');
If it's an external from PHP .js file, it won't work.
You could, however, insert JS directly in the PHP/HTML view document.
<?php
// Some PHP processing here, whatever you want
?>
<html>
<head>
<script type="text/javascript">
// Your Javascript here, for example:
var some_data = '<?php echo $some_variable; ?>';
// ...
</script>
</head>
<!-- Whatever you want to add -->
</html>
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 am trying to load the output of a PHP script into a using JavaScript and JQuery. The JavaScript function I am using uses the $.get function in JQuery to call a php script, which I want to display in another division. The script I wrote is:
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
});
});
}
</script>
The PHP script (dbtest.php) uses a simple echo statement:
echo "hello, world!!!";
I am getting the first alert here, but not the second. What Can I be doing wrong here?
I suppose uname is a ID, in that case you should use:
$("#uname").html(data);
You can add this to your php for debugging:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
Try also to remove http:// from your ajax call and use relative path instead.
The guys below pointed out that the selector is wrong. Indeed that's a problem, but I think that the real issue is that you don't get the second alert. Probably your php file localhost/dbtest.php is not accessible. What happen if you open localhost/dbtest.php in a new tab?
I think the problem is the path to your dbtest.php file. You are saying you seecond alert will not be displayed so your request must be wrong.
Try to copy your page into the same folder like dbtest.php open the page in your browser with http://localhost/yourfile.php
If this does not display both alert-boxes try the same with an open developer console (Chrome/IE = F12) and look if there are errors.
You say you are trying to make ajax requests to your localhost from a Phonegap application. Phonegap prevents making ajax requests to other domains by default. You must add localhost to whitelist. Here is more detail: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
Here you have a working example:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="uname"></div>
<script>
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("#uname").html(data);
});
});
}
on_load();
</script>
Beware of the same-origin-policy. The page loading dbtest.php must be from the same origin, unless you grant other origins by adding a header from dbtest.php.
Try add some error handling to your code to better see what´s happening.
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
}).fail(function () {
alert("failed");
});
});
}
</script>
Can someone help me out? I have an html file that calls a php script via ajax and displays a random number that the php script generates. It works just fine when both files are on the same domain, but if the 2 files are located at different domains, which is what I need, nothing happens. Can someone help me fix this.
The code for the HTML file is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
}, 5000); // the "5000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
</head>
<body>
<div id="divToRefresh">Loading users...</div>
</body>
</html>
If the line
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
is changed to:
$('#divToRefresh').load('random.php');
and placed in the same folder as the html file all is well.
The code for the php file is:
<?php
$random1 = sprintf("%02f", rand(0,9212));
echo $random1;
?>
What would the revised code that would allow cross domain ajax calls look like? I was reading documentation that talked about a json request wrapper, but I did not get where it was going. Any help would be hugely appreciated.
you are not able to use ajax cross domain its not possible, you have the following options though:
1.do the ajax to your own page and make a curl call to that page..
2.do $.getJSON('ur', variables, function(data){}).
there are few other solution, but those 2 are basically your best options
here is how getJson works:
On your server you should have a page that is ready to receive the $_GET sort of like an API or normal ajax call would do with $_POST.
should look something like :
<?php
if(!empty($_GET['jsoncallback']) && !empty($_GET['variable'])){
/* do whatever you like with the variable you get as get
*
*
*
**/
// echo the name of the callback function + the variables you want to receive back in JS
echo $_GET['jsoncallback'].'('.json_encode($jason_echo).')';
}
?>
Your JS or page you are going to do the call from should look something like:
$.getJSON("SomePage/PagethatTakesTheGet.php?jsoncallback=?", {variable:15}, function(response){
// do whatever you want with response.
});
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}