How do I change a HTML class via PHP? - javascript

I'm currently stuck at my "Newsletter Subscribe Form". I use MailChimp to send my newsletters and have managed to redirect the visitor of my page to a custom PHP file after entering the email.
The process goes like this:
User enter email
Email silently (user doesn't see it) gets added to the MailChimp Database (Email List)
Instant redirection to a self hosted PHP script.
4. The PHP Script changes the color of the button via a CSS Class in the HTML file.
I'm stuck right at Point 4, since I don't really know how to change a CSS Class in a HTML file with PHP. It's important that the webpage still remains in HTML (otherwise i'd use a simple variable in PHP).
Do I need to parse the PHP value to AJAX or JSON which then changes the class (probably with jquery?)
If yes, could you give me an example on how to do it? I have never really used JSON or AJAX before.
Thank you guys very much :)

It's a little bit difficult to understand the question completely.
If you're trying to output a class when the page loads, that's very easy using php:
<?php
$classVariable = "myClass";
?>
<div id="someID" class="<?php echo $classVariable; ?>">Some content</div>
PHP loads once, before anything else on the page, and never runs again. You can call other scripts using AJAX which can then return data that you can use. For example (using jquery)
<script type="text/javascript">
$.get("path-to-myscript.php", function(response){
// read the response in, perhaps you grab some class name from it
// for demo purposes, lets say this response is in json formatted as a simple string:
// '{ "class" : "someClass" }'
var data = $.parseJSON(response);
var newClass = data.class;
$("#someID").attr("class", newClass);
});
</script>

Related

How do I pass an email into the site tracking Javascript code?

does anyone here have any idea how to set up Site Tracking by passing a contact's email address into Javascript Code?
I am on Wordpress using the visual builder Elementor's native contact form.
Here's the contact form: https://www.bestseo.sg/free-report/ (Bottom of the page)
I have already inserted ActiveCampaign's site tracking code sitewide.
However, it does not seem to start site tracking even after the form submission.
According to ActiveCampaign's documentation(https://help.activecampaign.com/hc/en-us/articles/221542267-An-overview-of-Site-Tracking#how-to-pass-a-contact-s-email-address-into-javascript-code), I believe I have to add this line of code:
vgo('setEmail', 'Email_Address_Goes_Here');
above
vgo('process');
But I have no idea what to replace 'Email_Address_Goes_Here' with, in order to call the actual contact's email after form submission.
Any help would be much appreciated!
Thank you.
So the plugin used to insert these JavaScript codes is https://wordpress.org/plugins/header-and-footer-scripts/ - I’d suggest to maybe just keep using that, and keep the scripts in the footer, so that this does not require too much modication.
Inside your template, you have to output the email addresse somewhere, where the JS can read it from - via a custom data attribute added to the body element for example.
The header.php of your theme should contain something similar to
<body <?php body_class(); ?>>
Modify that, to add a custom data attribute to store the email address entered in the from:
<body <?php body_class(); ?> data-freereportemail="<?php echo !empty($_POST['form_fields']['email']) ? esc_attr($_POST['form_fields']['email']) : ''; ?>">
If the POST parameter by that name is set, then it will be output as content of this attribute, otherwise it’ll simply stay empty.
Then modify the JavaScript code you insert via the plugin like this,
var freereportemail = $('body').attr('data-freereportemail');
if( freereportemail != '' ) {
vgo( 'setEmail', freereportemail );
}
This assumes that jQuery has already been loaded at this point, but I think that should most likely be the case.
If the attribute contained an email address, then this will execute the vgo tracker function, if the attribute value is empty, then it will simply skip this call.
This is not the most sophisticated approach, but it should do.
(Only if you had other forms on the site as well, that use a form field of that exact same name, you might be tracking more than intended. In that case, you’d need to find some additional criterion, to be able to differentiate between these different forms.)
A person at the AC support gave me thsi code :
jQuery('form').submit(function() {
var userEmail = jQuery("form input[type='email']").val();
vgo('setEmail', userEmail);
vgo('process');
});
I hope it'll help you.
I use FluentForms, so i just went on the form specific Custom JS/CSS to apply it (so i had no problems of proper targeting...)

Hiding Password field content from users

