Passing a Variable with Ajax and Javascript - javascript

I have advanced ASP (classic) skills but am pretty green to JavaScript and Ajax. I'm working on a page that allows users to enter comments in response to a post. I'm wanting the form submission field to submit reader comments to the database, and then show those comments without changing the page. Much like a Facebook comment. Hence Ajax and JavaScript.
I've got the test.asp page (below) working. It's calling the AJAX.asp page, writing to the database, and updating a in the page with the submitted text. My only issue is that I am going to need to update a page with multiple sections, so I need to get a variable into the second JavaScript function to allow me to write to a unique . Currently it's set as id="newcomment" but this will need to change to something like id="newcomment" & var, so that the result is "newcomment1484" (or another unique number) and the right gets updated.
For the life of me I can't figure out how to get a variable in that second function. Any help greatly appreciated. Please keep in mind I'm quite new to JS.
<html>
<head>
<script>
function SendtoAjax(ident)
{
if(window.XMLHttpRequest)
{
oRequest = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
oRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
oRequest.open("POST", "AJAX.asp", true);
oRequest.onreadystatechange = UpdateComment;
val=document.getElementById('commentfield').value.replace(/\n/g, "<br>");
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.send("strCmd=availability&commentaid=" + ident + "&commentfield=" + encodeURIComponent(val));
}
function UpdateComment(ident)
{
if(oRequest.readyState == 4)
{
if(oRequest.status == 200)
{
document.getElementById("newcomment").innerHTML = oRequest.responseText;
}
else
{
document.getElementById("newcomment").innerHTML = "Asychronous Error";
}
}
}
</script>
</head>
<body>
<form method="post" action="javascript:void(0);" name="form1">
<textarea name="commentfield" id="commentfield"></textarea>
<input id="commentaid" type="hidden" value="Available1434">
<input id="submitcomment" type="button" value="submit" onClick="SendtoAjax(1434);">
<br><br><div id="newcomment"></div>
</form>
</body>
</html>
I tried all manners of getting a variable in there, but have come to learn (I think?) that there is some issue with the "onreadystatechange" and Ajax. Way beyond me at the moment.

you need to pass a formData object, see the docs for examples on how to do that.
let formData = new FormData();
// append some data (key, value)
formData.append("strCmd", "availability");
// send it with the form
oRequest.send(formData);

Related

Sending data between two php functions using ajax

I am currently working on user verification on the website. What I am trying to do is to ask the user to input the credentials and push the "send confirmation" button, then send the code to the user using something (SMS or messenger) and make the user insert this code into the field and click "confirm" to check if it is correct. The Issue that I am facing right now is how do I pass the correct code from one PHP function (which I currently call using ajax) to the other. For obvious reasons of security I can't just send the code through JavaScript, but you are welcome to prove me wrong :) . Here is the HTML that I have:
<button type="button" onclick="send_sms()">Send verification</button><br>
Code from the SMS: <input type="text" id="fi" value=""><br>
<p id="res"></p>
<button type="button" onclick="check_sms()">Check</button>
<script>
function check_sms() {
jQuery.post(
ajax_object.ajax_url,
{action: "confirm_sms",
code: document.getElementById("fi").value
},
function( response ) {
// showing the result of confirmation
document.getElementById("res").textContent = response;
}
);
}
function send_sms() {
jQuery.post(
ajax_object.ajax_url,
{action: "send_sms",
phone: document.getElementById("phone").value
},
function( response ) {
// temporarely showing the code in console (shold not be there 🤫)
console.log("not an sms, but the code for now is " + response);
}
);
}
</script>
Now, in functions.php I have:
add_action( 'wp_ajax_confirm_sms', 'confirm_sms' );
function confirm_sms() {
$code = $_POST['code'];
// yes, I know that it will not output anything after, but it is beside the point anyway.
// and yes, I will not send the real code as the output of the function (just for testing)
wp_send_json($_SESSION['real_sms_code']);
if ($code != $_SESSION['real_sms_code']) {
wp_send_json('The code is not correct, please, try again');
return;
}
wp_send_json("Nice code, awesome balls!");
}
add_action( 'wp_ajax_send_sms', 'send_sms' );
function send_sms() {
// my attempt at storing the code, not the same session as I suspected, but was worth a try
$_SESSION['real_sms_code'] = strval(rand(100000, 999999));
wp_send_json($_SESSION['real_sms_code']);
}
The issue here is that the confirm_sms function always outputs 'None' (It should be the code set by the other function) and I can't figure out how to fix that. I was thinking about just creating a file containing this code, but
a) It is unreliable
b) I can't (reliably) identify which user the code belongs to since this is before they are registered
c) This may be slow with many users
There is got to be a better way of handling this.
So I have figured out the issue: I have copied the $_SESSION part from somewhere, but the guy there never mentioned that you have to use session_start(); before the functions in PHP. Now it works flawlessly. Kinda frustrating that I have lost a day because of someone not posting the whole code, please don't be like that :)

