Get data from HTML and save it as a PHP variable - php

I have started learning php and I have a question.Let's say I have the following html code:
<p id='tobeChanged'>I wil be changed throughout the execution<p>
This paragraph is not static.Its content can be changed from the user with a button which will produce a random number and will replace the paragraphs html.
E.g. from
p id='tobeChanged'>I wil be changed throughout the execution<p>
to
<p id='tobeChanged'>42<p><!--changed with a button-->
Now my question.Is it possible to pass the new produced value to a php variable?If possible i would like a long explanation.
Also i would like not to use forms(if possible).
Thanks In advance

You need to fire an AJAX request on that button click, that will send that value to server making php to read it.
You can do something like this (you need to include jQuery on page):
$.post("/saveVariable.php",{randNum:randomNum},function(data){alert("Data saved successfully");})
At PHP end, you will get the value in
$_POST['randNum']
Maybe that will help.

Related

How can I refresh embedded PHP code from the client side?

Basically, at the click of a button I need to refresh a div that contains embedded PHP. I tried using .html() in jQuery to reload the contents of the div, but it didn't change anything so I'm assuming it's not recalling the PHP (because the PHP should be changed at this point). It's probably just rewriting the HTML that was outputted by the PHP when the page loaded. I also tried appending something to the new HTML load so I could see it was at least refreshing the HTML code, and it was. It looked something like (if "updateObject" is a variable that contains the location of the div):
updateObject.html(updateObject.html() + " random text");
I also fiddled around with the .load() jQuery method, but it seemed to be for external PHP files (and at this point I can't change my embedded PHP to external PHP).
Any thoughts? Thanks!
EDIT: The biggest problem I've had is that, with my limited knowledge of web dev, I need to have the PHP embedded. If I make it a separate file, I'd have a very difficult time finding it because I honestly don't understand how the files get put together through the framework we're using (Drupal). I did try using an external PHP file but I couldn't figure out how to find it. Even if I put it in the same directory as this HTML file, it doesn't seem to be easy to find.
You are to have 2 files:
PHP
This contains the data you want to show.
HTML
This is the one showing the php content.
In PHP you can put whatever you want. But the HTML once is loaded is loaded and the only way to have some more content into it is to make what is called an asynchronous call, which means a call after the page has been loaded.
To do this you are to use jQuery and call the $.post (or $.ajax), using this syntax:
$.post('filename.php', function(dataFromPhp){
//actions to do once the php has been read
})
So in your case you can make a function that reads the php every time the click is done on a div/button/other DOM object; like so:
function updateDivContent(whatDiv){
$.post('filename.php', function(dataFromPhp){
if(dataFromPhp){
$(whatDiv).html(dataFromPhp)
}
})
}
So if you want the div to be refreshed (and reload the php) you are to connect that function to an event and specify the div you want to show the data:
$('#myBtn').click(function(){
updateDivContent('#myDiv');
})
Refer to this documentation for further informations: https://api.jquery.com/jQuery.post/

Make value=null when page first loads

Is it possible to remove a value whilst the page is loading?
I'm using OSClass, and on one of the pages it's by default adding a value for region (cambridshire):
I need to clear this value since it's causing problems, everytime I type something else in, by default, it registers it as Cambridgeshire...
If I look at code for it:
It's being generated by a function (can see my JQuery attempt to clear it which hasn't worked).
Then if I search the function is splits up in many different parts, so I don't know where to go from there.
Basically, is there a way to remove the value when page loads and save the new value when the user submits?
JSFiddle - Note it won't display anything due to the way code is generated
Have you tried removing <?php ItemForm::region_text(); ?> on it's own? Or passing an empty string <?php ItemForm::region_text(''); ?>
I'm not familiar with OSClass though I'm afraid.
Paste this code below the jQuery initialization:
$(document).ready(function(){
$("#region").val('');
})

Find and store all innerhtml of div to php variable

I’m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.

How to append a div via PHP and AJAX Post

