I have a page that started with an empty PHP var. Then, when the user clicks on a link I want to pass the value of the name attribute to a JS var, and then pass that JS var to the same page and then update the PHP var with the JS var value. Here is a simple example of what I am trying to do:
// PHP
<?php
// Starts empty, then when posted should update
$jsVar = $_POST['jsVar'];
echo $jsVar;
?>
<!-- HTML-->
<!-- Link to click with name vlue to pull-->
Click Me
<!-- JAVASCRIPT -->
<!-- Import jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
// On link click
$('a').click(function(e){
// Prevent link default behavior
e.preventDefault();
// Store name vale as jsVar
jsVar = $(this).attr("name");
$.ajax({
type: "POST",
// url: "" <--------------- From what I read, if you want to post to the same page you just don't inclue the URL?
data: {jsVar : jsVar}, // <--------- This was also something I found online that supposedly helps pass JS vars to PHP?
success: function(data)
{
alert("success!");
}
});
});
</script>
A lot of people say that I don't need AJAX for this. The example I provided is a much similar version of what I am trying to do, which is dynamically change an include file based on the user clicking a sidebar item. I don't want to use a form for this, do I?
Ah! As I continued to look, I found that jQuery has the .load() function which is EXACTLY what I wanted. Dang! I was able to build this and make it work:
// Store clicked page
var currentPage = $(this).attr("name");
// Build filepath
var currentPagePath = "pages/" + currentPage + ".php";
// Find the div I want to change the include for and update it
$("#pageContent").load(currentPagePath);
So easy. Dang. Thanks all.
Related
So I am trying to get this code to echo my popup when class elements are clicked. I have the code in the head section of my wordpress file but it's not working. Any ideas?
I've even tried moving the variable around and still nothing
<?php
function popCash() {
$doit = "<script type='text/javascript'>
var wid = '111111';
var uid = '111111';
</script>
<script type='text/javascript' src='//cdn.popcash.net/pop.js'></script>";
echo $doit;
}
?>
<script type='text/javascript'>
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
var <?php echo popCash;?>
});
});
</script>
I need it to show the popup when the class elements are clicked
Depending on what kind of result you want, you need to use console.log(popCash) or alert(popCash), not echo, which is not valid JavaScript.
Follow-up after comment:
If you're trying to execute that script, it's more like document.write(popCash) that you'd be looking for, but this wouldn't be a very efficient way to accomplish what you're trying to do because you'd be loading up that script every single time you got a click, and accumulating additional <script> elements with every click.
For one thing, it looks like you're assigning values to global variables wid and uid using a script. There's absolutely no good reason to create a new script just to do that. Simply assign the variable directly:
<script type='text/javascript'>
var wid;
var uid;
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
wid = '111111';
uid = '111111';
var popCash = "<script type='text/javascript' src='//cdn.popcash.net/pop.js'>\n"+
"<\/script>";
document.write(popCash);
});
});
</script>
But then the question becomes: "Why reload the 'cdn.popcash.net' for every click?"
Isn't there a method inside the script that can be called whenever it needs to be invoked again?
And even if the script is so poorly written that it must be run from the top for every invocation (that's a terrible API!), you can at least dynamically create and delete script tags to do the job instead of using document.write(), but that would take a bit more explaining to describe.
I am trying to place the following <script> tag within a featherlight.js modal window however it's just displaying as plain text.
I need to be able to perform an ajax request on a form within the featherlight.js window.
<script type="text/javascript">
$('#customerOrderNoteAdd').on('submit',function(e){
e.preventDefault();
var formData = $(this).serializeArray();
var formURL = $(this).attr('action');
$.post(formURL,formData,function(data){
data = $.parseJSON(data);
if(data.success){
alert("Sent");
}
});
});
</script>
The <script> tag doesn't need to be "in" the dialog. Moreover, you're not mentionning which content filter you are using.
Anyways, you could make your binding generic ($(document).on('submit', '#customerOrderNoteAdd', ...) and run it once on startup, or else run your script in an afterContent callback.
To a lot of my php files i append a html and a javascript part, which modify and enhance the displayed data in a table. Because the html and js/jquery part is always the same, i wanted to make a global header file, that i'd include in my php file like this:
include("parts/head.html");
Head.html contains several jquery js files, css files and my own js, which calls the jquery plugins and applies it to certain ids or classes in the main table:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<script type="text/javascript" src="js/defaulttable.js"></script>
<link rel="icon" href="images/favicon.ico">
<body>test test
</body>
</html>
Now, everything works fine apart from one function - a function wherein you insert comments via a little textbox into the DB. Extraction from my .js file:
//function to insert textarea
function insertTextarea() {
if ($(this).parents("tr").find("td:eq(0)").text() == 1) {
var boardInfo = $("<form id='boardComment'><textarea placeholder='Notizen? Fragen? Kommentare?' rows='2' cols='27'></textarea>Privat:<input type='checkbox' name='privatecheckbox' id='privatecheckbox'/>Reminder:<input type='checkbox' name='remindercheckbox' id='remindercheckbox' checked/><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
} else {
var boardInfo = $("<form id='boardComment'><textarea placeholder='Notizen? Fragen? Kommentare?' rows='2' cols='27'></textarea>Privat:<input type='checkbox' name='privatecheckbox' id='privatecheckbox'/>Reminder:<input type='checkbox' name='remindercheckbox' id='remindercheckbox'/><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
}
console.log('this', $(this).parents("tr").find("td:eq(0)").text());
$(this).parent().append(boardInfo);
$("tbody img").hide();
$("textarea").focus();
$("#boardComment").on("submit", function(event) {
event.preventDefault();
var change_id = {};
change_id['id'] = $(this).parent().attr("id");
change_id['comment'] = $(this).find("textarea").val();
change_id['privatecheckbox'] = $("input[name='privatecheckbox']", this).is(':checked') ? 1 : 0;
// get remindercheckbox
change_id['remindercheckbox'] = $("input[name='remindercheckbox']", this).is(':checked') ? 1 : 0;
$.ajax({
type: "POST",
url: "boardinfo2private.php",
cache: false,
data: change_id,
success: function(response2) {
alert("Your comment has been saved!");
$("tbody img").show();
$("#" + change_id['id']).find("form").remove();
if (change_id['remindercheckbox'] == 1) {
console.log("rem checkbox 1");
$("#" + change_id['id']).parent().addClass("Reminds");
$("#" + change_id['id']).parent().find("td:eq(0)").html(1);
} else if ($("#" + change_id['id']).parent().hasClass("Reminds")) {
$("#" + change_id['id']).parent().removeClass("Reminds");
$("#" + change_id['id']).parent().find("td:eq(0)").html(0);
}
}
});
return false;
});
The variable change_id is sufficiently defined earlier and works perfectly, when i put everything in a single php file - html, script and php.
What happens is, that when i hit submit, the page reloads completely and the variables are stored in the URL without having been inserted in the DB.
The other function calls i do in my js file are AJAX Posts on external php files aswell and they work fine. They don't insert anything new into the DB tho.
I'd be endlessly thankful if someone can help me with this..
I desperately want to improve my coding and thought global files would be a good start, so i don't have to change every single file if i want to add something to the JS..
you want to improve by global isnt a good idea ... because global things have always issue and you should call this function on
$(document).ready(function(){
call it here
})
also including javascript in head isnt good idea either
As I understand, your issue is that the page is reloading when the form is submitted, and you just want it to happen asynchronously. If that is the issue, I would add a return false at the end of the ("submit", function(event) { function. Hope this answers your question.
I'm using similar functions with php and instead of using a post function to reload the page I am intercepting form submit requests and then use jquery get or load functions to accomplish the same thing without ever refreshing or reloading the page.
$( "#formsubmit" ).click(function(e)
{
//stop grid submission from reloading page or going anywhere
e.preventDefault();
//get variables
var passVar = encodeURIComponent($("#var").val());
//pass to insert to db page, get response
$.get('adddata.php?var=' + passVar,
function(data)
{
var getResult = data;
//do something, including update page if incessary
}
);
});
I was able to solve the issue via
$(document).on('submit', 'form#boardComment', function(event){
instead of
$("#boardComment").on( "submit", function( event ) {
I have a code set up where I use JS and PHP to write to a file and display the output to a html element (in this case a textarea). I have a huge problem about how to go about this. I know that PHP is executed before anything else happens. I use php to echo the file content using my own javascript function
output(string) // this outputs whatever into the html element text area
PHP:
<?php echo "output('".$someText."');"; ?>
Now my problem comes around when I update and add contents to that file, but the php has already been executed and trying to read from the file again, will only display results from the last time it executed the php. The only way around this is to refresh the page, thus 'rebuilding' the html content of the file.
This whole code of mine mimics the look and feel of a command line ( you have an output screen with an input box) How can i dynamically display the contents of a file as new content is being added to the file without having to refresh the window. Refreshing the window will work, but not at all what i need for this to work. Any help with this?
For more information about how my code is structured, below you will find a snippet of how the code executes:
// main.php
<?php
// displays the file into the output box
function displayFile($fileName){
$file_handler = fopen($fileName, "r");
while (!feof($file_handler)){
$line = fgets($file_handler);
$line = formatFileLine($line);
echo "output('".$line."');";
}
fclose($file_handler);
}
?>
switch(splitCmd[1]){
case 'permitted':
output('\nWells that have been permitted:\n');
<?php displayFile('permitted.txt'); ?> //calls the php function to display content.
break;
case 'drilled':
output('\nWells that have been drilled:\n');
<?php displayFile('drilled.txt'); ?>
break;
default:
output('Wrong syntax: show <permitted, drilled>');
}
You can do this with an AJAX request, there are multiple ways to do this, but the easiest is with jQuery (opinion based ofcourse!), here is a link to the documentation. jQuery AJAX
Example:
function ajaxCall(){
$.ajax({ url: 'PHPFILE.php',
success: function(e){
//e is what you get returned from the php file
$('#div').html(e);
}
});
}
Oh, and you should ofcourse have the jquery library linked. which you do this way:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You need to make an AJAX call to your PHP file. Take the output from the PHP script, and embed this into, say, a given div on your page.
Let's pretend you have a div set aside for display. Let's give you a button to refresh it whenever.
<div id="resultdiv"></div>
<input type = "button" id="rbutton" value="Click to Refresh">
Style it any way that you please.
Now, let's set up an AJAX call to load the results from the PHP.
<script type="text/javascript">
$(function() { //document ready psuedonym
function refreshdata(){
$.ajax({
type: "POST",
url: "my_data_script.php",
dataType: 'html',
data: {myparam1: 'abc', myparam2: '123'}, //these are optional parameters in case your PHP script needs them
success: function(data){
$('#resultdiv').html(data);
},
error: function(){
},
complete: function(){
}
}); //end ajax
} //end function
$("#rbutton").click(function() { //clicking the button refreshes the data on demand
refreshdata();
});
refreshdata(); //this will run the function when the page loads
});//end document ready pseudonym
</script>
I have a PHP page with a lot of includes which make up various parts of the page for a video website.
I have a comments section which submits information into a database (Which works fine). But I need to make it so when this is done only the included page/div refreshes.
This is the PHP:
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?php $showComments?>
</div>
Here is my attempt at doing it with Javascript:
<script>
var $comments = $("#player-song-comments");
setInterval(function () {
$comments.load("/template/sections/player_comments.php #player-song-comments");
}, 30000);
</script>
This should reload just the comments section but instead, everything from this point onwards goes blank.
How it looks now when I press submit:
When I reload that page manually:
I don't want the whole page to refresh because it contains a video.
How can I make just that Refresh after submit is pressed OR every 30 seconds?
UPDATE:
I have tried using JQuery to execute this. I'm getting an error:
Fatal error: Call to a member function query() on a non-object in /home/content/58/12052758/html/template/sections/header.php on line 42
<script>
/*wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
alert("Thank you for your comment!");
});
}); */ //THIS IS LINE 42
$(document).ready(function() {
var options = {
url: 'template/sections/player_comments',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
$("#player-song-comments").load('template/sections/player_comments.php');
alert("Thank you for your comment! The site is currently in maintenance and the comment won't show until you revisit this video");
});
});
});
</script>
For those interested. Here is the whole page: http://pastebin.com/c0kQ3tGp
You seems to load comments in PHP and as far as I know, PHP is only parsed once.
The simplest workaround I know is to use an iframe that you would refresh, but I'm not sure this is a good practice tho.
So there are two parts to your question:
How can I make just that Refresh after submit is pressed
You can use jquery-form for that. In your case, you can initialize your form to something like this:
$(document).ready(function() {
var options = {
url: 'your_form_action',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
There are many other options you can play with.
OR every 30 seconds?
Try change your
$comments.load("/template/sections/player_comments.php #player-song-comments");
to
$comments.load("/template/sections/player_comments.php"); // remove the selector
According to the docs, the selector is used to insert fragments of the remote document. In other words, when load was executed, jQuery parses the returned document to find the element #player-song-comments. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.... I assume #player-song-comments is not part of your response?