I'm using jQuery to load the result of a PHP script into a variable. The script is passed something that the user typed with a GET request. I want to take just what the script spit out into its <body> tag. Here's what I've tried:
JS:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;});
alert($(dataloaded).find('body'))
}
But it just displays [Objec object]. How can I get a useful value that is just the contents of the body of a loaded page?
I know the PHP works, I just need the JS.
The script echos something like 1!!2 (two numbers separated by two exclamation points).
Thanks!
You are trying to access the dataloaded which might not be assigned due to the asynchronous nature of AJAX calls. The only safe place to access it is inside the success callback. Also you could use the .html() function to get the contents of the body tag:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get('script.php', { i: typed }, function(loaded) {
alert($(loaded).find('body').html());
});
}
Also note that if the script.php only echoes 1!!2 without a <body> tag it won't work.
Without knowing what console.log prints it is hard to say, but try these
alert($(dataloaded).find('body').html());
Or
alert($(dataloaded).find('body').text());
I changed the page that I'm trying to fetch to XML. I'm using $.find to get each element of interest individually from the XML page, which suits this particular app well.
This problem has disappeared, as there is no longer a head section to ignore, and I'm just grabbing individual XML elements anyway.
Thanks for all your time and help!
Use JSON type. I am not sure about whether your Jquery script correct or not but using JSON with a correct usage would solve problem. ie.:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;},"json");
alert($(dataloaded).find('body'))
}
And POST variable from script.php after encoding JSON. Use Php's json_encode() function. You need to create variable as an array. For example:
<?php
$title = 'Hello World';
$content = 'Get well soon Japan!';
$arr=array('title'=>$title,'content'=>$content);
echo json_encode($arr);
?>
And Jquery would be something like:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {var dataloaded = loaded.title+" "+loaded.content;},"json");
$("body").html(dataloaded);
}
You may need to use Jquery's parseJson() functions on some situations. Don't think you will need here.
Related
Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});
I have this Javascript function:
function capitalizeFL(string) { //takes a string, returns it with first letter capitalized
return string.charAt(0).toUpperCase() + string.slice(1);
}
A file called statuswindow.php, which includes the following:
<?php
$raceV = "<script>document.write(capitalizeFL(\"".$player->race."\"));</script>";
$clasV = "<script>document.write(capitalizeFL(\"".$player->clas."\"));</script>";
echo "You have chosen a " . $raceV. " " .$clasV ."!";
?>
Now the main file, which uses ajax to update and show the player's class and race ($clas, $race), after capitalizing their first letters using capitalizeFL:
Main file includes the following:
$("button").click(function() {
$("#topMenu").load("statuswindow.php");
});
What I would LIKE to happen, is that the html from statuswindow.php will be properly displayed in the main window's #topMenu div.
I'm assuming the problem is due to document.write overwriting the whole page. The question is, how can I do the following, without using document.write?
You can not use document.write after page load. what it does is opens up a new document and replaces what ever you have there with new content.
In this example there is no need to even use document.write. Just use the script tags. jQuery will handle the script tags for you.
You really should just skip using load and use $.get or $.getJSON and handle the response yourself.
Have the server return a JSON object.
{
raceV : "foo",
clasV : "bar",
outStr : "You have chosen a {1} {2}!"
}
and the JavaScript would be
$.getJSON("statuswindow.php", function(data) {
var outString = data.outStr;
outString = outString.replace("{1}",capitalizeFL(raceV));
outString = outString.replace("{2}",capitalizeFL(clasV));
$("#topMenu").html(outString );
})
BUT the real issue is:
Why are you not doing all of this in PHP. There is no reason for JavaScript to do it.
No JavaScript needed!
<?php
$raceV = ucfirst($player->race);
$clasV = ucfirst($player->clas);
echo "You have chosen a " . $raceV. " " .$clasV ."!";
?>
and the jQuery load would be the same
$("#topMenu").load("statuswindow.php");
echo "You have chosen a ".ucFirst($player->race)...
Would make more sense
When you use $.load you do not really want any scripts in the page you load and in this case there is absolutely zero reason to have javascript uppercase the first letter when php has a built-in function to do it
I'm assuming the problem is due to document.write overwriting the whole page. The question is, how can I do the following, without using document.write?
Because is exactly what document.write does.
Try with innerHTML:
For example, if you want to add content to #topMenu, just do:
document.getElementById('topMenu').innerHTML += capitalizeFL(".$player->race.");
This is a part of the code in a 'process.php' file:
echo "<script type='text/javascript'> percYes = ".$yes."</script>"
echo "<script type='text/javascript'> percNo = ".$no."</script>"
This 'process.php' file runs in the background (using jQuery/ajax) when the user clicks a butto. The 'echoed' html above replaces the contents of a div. So essentially what I'm trying to do is update some Javascript variables using a background php call, the above solution does not seem to work though, i.e. the script is not being ran once it is placed in the div.
A bonus problem involves using these updated Javascript variables to update a graph. I have a workng javascript graphing function, but the problem is getting the new graph to replace the old one (or just update it, if that's possible).
Thanks.
If all you are trying to do is update some JS vars, you may be better off having your process.php file returning a json string:
$array = ('percYes' => $yes, 'percNo' => $no);
echo json_encode($array);
This will give you a json string that can be evaluated and used in a callback for your JS ajax call.
So if you have a var 'percYes' and 'percNo' in an accessible scope, your callback could look something like this:
function(jsonstr) {
obj = eval(jsonstr);
percYes = obj.percYes;
percNo = obj.percNo;
}
I hope this helps.
I want javascript to be able to call a php script (which just echos a string) using jQuery.
I think $.get is the right way, but not too sure.
I then want to use the returned string as a javascript variable.
$.get() is the way to go, indeed.
First of all, you will need a page / url that outputs the result of the function you want to use (for example, *www.yoursite.com/test_output.php* ). You should create that page and call the function you want to use there.
Also keep in mind that I said output, not return, because .get will fetch the output of the http response, not the returned value of the php function.
So if you have the following function defined in your site (you can also define it in test_output.php, of course):
<?php
function say_hello() {
return 'hello world';
}
?>
In test_output.php, you will need something like this:
<?php
echo say_hello();
?>
Then on the client side, you need some JavaScript / jQuery:
var data_from_ajax;
$.get('http://www.yoursite.com/test_output.php', function(data) {
data_from_ajax = data;
});
Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.
$.get() is the right way.
$.get('ajax/test.php', function(data) {
// use the result
alert(data);
});
Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);