Using a href with Post within a list

I am looking for a solution after trying all different option for 5 hours . I am not a big HTML or Javascript person but I tried.
I have a List coming from the Database which is listings of services. Each Service gets their own unique ID. At the moment I send the ID via the URL but this is not preferable,
Within each list element I have a Picture and button and a link using the persons name.
I tried to use javascript to take the value from a value in the href line and sent that to the url which worked but it seems like the server saw that as a different session and hence the webpage did not display the full editable listing,
This was the script
<script>
function myFunction(test) {
var url = "/portal/vendorlistingsadd";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send(test);
}
</script>
then did
</div>
other problems I had was due to the same 'name' been on each row in the list, I could not extract the correct one.
So basically the only way I can see it working is to send the data via url .
If anyone has any suggestion I would try each one
Thank you
****UPDATE
<form action="/portal/vendorlistingsadd/editlisting" method="post">
</form>
and the second line
<button class= "btn-lg" name ='${serviclist.listing_id}' type = "submit"> <img src="${serviclist.picture}"/> </button>

How do you pass a Javascript variable through POST to use in Flask?

So I have a JS variable that is created after pressing a button, and I need to pass it to my app to process in flask. I'm currently trying to do it with query strings but I'm not really sure what I'm doing.
In the html I have a form set up like this:
<form action="/deleteBook" method="POST" onsubmit="deleteBook()">
<input type="submit" value="Delete" />
</form>
which calls this function to apply query string:
function deleteBook() {
var existingUrl = window.location.href;
window.location.href = existingUrl + '?itemID=' + itemToRemove;
};
and then I want to process that variable through flask:
#app.route('/deleteBook', methods=["POST"])
def deleteBook():
if(request.method == "POST"):
itemID = request.args.get('itemID')
In my mind the code should detect the form submission (basically single button click), call deleteBook() which should then append a query string to the URL which can then be processed in flask.
I'm aware that I'm lacking some basic knowledge about html/js/processing data so I'm not really sure where to go from here. Should I use PHP to process the request somehow? Or should I not be using a form at all? Or maybe in flask there is an easier way to get data without using POST? I'm not sure so any suggestions are appreciated, thanks!
Well I for one find your style for a question like this unique so I'll try my best to explain my idea of the answer.
Firstly, I would just have the form calling the function
Secondly, I would have the function call an 'XMLHttpRequest' with 'POST' configuration
The HTML
<form onsubmit="deleteBook()">
<input type="submit" value="Delete " />
</form>
The JavaScript
function deleteBook () {
var xhr = new XMLHttpRequest();
xhr.open('POST', existingUrl + '?itemID=' + itemToRemove, true); //The second argument is the url you wish to 'POST' to
xhr.send(); //if you want to do something if your flask returns something, 'xhd.onload = function () {}'
}

How to post javascript boolean result back to server