Good day. I'm trying to make an online quiz application using php. The idea is that the form will add a text field for the question and four other text fields below it for the answers each with a radio button to determine which one is correct. Then below the form is an add a new question button which would call an ajax post function. The problem is instead of appending to the target div, the php code replaces the contents of the div itself. Is there a way for php to append to the div instead of replace its contents?
PHP is server-side, it can't do anything in the browser, only deliver content.
To add a div, you use Javascript in the page, e.g.
var el = document.getElementById('idoftarget');
el.innerHTML += '<div>new stuff</div>
... I think. I always use jQuery:
$('#idoftarget').append('<div>new stuff</div>');
how are you handling the ajax response? maybe instead (since you don't have code here it's a guess) of
document.getElementById('someDiv').innerHTML=ajaxResponseText;
you want
document.getElementById('someDiv').innerHTML+=ajaxResponseText;
(appending rather than overwriting)
This is the right one:
document.getElementById('exampleDIV').innerHTML+=ajaxResponseText;

strategy to split up php output into smaller outputs (ajax, php) (nested ajax calls, ajax within ajax?)

I don't know the correct terminology to search for the solution. Please suggest a strategy to break up the php output into small chunks and pass them stepwise to ajax's responseText.
The project is an ajax webpage that takes a text string (lastname) and passes it to a php program. The php code takes the last name and randomly fetches 3 people with different first names, and puts it into an array. Once that is done, the php code will contact outside servers to retrieve info associated with each name, and output the info to a div of the webpage. The process of getting data from the outside servers is very slow.
This code is basically done, but the whole process takes a very long time to generate the output on the screen. Is there a way (a strategy) to output each step of the php code immediately instead of having to wait for the complete code?
My pseudo php code is like this:
<?
get 3 names; //output this immediately
foreach name { get phone number }
?>
Alternatively, I could get a name and the phone#, and output it immediately before moving to the next name.
Are there php or ajax codes/functions/strategies that would achieve this? Please suggest solutions or search keywords.
Addition/Edit:
Thanks for the suggestions. Is it possible to execute another ajax call after the parent ajax call? I initially went that route, but my testing of nested js/ajax call did not work. It could be due to syntax errors, please look over the code.
The test code in the testajax.php (or testajax.html) file for the ajax call XHR.responseText is
<div id="name" >JAM <div id="numa" >
<br />
<br />text holder >>
<script type="text/javascript">
var pid=document.getElementById("numa").parentNode.id;
alert (pid);
document.getElementById('numa').innerHTML += 'append text>> ';
document.write(' docwrite');
</script>
</div>
</div>
<br />
<br />ending text
If I view the file testajax.php (or testajax.html) directly, I would see
JAM
text holder >> (an alert window) append text>> docwrite
ending text
but if I do an ajax call of the testajax.php file, all I would see is
JAM
text holder >>
ending text
The code inside the <script> </script> tags does not run after the ajax call
can someone explain this, and offer a fix?
TIA
Without knowing the actual code and code-based answer is hard. But, here's an idea.
When you get the three names, return them to the page and display them. Then, for each one, in a different AJAX call, call the phone info. I'm not positive if javascript will make all three calls independently of each other, but that would at least display all 3 names, and then each phone info one at a time.
Edit
Workflow:
Javascript sends a name to php via ajax.
PHP returns 3 names to js
js appends 3 divs to the page, one with each name.
js makes 3 requests to php, sending 1 name per request.
php returns phone info / whatever else to js
js takes info and adds it to the respective div
In theory, yeah, you can call flush() (and ob_flush() as necessary) to ensure output is sent from PHP.
However, the web server may add buffering of its own outside of the scope of PHP (most commonly, if mod_deflate is in use on Apache); and you'd have to be careful about delimiting your response chunks so they're not read by the browser until a chunk is complete.
In any case not all browsers can read the responseText from an XMLHttpRequest until the request is fully complete. So for it to work on all clients, you'd have to try a different mechanism, such as the old-school HTML-iframe-containing-multiple-<script>s.
Summary: it's a bunch of hassle, and perhaps not really worth it. A simpler-to-deploy possibility would be separate AJAX requests for each name.

Categories