ajax returning php/javascript code - php

I was playing around with AJAX.
If I do
echo "helllo"
in the PHP file it works fine.
However, if I do something like
echo "<script language=Javascript> alert('hi');</script>";
in the PHP file, the alert() does not come up.
Anyone know if I'm doing anything wrong?
example:
in my html file i've got this
<div id='something'> </div>
and i want the response text from the php file be placed above:
if (req.status==200) {
document.getElementById('something').innerHTML=req.responseText;
}
if i changed that to:
if (req.status==200) {
document.getElementById('something').innerHTML="<?php echo 'hi';?>";
}
it works fine, the response text will be ---> hi
but if i do echo "\"<?php echo 'hi';?>\""; in my php file,
the response text will be ""
i hope i was clear in explaining

use $.load() , and the script will be evaluated.
$("#something").load("request.php");
Maybe jQuery there also uses eval() , so it is'nt more safe, but as long as load() only works on the same Domain u should have Control over the things that will be evaluated.
However, it is easier to use, because you did'nt have to parse the Fragment for script's on your own :)

another approach: using eval
var result = ajaxResponseText;// "alert('hi')"; in your case
eval(result);

You must create script tag with returned data;
var script = document.createElement('script');
stript.innerHTML = req.responseText;
document.getElementsByTagName('head')[0].appendChild(script);

Related

Getting a string from PHP using jQuery

Basically, I have a jQuery script which detects when a certain button is pressed. When the button is pressed, the script is meant to make a GET request to a separate PHP file. The PHP file should return a string to the JavaScript file, but I have multiple errors in both my scripts, creating a problem.
<script type="text/javascript">
$(document).ready(function() {
$('#generate').click(function(){
$.get("give.php?data").done(function(info){
console.log(info);
});
});
});
</script>
When logging info, I get nothing. Literally, nothing.
<?php
$f_contents = file("combo.txt");
$line = $f_contents[array_rand($f_contents)];
$data = $line;
$_GET['data']
?>
That's my PHP script.
If someone can help me out, I would appreciate it. None of the posts on the internet helped me out.
Thanks!
Oh and yes, I know my code is terrible.
Network Tab
No, you're code is not terrible
You need to know the difference between $_GET['data'] and echoing out variable called $data .. If you know its Ok
To solve your problem you need to
Directly access the php file in the browser something like http://localhost/give.php and play with the php file to get the result printed out .. you may need to check the combo.txt file directory it may ./combo.txt or something else
Then copy the fullurl like http://localhost/give.php then paste it to $.get(fullurl....
Some notes
You've to echo out the data in your php file echo $_GET['data'] or echo $data to echo the file content data
With $.get you can use $.get('url' , {} , function(response){ console.log(response); });

ajax data passing to php not working

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(){});

Update JavaScript variables in background using PHP + jQuery

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.

Include javascript variable inside php tags

i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.

PHP Javascript variable help

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);

Categories