I'm trying to pass an Object to the server with html post. I've already serialized the object and verified that there were no errors in that process. After I hit the submit button I receive a json string with several escape slashes and I don't know why or how I can prevent that from happening. I'm using node.js and the express module.
This is a snippet of the output I get.
{"obj":"{\"nodes\":[{\"id\":0,\"role\":\"sensor\",\"spy\":false,\"correctData\":true,\"port\":8000,\"requiresData\":[],\"connectedTo\":[]},<
HTML:Post
<form action="/result" method="post" enctype="json" autocomplete="off">
<input id="obj" name="obj" required>
<button type="button" name="action" value="getResult"
onclick="generateJSON(true)">generateJSON </button>
<button>Generiere Knoten</button>
</form>
Javascript:
function generateJSON(loaded){
if(loaded) {
var stuff = {nodes: localData, edges: localEdges};
stuff = JSON.stringify(stuff);
console.log("Result?:" + stuff);
$('#obj').val(stuff);
}
}
It should be noted that the json string presented in that input field looks perfectly fine. Snippet:
{"nodes":[{"id":0,"role":"sensor","spy":false,"correctData":true,"port":8000,"requiresData":[],"connectedTo":[]},
I found this answer which helped me initially since I made the same mistake but somehow I'm still missing something.
Edit: Found a solution
I found a way to delete those backslashes and thus got a working json again. Leslie pointed me in the right direction - thanks again. I'm still unsure why this happens in the first place.
myJSONString = myJSONString.replace(/\\/g, "");
Related
I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/
I am just starting with jQuery and I am trying to do a $.post request, but I am getting a post AND a get (see log below). I have searched a lot and only found cases where they were calling an ajax function twice.
My case is a dynamic table of forms where I want to send an ajax POST when a single form is submitted.
Here is my javascript:
$(document).on('submit', 'form.newguess', function (event) {
event.preventDefault();
alert($(this).serialize());
$.post("game", $(this).serialize());
});
Here is my JSP:
...<tbody>
<c:forEach var="player" items="${players}">
<tr>
<td class="namecell"><p>${player.key}</p></td>
<td class="guesscell">
<p>${player.value}</p>
</td>
<td class="inputcell">
<form class="newguess" action="game" method="post">
<input type="text" name="guess" />
<input type="hidden" name="player" value="${player.key}"/>
<input type="submit" value=">"/>
</form>
</td>
</tr>
</c:forEach>
</tbody>
And here is the log from my server:
23:32:41,617 INFO (http-localhost/127.0.0.1:8080-3) POST - Game
23:32:41,696 INFO (http-localhost/127.0.0.1:8080-3) GET - Game
I have tried to remove the $.post and then I don't receive anything, so it is definitely the $.post.
Any ideas are welcome, it must be a very dumb mistake.
Thank you.
I think you can use a normal button instead of
<input type="submit" value=">"/>
use
<input type="button" value=">" onclick="yourFunction"/>
Maybe thats why it is sending two times, one from jquery and another from the DOM (?)
Solved it! I knew it had to be something dumb.
This is my code on the server:
#RequestMapping(value = "/game", method = RequestMethod.POST)
public String postPlayerGuess(#RequestParam("player") String playerName,
#RequestParam("guess") String guess, Model model) {
System.out.println("POST");
gameService.setGuess(myself.getGameName(), playerName, newGuess);
return "redirect:/game";
}
Notice that redirect:/game at the end? yep, that it was. I was redirecting the response, so the client made another GET request.
Sorry guys, you couldn't have solved this one without the code on the server, my bad!
It is due to, you have put your form in loop. So that every first iteration your mentioned form method will post but after that all form will have get request by default.
You need to generate unique "name" for every form . To avoid multiple GET/POST request .
I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}
I had an issue with copying a value from one form to another via JavaScript, which I was able to figure out with help from my previous question here: "How to copy a value from one form's file upload field to another form's text field?"
So, thank you!
But now I have a new issue. When the form field value is copied over, in some browsers (such as IE), the field contains the local path of the field on the user's computer (i.e. "C:\Users\username\Desktop\file.png"), which obviously won't work in the URL.
So: is there a way to filter out everything but the file name itself before it's copied to the new field? Or a way to do it after the fact?
Thanks for the help!
Here is my most recent simplified code for this:
<script>
$(function(){
bindGroups();
});
var bindGroups = function() {
// First copy values
$("input[name='logofile']").val($("input[name='logoname']").val());
// Then bind fields
$("input[name='logoname']").change(function() {
$("input[name='logofile']").val($(this).val());
});
};
</script>
<form action="/current-url" method="post" enctype="multipart/form-data">
<input type="file" name="logoname" value="1" />
<input type="submit" value="Upload" />
</form>
<form name="create_landing_page" action="/landing-page-url/" method="get">
<input type="hidden" name="logofile" />
<input type="submit" value="Generate Landing Page" /></form>
Try using a combination of split() and pop();
var basename = fullFileName.split('\\').pop();
Note the double backslash to escape the slash; this will only fix the problem for Windows browsers, because Linux/OS X uses a slash (/) as directory separator, so might try this (untested as I'm on my iPad at the moment)
var basename = fullFileName;
if (indexof('\\', basename) >= 0) {
basename = basename.split('\\').pop();
}
if (indexof('/', basename) >= 0) {
basename = basename.split('/').pop();
}
Try this:
var field = $(this).val();
var index = field.lastIndexOf("\");
field = field.substr( index, field.length-index );
I finally figured this out, and it was simpler than I had hoped. All I had to do was change the line:
$("input[name='logofile']").val($(this).val());
to:
$("input[name='logofile']").val($(this).val().split('\\').pop());
The problem with using a variable was that I had to refresh it when the upload field changed, which wasn't hard; I refreshed the variable when the upload button was clicked. But for some reason, when I replaced $("input[name='logoname']") with my variable name, the value wouldn't copy over. I couldn't figure it out.
This ended up being much simpler, no variables needed. Split/pop did the job, so thanks everyone who suggested it! You pushed me in the right direction.
I'm driving myself crazy with Ajax at the moment, there is something that im not getting.
I want a user to input their password, then their new password twice, but i want to use Ajax to send that data to a PHP script to check it and to store the new password in the database if needed.
I just don't understand how to get the data from the HTML form to the Ajax script. Everywhere i look on the internet the information just seems to confuse me that little but more, this always seems to be the case when trying to find help with Java related product i feel.
So heres teh Ajax:
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4){
//document.myForm.time.value = ajaxRequest.responseText;
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
var queryString = "?oldpass=" + oldpass + "&newpass=" + newpass + "&newpassretype=" + newpassretype;
ajaxRequest.open("post", "serverTime.php", true);
ajaxRequest.send(queryString); //Would use this to send post data (passwords) to the script
I have missed out all the broswer specific stuff because im sure you've seen it all before.
<form>
<input type="password" name="oldpass" id="oldpass" />
<input type="password" name="newpass" id="newpass" />
<input type="password" name="newpassretype" id="newpassretype" />
<input type="submit" onclick="ajaxFunction('oldpass', 'newpass', 'newpassretype')" name="button2" id="button2" value="Change Password" />
<div id="txtHint"></div></form>
I think i miss something here, but i haven't got a clue what it is! ANy ideas?
thanks for your time and i hope this isn't something silly.
Just change this one line and it will work...
var queryString = "?oldpass=" + document.forms[0]["oldpass"].value +
"&newpass=" + document.forms[0]["newpass"].value +
"&newpassretype=" + document.forms[0]["newpassretype"].value;
2 things though...
You're passing the password and the confirmation in the URL. That's not needed as you should check that they're the same at client side, rather than send them to be checked at server side.
You shouldn't send password information in a URL as it's the easiest thing in the world to capture.
You have hard coded strings that you are passing to ajaxFunction, you need to use DOM to access the form fields and get their values. You also need to run encodeURIComponent over them to make them safe to drop into the query string.