I'd like to know if its possible for me to do something from the following :
1) Replace the source code visible in view source , with an image , or nothing at all.
2) Hide the value attribute of <inpt type="password" ....> tag , so that the password entered by the user is not visible to anyone .
Thanks in advance.
You can minify your HTML to make it slightly unreadable, but it's trivial to unminify it. You can't do anything further to "remove" or "hide" it.
You mean to hide the value attribute after the user types something in, or to hide the value sent from the server? If the former, you could use JavaScript to extract the value as it's typed into some variable and replace the value with gibberish. If the latter, then the obvious answer is to not send that value.
View source is a representation of static HTML, so if you create any element dynamically, it will not be displayed in view source.
Note: These fields will still be accessible using dev tools.
Following is a sample code:
JSFiddle
function submit() {
var uName = document.getElementById("txtUserName").value;
var uPass = document.getElementById("txtUserPass").value;
console.log(uName, uPass);
}
function addPasswordField() {
var passInput = "<input type='password' id='txtUserPass' />";
document.getElementById("content").innerHTML += passInput;
}
(function() {
addPasswordField();
})()
<div id="content">
<input type="text" id="txtUserName">
</div>
<button onclick="submit()">submit</button>
There is no way to hide source code in a browser since that is how these things are built. The web is an open platform and developers working with the web need to have the view source functionality while working on their project(s). May I ask why you feel the need to hide the source code and the password?
To answer the first question: No. This is how browsers are designed and there are lots of other ways to request the page to see the source. For example, you could use Fiddler to see the traffic passing between the server and the browser.
As for the second question...why are you trying to hide the password?
Using the password input type will prevent anyone from seeing the password on the screen. so I assume this is to stop the data being viewed in transit?
If you want to secure your connection between the client and the server, you should consider using a secure (https) connection. Thanks to LetsEncrypt this is free, so it is no longer a costly option.

go back to dynamically created form

i have a form that is created from a textfile. I fill the form with values and then on the next step i just show the values with text. But if any of the values is wrong and i want to change it i would like to be able to go back and change them. But as it is now i can't because then i need to do all the steps again and generate the form again. Is there a way to just go back to the previous page?
now i use
$(document).on("click", "#btnBackO", function () {
window.location = "/Home/RiskScore";
});
but this does obviously not work. This code just sends me back to nothing because the form is not generated before it tries to go to the page. Is there a way to go back to a cached page of something?
I am pretty sure you would be required to be using some kind of server side language or javascript for this. Reason being is because the only way to "save state" is by passing the values back and forth. So when you hit back it's not like you are just going back to your last state, your essentially reloading the page.
Your code:
$(document).on("click", "#btnBackO", function () {
window.location = "/Home/RiskScore";
});
would change to something like:
$(document).on("click", "#btnBackO", function () {
window.location = "/Home/RiskScore?field1=value1&field2=value2"; //etc.. etc..
});
your page that holds the orginal form would have to be at bare minimum an HTML file that can support javascript tags. Preferable doing something server side via PHP:
VERY SIMPLIFIED EXAMPLE: (things like error catching, and escaping special characters are not addressed here)
<?php
$field1 = $_GET['field1'];
?>
<input type='text' value='<?php echo $field1; ?>' />
Any web language will be capable to accomplish this.
Sources:
How to get the query string by javascript?
http://php.net/manual/en/reserved.variables.get.php
If you want to go back to previous page :
history.go(-1)
history.back() or history.back(-1)
should work as well

PHP/Javascript passing message to another page