On the html page of a custom built shopping cart, I need to be able to send a post back to our server to tell it whether or not cookies are enabled.
I have the appropriate javascript on the page to detect cookies enabled/disabled (via navigator.cookieEnabled), which does nothing if it detects cookies enabled, and posts a message if they’re not enabled. I need to go beyond just posting a message.
I don’t want the user to be able to click the purchase button, the html for which (along with the cart itself, and all the items the cart contains) is generated by our database software on our server (using associated cookie ID to generate the cart on the website).
I can not figure out how to get the boolean value (enabled/true or disabled/false) out of the javascript and post that info (true or false) back to our server, where I can detect an incoming connection from the website.
Very much a novice where it comes to JS, so go easy on me!
Thanks in advance for any input you can give me, or point me in a direction…
Here is followup based on answers received:
On the cart page (which is displayed when user hits a “Buy This” button elsewhere on the site, to purchase something) is this JS:
<div id="demo"></div>
<script>
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
} else {
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>
So, there is a true/false value generated within the JS. Then, to build the cart, as the html page loads, I send a call to our web server, via this (which is part of the html code on the same page as the above JS):
"4DHTML vCart"
(this is enclosed within comment tags, although it is not a comment. I couldn't put it within comment tags in this edit, because it got ignored). It is picked up by a method called “On Web Connection” in our web server software, which is written in 4th Dimension (it’s basically 4D code embedded in the html, and the comment tags are part of the protocol).
The 4D code then builds the cart and sends it (the cart page) back to the website as an html file.
So… when the call is picked up by the OWC method, I can detect incoming vars from the html cart page, which come in in arrays, and can parse those values. The problem is, the boolean values I want are in the JS and I don’t know how to represent them outside of the JS.
Thank you for your time and consideration on this.
It sounds like you are trying to do an AJAX post back to the server. Try something like this:
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
//PERFORM ANY ADDITIONAL ACTIONS AFTER A SUCCESSFUL POST HERE...
} else {
alert('An error occurred. Please try again.');
}
}
}
var xyz = "";
xyz = "Cookies Enabled: " + navigator.cookieEnabled;
document.getElementById("demo").innerHTML = xyz;
if (navigator.cookieEnabled) {
xyz = "";
request.open('POST', 'http://yourpostbackurl.com/enabled');
request.send();
} else {
request.open('POST', 'http://yourpostbackurl.com/disabled');
request.send();
xyz = "Cookies seem to be disabled in your browser.";
}
document.getElementById("demo").innerHTML = xyz;
</script>

Submit to external form with "action:javascript" using javascript

I have a form on one page (one.html) that has a javascript funtion as its submit action:
<form id="the_form" action="javascript:myfunc('input_text');" method="post">
<input type="text" id="input_text" name="input_text">
<input type="submit">
</form>
I have another page (two.html) with a button that when clicked I would like to submit the form on one.html, along with a value for input_text. Is this possible with ajax or any other way for that matter? If possible, I would also like to redirect to the page I submit the form too although this is optional.
this code should be on second form:
$(document).ready(function(){
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
if(QueryString.preview){
console.log(QueryString.preview);
}
});
this sample read query and parse.
So, first you can send your form as GET, like http://asd.com/?param1=a&param2=b
and then just use QueryString.param1 and QueryString.param2 in your another page.
Based on the comment under this post, I'm asuming you want to send it info from pageA to a php file that returns a resulting file:
download file using an ajax request
How to download file from server using jQuery AJAX and Spring MVC 3
Downloading file though AJAX POST
Based on the comments under your question, I'm assuming you want to post from pageA to new page (pageB) with javascript.
Quick answer: Not possible (in a userfriendly way).
More useful answer:
It requires a bit more work, but based on the info given, this might work:
Submit the form from pageA via either GET or POST to pageB
Create hidden fields (<input type="hidden"/>) and fill those with the corresponding GET or POST values. This might be easier with a serverside language like PHP, but isn't impossible in JS
Set a hidden input and name it like <input type="hidden" id="linkedSubmit" value="1" />
Create some javascript to see if $('#linkedSubmit').val()==1, if so continue to submit the form on pageB
This isn't the prettiest solution and on a slow connection the user will see page hopping. And because it is javascript it's clientside, thus a user can manually change the value to 1 and trick your page. This should not become a security problem.

Categories