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 .
Related
this question is pretty common question, but just can't get any way around it for a long time...please help if you can figure out where I am going wrong
I have a form returning a string like this:
<form id="details" name="details" method="post">
<input class="myButton" style="margin-top:300px; margin-left:320px; text-align: center;" type="submit" value="Save" onclick="return getstring()">
</input>
</form>
<script>
function getstring() {
....
....
return "abcd";
}
</script>
Now, in my flask code:
def process_details():
if request.method == 'GET':
return render_template('page1.html')
else:
returned_details = request.form['details']
print(returned_details)
But when I debug this, during the 'POST' request, it enters correctly in process_details function, but it can't populate the returned_details variable. The return string is not a dictionary, any idea how to return in this case to flask?
in other words, I just need a button inside a form which collects the data from the page and submits when pressed(I get that data on onClick). In flask part so that, when I do request.form['details'], i should get that value.
Thank you
I think the problem is in form in html page.As you want to run the else part of code when we make a POST request but there is no form which is sending us to that code after submitting.So in short add this in your form;
<form action="{{ url_for ('process_details') }}">...</form>
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, "");
I've got this research.php file that should show the content of a database table, taking the informations for the query from a javascript form.
I made in javascript the form and disabled the enter key, so that only by hitting the button you can submit the value. The value of the components in the form should be used to make the query. Can I pass the value to a php variable in the same file?
<!DOCTYPE html>
<html>
<head>
<!--
Implemented by Argese Alessandro and Rosso Kevin
The slider is taken from "https://dhtmlx.com/docs/products/dhtmlxSlider/samples/index.html"
Download slider: "https://dhtmlx.com/docs/products/dhtmlxSlider/"
-->
<title>Ricerca diplomati</title>
(...) <!--slider things-->
<style>
(...)
</style>
<script>
var mySlider;
function doOnLoad(){ //slider load
(...)
};
function doOnUnload(){ //slider unload
(...)
};
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
if (event.keyCode == 13) {
// prevent default behaviour
event.preventDefault();
return false;
}
});
function interact(form){
(...) //here the value is put in js variables, for a test
});
</script>
</head>
<body onload="doOnLoad();" onunload="doOnUnload();">
<form id="filters" name="filters" action="#" enctype="text/plain">
<table cellspacing="0" cellpadding="0" border="0" class="filters_table">
<tr>
<td>Specializzazione:</td>
<td>
<select name="specialization" class="table">
<option selected value="0">Tutte le specializzazioni</option>
<option>Chimica</option>
<option>Elettrotecnica</option>
<option>Informatica</option>
<option>Meccanica</option>
</select>
</td>
<td></td>
<td></td>
<td>Valutazione finale:</td>
<td><div id="sliderObj"></div></td>
<td><span id="sliderLink"></span><span class="minussign">-</span><span id="sliderLink2"></span></td>
<td></td>
<td></td>
<td>Città :</td>
<td><input type="text" name="city" size="35" maxlength="40" value=""></td>
<td></td>
<td><input type="button" onclick="interact(filters)" value="search" style="background: url(res/magnifying-glass-16x.png); background-repeat: no-repeat; background-position:center; background-color: #0c84e4;width:24px; height:24px;"></td>
</tr>
</table>
</form>
<?php
function viewTable(){
echo "Here the table will be shown";
}
?>
</body>
</html>
In this code the button click just call the interact function, that show an alert window with the value of the variables.
I tried to use ajax but, as far as I understood, it would open a new file.
I've also seen a solved answer in which someone suggested to use the cookies, but that solution really disgusted me.
The most helpful thing I found is here:
How do i store select value into a php variable,
but the POST method refresh the page and the slider crushes.
If you want to pass a variable from JS to PHP you are going to want to use AJAX, it allows you to send and receive info from server running the PHP script.
Your Javascript:
var infobeingsent = "test";
$.ajax({
type: "POST",
url: 'YOURPHPFILE.php',
data: { testVAR : infobeingsent },
success: function(data)
{
alert("data has been sent");
var recievedvar = data;
}
});
Your php file:
if(isset($_POST['testVAR']))
{
$recievedvar = $_POST['testVAR'];
echo "Hey, ive recieved your request";
}
Using AJAX means that your browser never has to come into direct contact with the php file and there's no interruption from the end-users perspective
I think you are a bit confused about the whole work flow between php (server side) and js (client side). OR may be I got your question wrong. But here is a hint on how you can approach this.
You have a server side running php - Great.
You have an html page with js - Awesome.
In the html page, you have a form that you want to run a query based on the user submission:
AJAX is the way. You can do it with pure javascript or a plugin like jquery. On the php side, you can even keep a small, seperate script just to handle this request, run the query and generate the result. Use "onSubmit" for the form to invoke ajax.
I have a method Processsots which I am trying to invoke from submit button, But when I diasble by OnClick element. it is not calling the method. Any one help me how to call the method after disabling the submit button as well
<table>
<tr>
<td width=150> </td>
<td width="1999">
<h1 ALIGN='Left'>Please click on the Button to process Sots feed file</h1>
<form name="sotstestorderfoler" >
<br>
<input type="submit" name="username" value="Process Feed File" onclick="this.disabled='disabled';>
</form>
</td>
</tr>
</table>
<%
if ( request.getParameter("username") != null ) {
Processsots();
}
%>
(Code tried with onsubmit)
<form name="sotstestorderfoler" method="post" onsubmit="foo()" >
<script type="text/javascript">
function foo() {
sotstestorderfoler.username.disabled=true; <%Processsots();%> return true;
}
</script>
</form>
I would use the onsubmit of the form to disable your button, like these answers illustrate:
https://stackoverflow.com/a/12944611/2047962
https://stackoverflow.com/a/19696817/2047962
Realize that JSP code is server-side and JavaScript is client-side, so they can't directly interact with each other.
You are mixing JSP code and JavaScript. The JSP code is only executed on the server. When your browser requests your webpage, JSP code is executed in order to build your webpage. That means that it starts writing out things like <script type="text/javascript"> and function foo() into a stream to send back to the browser. When it reaches <%Processsots();%>, it doesn't simply write out that text, it calls your method Processsots(). It will then write out the return value of Processots(). This means that your method is already executed before users even see your page or try to push the submit button.
This is a mistake that many new JSP programmers make; your JSP code cannot be executed while your JavaScript is executing. The only way for JavaScript code to interact with JSP code is via HTTP requests, usually in the form of an AJAX call or a form submit.
Instead of trying to call a JSP method in the JavaScript, you must have the form submit to a Servlet that can then call Processsots() and return the result as an HTTP response.
So a follow up to this question: getting bad request from ruby on rails ssl post.
I fixed that problem and I make the next step in the transaction no problem. The problem I am facing is that their response is sent to an iFrame as a hidden form on an html document. The form then posts to a url that I provide them.
I have tried giving them localhost:3000/policies/complete making a controller action and a route resource for the post but it doesn't ever show anything.
- It just says javascript error unable to load resource: localhost:3000/policies/complete
So then I tried just /policies/complete (with the coresponding method in my policies controller complete) but for some reason instead of posting to that action - it posted to theirwebserver.com/policies/complete which obviously doesn't exist.
So since it looks like I have to pass in a whole url for it to work correctly the form is going to look like: <form method='Post' action='whatever whole url I give them'>
The form looks like this:
<form name="frmReturn" method="Post" action="localhost:3000/policies/hosted_checkout_complete">
<input name="PaymentID" type="hidden" value="the value you need really badly!">
<input name="ReturnCode" type="hidden" value="0">
<input name="ReturnMessage" type="hidden" value="Your transaction has been approved.">
</form>
Tl:DC How do I set up my app to handle that?
I can request that they use get to send the information back to me. If that would be easier to set up and accept please let me know!
You need to add the protocol (either http:// or https://) to the front of the action=
<form name="frmReturn" method="Post" action="http://localhost:3000/policies/hosted_checkout_complete">
However, I would NOT recommend doing this... You have completely missed the point of Rails routing. You should be doing something like this:
<form name="frmReturn" method="Post" action="<%= resource_url %>">
Ideally, you'd use the Rails form builders:
<%= form_for :resource, :action => 'hosted_checkout_complete' do %>