So let me explain:
I basically want so when you post a comment, (i use a js/jquery script to send string to insert.php which inserts to the database) you will receive 2+ points. Now i have done so you get +2 points, BUT i want to display a message like stackoverflow. I already know how to display a message like stackoverflow, but in somehow i need to send from insert.php(after you inserted), this:
<div id='message' onclick="closeNotice()" style="display: none;">
Hey, <b><? echo $pusername; ?></b> - You've just got +<? echo $gpm; ?> points for your comment!
X
</div>
to index.php..
I was thinking of maybe coding into my current script(that are sending string to insert.php) that it should find #message and throw it in #box (div called "box" in index.php).
But how should i do this? Should i like, after you got through insert.php, then you activate a function in javascript that does:
function showmessage() {
$("#box").html(data).find("#message").fadeIn("slow")
}
and as i said you activate the script doing:
<script type="text/javascript" language="javascript">
showmessage();
</script>
after you succesfully have inserted to database and gived points to the user?
Ive just tested this, and i cant get it to work.
my site is integrated with sessions from the phpBB login (phpBB forum i've got), so i don't think i can use $_SESSION.
And the insert.php is opened in a frame.
My problem is that the action, and the displaying of the confirmation take place on different pages.
If I understand you correctly, your problem is that the action, and the displaying of the confirmation take place on different pages.
One approach to do this is to store the message that is to be displayed on the next page in the user's session:
// insert.php
$_SESSION["user_message"] = "You were awarded +2 points.";
and output it on the following page:
// thankyou.php
echo $_SESSION["user_message"]; // Or show the box, or whatever
$_SESSION["user_message"] = null; // Clean up
the potential downside to this is that if the user has two or more pages/tabs of your site open, and navigates a lot across them, the message may appear in the wrong context. For example, if I click "save" in tab A, and refresh tab B, it could happen that the message intended for tab A is displayed in tab B.
You could help that by adding a randomly generated key to the message's variable name, and passing that key on to the page you want to display the message on:
// insert.php
$key = "123456"; // Insert random generation method here, e.g. using rand()
$_SESSION["user_message_$key"] = "You were awarded +2 points.";
header ("Location: thankyou.php?message=$key"); // Pass the key to the next page
// thankyou.php
$key = $_GET["message"]; // No sanitation necessary here AFAICS
echo $_SESSION["user_message_$key"]; // Or show the box, or whatever
$_SESSION["user_message_$key"] = null; // Clean up
This is very elegant because
the message you want to display remains in your internal session store, and at no point is passed on in the browser, reducing the risk of security holes and such.
by unsetting the session variable, you make sure the message is shown only once, even if the user reloads the page.
If insert.php is being opened by the page that needs to display the mesage, you can use window.opener to access the originating page. I think something like this might work:
window.opener.$("#message").html($("#box").html()).fadeIn("slow");
I'm not sure if I understand correctly, but if the user makes the input in a field on index.php, then maybe you could send it to insert.php with an ajax request, and use the callback of the ajax to display the notice to the user?

Non-AJAX jQuery POST request

I am trying to use the jQuery POST function but it is handling the request in AJAX style. I mean it's not actually going to the page I am telling it to go.
$("#see_comments").click(function() {
$.post(
"comments.php",
{aid: imgnum},
function (data) {
}
);
});
This function should go to comments.php page with the aid value in hand. It's posting fine but not redirecting to comments.php.
#Doug Neiner Clarification:
I have 15 links (images). I click on a link and it loads my JavaScript. The script knows what imgnum I opened. This imgnum I want in the comments.php. I have to use this JavaScript and no other means can do the trick. The JavaScript is mandatory
Your method successfully POSTs the aid value. But in the comments.php when I try to echo that value, it displays nothing.
I am using Firebug. In the Console, it shows the echo REQUEST I made in Step (2) successfully.
I know what you are trying to do, but its not what you want.
First, unless you are changing data on the server, don't use a POST request. Just have #see_comments be a normal <a href='/comments.php?aid=1'>...
If you have to use POST, then do this to get the page to follow your call:
$("#see_comments").click(function() {
$('<form action="comments.php" method="POST">' +
'<input type="hidden" name="aid" value="' + imgnum + '">' +
'</form>').submit();
});
How this would actually work.
First $.post is only an AJAX method and cannot be used to do a traditional form submit like you are describing. So, to be able to post a value and navigate to the new page, we need to simulate a form post.
So the flow is as follows:
You click on the image, and your JS code gets the imgnum
Next, someone clicks on #see_comments
We create a temporary form with the imgnum value in it as a hidden field
We submit that form, which posts the value and loads the comments.php page
Your comments.php page will have access to the posted variable (i.e. in PHP it would be $_POST['aid'])
$("#see_comments").click(function () {
$('<form action="comments.php" method="POST"/>')
.append($('<input type="hidden" name="aid">').val(imgnum))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
});
While the solution by Doug Neiner is not only correct but also the most comprehensively explained one, it has one big problem: it seems to only work at Chrome.
I fidgeted around for a while trying to determine a workaround, and then stumbled upon the second answer by devside. The only difference is the extra code appendTo($(document.body)). Then I tested it in firefox and it worked like a charm. Apparently, Firefox and IE need to have the temporary form attached somewhere in the DOM Body.
I had to do this implementation for a Symfony2 project, since the path generator inside the .twig templates would only work with GET parameters and messing with the query string was breaking havoc with the security of the app. (BTW, if anyone knows a way to get .twig templates to call pages with POST parameters, please let me know in the comments).
i think what you're asking is to get to 'comments.php' and posting aid with value imgnum. The only way to do this is to submit this value with a form.
However, you can make this form hidden, and submit it on an arbitrary click somewhere with jquery.
html necessary (put anywhere on page):
<form id='see_comments_form' action='comments.php' action='POST'>
<input id='see_comments_aid' type='hidden' name='aid' value=''>
</form>
js necessary:
$("#see_comments").click(function(){
$('#see_comments_aid').val(imgnum);
$('#see_comments_form').submit();
);
this will redirect to 'comments.php' and send the proper value imgnum (that i assume you are getting from somewhere else).
Actually, $.post() sends some data to the server. It does not cause any redirection unless you do it in your server side code which handles the POST request. I can suggest two solutions:
To go to comment page, instead of using JQuery post, you can simply use a 'anchor' tag - Show Comments.
Or if you are want to go through JQuery, you can use this code snippet: $(location).attr("href", "comments.php?aid=1");
didnt exactly solve the problem. but did manage to work around it. i had to do a lot modification to the JS to make this work, but the core problem of this question was solved by doing this:
$("#see_comments").attr({href: "comments.php?aid='"+imgnum+"'"});
this appended the aid value to the URL as #Doug Neiner initially suggested me to do.
Thanks a lot Doug for all the effort. I really appreciate. +1 and accept to your answer for the effort.

Categories