Creating a CMS and I want to create buttons for user to style the page.
//customize.php
<body class = "body">
<input type = "color" name = "bgColor" id = "bgColor">
<button onclick = "changeColor()">Change Color</button>
</body>
I'm parsing my css in php so I can update the css through ajax.
//style.js
function changeColor(){
var request = new XMLHttpRequest();
var getbgColor = document.getElementById("bgColor").value;
request.onreadystatechange = function(){
if(request.status == 200 && request.readyState == 4){
//I want to send $mycolor back to the client side so user can see
//how their page would look like
var asx = request.responseText;
document.body.style.backgroundColor = asx;
}
};
request.open("GET","mode.php?theColor=" + getbgColor,true);
request.send();
Parsing css in php
//mode.php
<?php
header("Content-type: text/css; charset: UTF-8;");
$mycolor = (isset($_GET['theColor'])) ? $_GET['theColor']: false;
?>
.body{
background-color: <?php echo $mycolor; ?>;
}
I have another file call showPage.php that will have the style manufactured from the customize.php file, but I can't get it to work. What I keep getting is false from $mycolor. Can't seem to figure out what I'm doing wrong. I haven't taught myself jQuery yet, so if you assist, please no jQuery. (thanks for the assistance)
Related
I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}
I want to send a section of html content (not a form data) through AJAX.
I know how to do this in jQuery but i want to achieve with javascript.
HTML (I want to send content who has id=stack)
after clicking on SEND button button, response must be loaded in id=target
<div id='stack'>
<ol>
<li>stack 1</li>
<li>stack 2</li>
<li>stack 3</li>
</ol>
</div>
<button id='btn'>SEND</button>
<article id='target'></article>
AJAX
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(main);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
print_r($div);
?>
After running my above code it is just displaying Array()
because Ajax method is not sending the div.
Please help me using Javascript instead of jQuery
Do not send the element reference itself, get the outerHTML property and send that one like so: xhr.send(main.outerHTML);
This sends a string version of the element including its descendants.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
okay guys !
I asked the above question and finally successfully solved my problem.
So I am going to share my solution with you (love).
SOLUTION :
AJAX
There is one line of code i missed in ajax.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
So the full Ajax code will be -
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
//*****new line added
var data = 'key' + '=' + main.outerHTML;
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
//*****(new line added) must add when working with POST data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(data);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
echo $div['key'];
?>
Thank You !
Also, how do i unset the session through javascript?
I have made this code with PHP:
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_POST['excel_array']['Main']['Plan1'] = array();
}
else{
$_SESSION['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_SESSION['excel_array']['Main']['Plan1'] = array();
}
So here i check if there is a session. If there is, i unset it and send the $_POST data instead. however, if there isn't one, i create it.
The problem is, i might want to call this on a button click. How would i make a code with the same functionality, but using a javascript function?
Put your php in a file on its own, called set_session.php for example:
<?php
session_start();
unset($_SESSION['Plan1']);
echo 'unset';
?>
Call it in javascript:
<script>
function unset() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "set_session.php", true);
xhttp.send();
}
</script>
<button type="button" onclick="unset()">Unset</button>
<div id="result"></div>
I saw the "likes" function in this demo blog and I'm trying to create a similar button. It seems that once hovering over this heart button, there will be a "finish" class added to the div containing it, so there must be a JavaScript that counts each like. I'd like to make it store each like per visitor (not more) on mouse click and remember it when reloading the page (so I guess there should be a cookie as well?).
It's done with ajax which store data to DB without page refresh and updates the value +1 at the same time
index.html (HTML File)
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<button id="btn">Like</button>
</body>
</html>
script.js (Javascript File)
window.onload = function(){
document.getElementById('btn').addEventListener("click",
function(){
sendLike();
document.getElementById("btn").disabled = true;
});
}
function sendLike(){
var xhr;
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else xhr = new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET","like_counter.php?like=1",true);
if (xhr.readyState == 4 && xhr.status == 200) {
//handle what you want to do after the operation is completed here
}
xhr.send();
}
like_counter.php (PHP File)
<?php
if(!(isset($_GET['like'])&&$_GET['like']==1)){
die("Access denied!");
}
//This is just a demo. On a more practical situation,
//you would want to store the likes in a database and verify the authenticity
//of the request to prevent Cross-Site-Request-Forgery
session_start();
if(!isset$_SESSION['likes']) $_SESSION['likes'] = 0;
$_SESSION['likes'] += 1;
echo "done";
?>
I have 3 files linked together index.php functions.js and compute.php
index.php has a div that calls a function in functions.js: compute() that sends an AJAX request to do something in compute.php
index.php:
<form id = "input_form">
<textarea name = "row" id = "inputform" placeholder="Input row here"></textarea>
<input type = "submit" value = "Enter" onclick="compute(inputform.value);">
</form>
<div id = "output_container">
<p id = "output"></p>
</div>
When the button is pressed, compute() is called passing in whatever was in the textarea as data.
function compute(row){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
output.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","compute.php?row="+row,true);
xhttp.send(null);
}
This passes the value into a php script which simply is suppose to output what was in the textarea into #output
<?php
$str = $_GET['row'];
echo $str;
?>
When I test my program by clicking the button, nothing happens indicating something went wrong. I tried to pinpoint the problem by adding a window.alert('something'); after the check if(xhttp.readyState == 4) but a popup box never appears, making it seem like the issue is between functions and compute.
I tested out phpinfo(); and it looks like php is working properly on my server as well
Problem: Form is getting submitted without making ajax call, because your code contains type='submit'
Solution: Change type to button:
<input type = "button" value = "Enter" onclick="compute(inputform.value);">
Also update code to fetch the output properly:
if (xhttp.readyState == 4) {
document.getElementById("output").innerHTML = xhttp.responseText;
}