I'm using this web service that prints out table using Javascript functions. I need the table to print out in plain html. This could be done if the Javascript string was transferred to a PHP file. So basically, this is similar to AJAX, but it is in reverse.
You could do that with ajax also
var value = 'This is a test';
if ($(value).val() != 0) {
$.post("jquery2php.php", {
variable:value
}, function(data) {
if (data != "") {
alert('We sent Jquery string to PHP : ' + data);
}
});
}
Important thing here is we are using $.post, so we are can gather the information with $_POST
We are sending only 1 value, named variable.
PHP part;
<?php
$jqueryVariable = $_POST['variable'];
echo $jqueryVariable;
?>
I believe, this is the most elegant way to achieve what you want.
not necessarily reverse, You could pass the string as a URL variable (www.yoursite.com/?string=yourvariable) and have PHP process it from there.
I've quoted a ugly method down here But i dont recommend this..
Instead store values in hidden fields in forms and access them through js or do something else..
<?php
echo "<script type=text/javascript>var x = $value; </script>";
?>
then use the variable x in js..
Anyway if you explain ur situation a bit clearer, we can give u best alternate solution
what you should do is use jQuery's .load() to load in the php's html results into the page
in the docs i've linked above they give this example
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
EDIT
in response to your comment on Pixeler's post. You will not be able to just view the source of a ajax based solution. if your ultimate goal is to be able to read the source you have basically three options
send them to a new page
load in an iframe
do it the way you have, use fire fox and web devloper addon which will allow you to view generated source. (or something similar)
I'm not sure why there is a need to see the source users don't really care about the source typically the developer uses that
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(){});
Greeting, fellow programmers,
I have a problem.... keep in mind that I'm completely self-taught, so this may be a stupid question, but I've done hours of research and no one seems to have had the same problem..
I'm working on a php project and I need to be able to perform and ajax GET request, but then store the response as a string variable and perform some string methods on it. Is this possible? And if so, how do I do it.
Thanks in advance.
PS: I've been using JQuery's .load() method to perform GET's and POST's.
The following could be a better approach than using the .load function if you have to use it for other things than just interacting with the DOM.
$.get("from-page.php", function(data) {
var manipulated = data.substring(data.length, Math.ceil(data.length / 2));
//any kind of manipulations you want
$("#div").html(manipulated);
});
I'm not sure if you read the docs but it's in here
Look for Example: Display a notice if the Ajax request encounters an error.
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
response should contain the string you want to manipulate.
I have an ajax function and while caling that function the php code will execute and check if any rows with the given data is present in the table. If there is no data I would like to display an alert. right now I can display a div with the error message but I could not get the out put such as
echo "<script> alert('error'); </script>";
You can not stick JavaScript on the page using innerHTML since it will not be evaluated. What you would need to do is parse out the JavaScript code and shove it into eval(). OR use a framework that does it for you like jQuery.
It is better to develop a framework on the client that does not rely on this eval. A better messaging system would work.
{ "alert" : "Your alert message", "html" : " the mark up " }
Basic JavaScript idea:
//get the responseText
var result = xhr.responseText;
var json = JSON.parse(result); //This line is not cross browser for older browsers
if(json.alert){
alert(json.alert);
}
if(json.html){
document.getElementById("out").innerHTML = html;
}
i want to have function like delete file from database by using link instead of button. how can i do that? do i need to use href/unlink or what?
Can i do like popup confirmation wther yes or no. i know how to do that, but where should i put the code?
this is the part how where system will display all filename and do direct upload. Beside each files, there will be a function for 'Remove':
$qry = "SELECT * FROM table1 a, table2 b
WHERE b.id = '".$rs[id]."' AND a.ptkid = '".$rs[id]."' ";
$sql = get_records_sql($qry);
foreach($sql as $rs){ ?>
<?echo ''. basename($rs->faillampiran).'';
?><td><?echo ' [Remove]';?></td><?
?><br>
<? }
?>
thankz all
The elegant way of doing this would be to use both PHP and JavaScript. PHP is a server-side language, and should probably be removed as much as possible from the client side stuff. One great way to do it would be to essentially create yourself an API.
The API would be a PHP script that deletes a row. It takes a variable in via GET and returns a boolean that says "yes we deleted the row" or "something went wrong." I like to use JSON, which in JavaScript is easier to work with than XML, and jQuery's getJSON function, a package that makes it really easy to get going.
In the .php file (we call it api.php later), if your results are successful return out success boolean. We use PHP's json_encode on an array, and echo out the result:
$variable = someFunctonToSanitize($_REQUEST['idToDelete']);
$query_to_run = "delete query using $variable";
$result = mysql_query($query_to_run);
// set headers
header('Content-type: text/json');
header('Content-type: application/json');
// if the query was successful, echo true
if($result) {
echo json_encode(array("success"=>"true"));
} else { // else echo false
echo json_encode(array("success"=>"false"));
}
In your JavaScript, here using jQuery (this is discouraged, see comments below):
$('#deleteLink').click(function(event) {
// prevent link from actually going anywhere
event.preventDefault();
// Fire off API request
$.getJSON("api.php?idToDelete=whatever", function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
});
});
With a .post() request, per #Col. Shrapnel and #josh3736's comments (note: also changed $_GET to $_REQUEST to work with both):
$.post("api.php", { "idToDelete": "whatever" },
function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
}, "json");
In your HTML:
Delete!
No links nor buttons can be used for the database interaction. It is server-side code to do such things. You have to understand that your application has 3 layers:
an HTML form
an server-side code
a database
the first one cannot interact with the last one directly.
So, on the one hand, it doesn't matter, with link or button you do call your server side code (the code remains the same).
But, on the other hand, there is a rule:
use GET method (link) to request information and POST (form/button) to modify it.
So, you should not use links to remove files, because some too smart bot can wipe all your database in a second.
As for your question where to place the code, just write a php script, unlink.php which deletes a file by hardcoded path. Then, after you've done that, make this file an action for the HTML form. Hardcoded one. Once you've done that - you can try to generate this form from your database.
This - step-by-step way - is the only possible way to develop a wab-application
Make a link:
Delete
Then make a delete.php that handles deleting and make sure you check that the session is authorised.
In PHP you use unlink() to delete a file. If you provide a page which accepts the file name (or better yet, file Id) as a parameter you can call unlink() on the file. Obviously there are some serious security implications which you will need to account for.
For confirm Delete, use this in onclick function()
In a href tag, itself :
<a href="" onclick="return ConfirmDelete();" ></a>
In upper Page use javascript like this,
function ConfirmDelete() {
var confm = window.confirm("Are you sure want to delete this !");
if(confm == true) {
return true;
} else {
return false;
}
}
For delete option give the same page link and pass the parameter and get the parameter by get function
<a href='samepagename?deleteid='.<?php echo $id;?>
In get parameter use like this,
$deleteid = $_GET["deleteid"];
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.