I have a form where I upload a file through an ajax call containing an API call.
If the API is successful I want to update a table containing the list of files.
I was thinking of calling a javascript function inside the ajax page, but what I get back is that the function in undefined, I fixed that by putting clarifications.js before the javascript function.
Here is the form (at the top of the page I included the js file containing the javascript function):
<div class='input_table_title'>Upload file:</div>
<div style='float:left;'>
<form name='upload_my_files' action='ajax/clarifications/handle_upload.php' method='post' enctype='multipart/form-data' target='upload_target'>
<input type='file' name='file_upload' />
<input type='hidden' name='notification_id' value='<?php echo $value->NotifiNumber; ?>' />
<input type='submit' value='Upload'>
</form>
<iframe id='upload_target' name='upload_target' src='' style='width:0;height:0;border:0px solid #fff;'></iframe>
</div>
in handle_upload.php I make the API call and at the end of the page I close the php, put the clarification.js and calling the function.
<script src="(position)/clarifications.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
createTable("<?php echo $outcome ?>", "<?php echo $uploaded_filename ?>");
</script>
in the clarifications.js file I declare the function (as I said earlier I included the js file in the form page):
function createTable (result, filename) {
if (result == 'success'){
var success = document.getElementById('clarification_success');
success.style.display = "block";
success.innnerHTML = "File "+filename+" successfully uploaded.";
// Update the list of uploads
var list = document.getElementById('table_clarification');
var myElement = document.createElement("td");
myElement.innerHTML = filename;
list.appendChild(myElement);
}
return true;
}
clarification_success is a div where I want to display a success message.
table_clarification is the id of the table where I want to add the row with filename uploaded
The upload is successful but the function createTable is not defined. Edit: Solved
The other problem that I'm having is that the function can't find the id "clarification_success", I think because is looking for it in the instead of the normal page. Am I correct? If yes how can I solve it?
Note: I'm afraid I can't use jQuery, only Javascript please.
if i understood right - the iframe content should be the separate page. this page is dynamicaly constructed on server and returned to client as a post answer.
this page should probably contain <script src="(path)/clarifications.js"></script> in the header
Related
To put it simply, I tried to make a website where the user can make an element, and then put it in a div element with the id "box". The js script works perfectly fine, and p elements can be created.
And then, I made a php script where it saves the innerHTML of the "box" div and then save it in a .txt file.
Now, the problem is, the script returns the innerHTML value as the original value, before p elements were added in there.
Here's my php script:
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
I'd suppose the question is already pretty clear. Which is how to get the CURRENT value instead of the ORIGINAL one.
Here's the entire code if it helps:
<html>
<head>
<script>
//The javascript function to add a "para" into a div with the id "box"
function addstuff() {
var parag = document.createElement("P"); // Create a <button> element
var t = document.createTextNode("Lorem Ipsum"); // Create a text node
parag.appendChild(t);
document.getElementById("box").appendChild(parag);
}
</script>
</head>
<body>
<!--Button to call the funtion-->
<button onclick="addstuff()">Add it</button>
<!--The form for the button to work-->
<form action="" method="post">
<!--The div to put the "para"s in. The style only adds borders-->
<div id="box" style="border: 2px solid black;">
<!--A pre-existing paragraph-->
<p>This was here before</p>
</div>
<!--The button to call the php-->
<input type="submit" name="use_button" value="Store in file" style="width:100%;" />
</form>
<!--The PHP-->
<?php
//Basically a function
if(isset($_POST["use_button"]))
{
//Loads the file, which is named test.php
$dom= new DOMDocument();
$dom->loadHTMLfile("test.php");
//Gets the innerhtml value
$div = $dom->getElementById("box")->nodeValue;
//Writes it down in a file.
$file = fopen("stuff.txt","w");
fwrite($file,$div);
fclose($file);
//Just for fast-checking if the code has any errors or not
echo "File saved.";
}
?>
</body>
</html>
This is not possible:
PHP generates HTML which is then send to the browser.
The browser executes javascript in the page.
There is no PHP in the browser! and server can't know about anything the user does in the browser!!
you can do an AJAX calls with javascript to send data to the server.
Please refer to this answer: https://stackoverflow.com/a/6009208/1275832
You seem to be confused on how <form> element's work. Just adding HTML code to a form client side does not send that HTML code as form data to the server upon form submission. Nor does it automatically update some PHP file.
You would need to add the HTML code to some input control (input, textarea, etc) that is part of the <form>. Then that input's value will be sent to the server on submission at which point you can then use that sent data.
So on the client side you could have a hidden input that will hold the html that is to be sent. Updating it every time you need to change the html
HTML
<form action="" method="post">
<input id="boxinput" type="hidden" name="boxinput"/>
<!--- Rest of form -->
</form>
JS
//cache these so you don't need to call getByElementById every call
var box = document.getElementById("box");
var boxinput = document.getElementById('boxinput');
function addstuff() {
var parag = document.createElement("P");
var t = document.createTextNode("Lorem Ipsum");
parag.appendChild(t);
box.appendChild(parag);
//update the input field
boxinput.value = box.innerHTML;
}
And then on server side, get the input data from the $_POST global and use it as needed
if(isset($_POST["use_button"])) {
$boxHtml = $_POST['boxinput'];
//..
fwrite($file,$boxHtml);
//..
}
Obligatory note: if you are going to be using this saved html in some way, eg echoing it back on some new page, you should sanitize it before saving/using it. Or only showing it in a sandboxed frame (kinda like how Stack Overflow has sandboxed its Stack Snippets)
This is not possible.
But you can handle it manually by using query parameters that are same in php and javascript
Generate your page elements by query parameters.
For example when you got test.php?div=box generate a page that contains a <div id='box'>
There is so many solutions like this
I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?
this code is in page1 i have to send this variables to page2 where
i can get this variables using post method i have tried many to do but its so tough to it
calls();
function calls(){
function calls(){
var l="<?php echo $abc ; ?>";
var u="<?php echo $cdf ; ?>";
var ajax = ajaxObj("POST", "page2.php");
ajax.send("u="+u+"&l="+l);
}
this ajax variables have to be sent to page2 on page load automatically
If you are loading page two anyway why not just use a form submit
<input type ="hidden" value="$abc" name="l" />
Then just pick it up on page two
$_POST['l']
I am searching for a simple solution to call a PHP function only when a-tag is clicked.
PHP:
function removeday() { ... }
HTML:
Delete
UPDATE: the html and PHP code are in the same PHP file
First, understand that you have three languages working together:
PHP: It only runs by the server and responds to requests like clicking on a link (GET) or submitting a form (POST).
HTML & JavaScript: It only runs in someone's browser (excluding NodeJS).
I'm assuming your file looks something like:
<!DOCTYPE HTML>
<html>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</html>
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST), this is how you have to run a PHP function even though they're in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page, you can make a request to PHP without refreshing via a method called Asynchronous JavaScript and XML (AJAX).
That is something you can look up on YouTube though. Just search "jquery ajax"
I recommend Laravel to anyone new to start off right: http://laravel.com/
In javascript, make an ajax function,
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
Then call from html,
Delete
And in your ajax.php,
if($_POST['action'] == 'call_this') {
// call removeday() here
}
It can be done and with rather simple php
if this is your button
<input type="submit" name="submit>
and this is your php code
if(isset($_POST["submit"])) { php code here }
the code get's called when submit get's posted which happens when the button is clicked.
You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
http://api.jquery.com/jQuery.ajax/
Solution without page reload
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
Delete
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>
Here´s an alternative with AJAX but no jQuery, just regular JavaScript:
Add this to first/main php page, where you want to call the action from, but change it from a potential a tag (hyperlink) to a button element, so it does not get clicked by any bots or malicious apps (or whatever).
<head>
<script>
// function invoking ajax with pure javascript, no jquery required.
function myFunction(value_myfunction) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML += this.responseText;
// note '+=', adds result to the existing paragraph, remove the '+' to replace.
}
};
xmlhttp.open("GET", "ajax-php-page.php?sendValue=" + value_myfunction, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php $sendingValue = "thevalue"; // value to send to ajax php page. ?>
<!-- using button instead of hyperlink (a) -->
<button type="button" onclick="value_myfunction('<?php echo $sendingValue; ?>');">Click to send value</button>
<h4>Responses from ajax-php-page.php:</h4>
<p id="results"></p> <!-- the ajax javascript enters returned GET values here -->
</body>
When the button is clicked, onclick uses the the head´s javascript function to send $sendingValue via ajax to another php-page, like many examples before this one. The other page, ajax-php-page.php, checks for the GET value and returns with print_r:
<?php
$incoming = $_GET['sendValue'];
if( isset( $incoming ) ) {
print_r("ajax-php-page.php recieved this: " . "$incoming" . "<br>");
} else {
print_r("The request didn´t pass correctly through the GET...");
}
?>
The response from print_r is then returned and displayed with
document.getElementById("results").innerHTML += this.responseText;
The += populates and adds to existing html elements, removing the + just updates and replaces the existing contents of the html p element "results".
Try to do something like this:
<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Click Me!
This is the easiest possible way. If form is posted via post, do php function. Note that if you want to perform function asynchronously (without the need to reload the page), then you'll need AJAX.
<form method="post">
<button name="test">test</button>
</form>
<?php
if(isset($_POST['test'])){
//do php stuff
}
?>
Try this it will work fine.
This will work without form tags and button tag.
<div onclick="window.location='?hello=true';">
<?php
if(isset($_GET['hello'])) {
hello();
}
function hello()
{
echo "hello world";
}
?>
I have a file called index.jsp which is where a user is directed to upon loading my website.
I want to send a get request to one of my servlets upon loading the page.
So my URL at the beginning is:
localhost:8080/Test/
The servlet will do something when the URL is:
localhost:8080/Test/MyServlet?action=fetchdata
I can get the servlet to perform fetchdata if in the html body i put this:
<form name="fetchdata" action="MyServlet" method="get">
<input type='hidden' name='action' value='fetchdata' />
</form>
and then run a script:
<script type="text/javascript">
document.fetchdata.submit();
var testresult = '${result}';
document.write(testresult);
</script>
However this does not look nice and it is also in the HTML body which seems very unprofessional. So I tried implementing the same function in JQuery by putting this in
the HTML head:
window.onload = function() {
$.get("MyServlet", { action : "fetchdata"});
};
and nothing happens when I load the page. I have tested to see that jQuery is working. Any idea on what is wrong? Thanks
Try this instead:
$("form[name='fetchdata']").trigger('submit');