hidden form field not submitting - javascript

I am submitting a form which has a hidden field. This hidden field is being populated by the server right when the previous page is submitted and the current one loads. So below is the code where I am populating it.
$('form').on('submit', function () {
$.ajax({
type:"post",
url: "/connect",
dataType:"json",
data:$(this).serialize(),
success: function(response){
$('#template_request').val(JSON.stringify(response.template_request),null,2).trigger('change');
console.log($('#template_request').val()); // this logs correctly
},
error: function(response){
console.log(response);
}
});
});
I log the value in the console and it works fine. But when I submit the form, my server gets an empty value.
Relevant snippet from my HTML
<form>
<input class="span2" type="hidden" id="template_request" name="template_request">
.......
</form>
Relevant Python code
req = self.get_argument('template_request')
print "Template Request"
print req

Related

How to submit a form and get some text in return using Ajax

This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})

Console log on click event with textbox

I know this is probably a duplicate question. I am trying to use the value of a textbox and just show it in my console.log. It appears for a second and disappears.
Here is my HTML form
<form>
<input type ="text" id="search" name="search" placeholder="Search..." size="45" required>
<input type ="submit" value="GO" id="submit">
</form>
Here is my JavaScript
$(function(){
$("#submit").on("click", function(){
var t = document.getElementById("search").value;
console.log(t);
});
});
For future context, I am trying to use that information to plug it into the wikipedia API.
var wikipediaURL = "https://en.wikipedia.org//w/api.php?action=opensearch&search="+ t +"&format=json&callback=?";
$.ajax({
url: wikipediaURL,
type:'GET',
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function(data, status, jqXR){
console.log(data);
},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("fail");
})
.always(function() {
console.log("complete");
});
Reason you see it for a moment in your console and then it's disappear is you are using submit button inside your form and whenever you click submit button it will by default submit the form and refresh the page if target is same page unless you stop form submission.
In order to avoid form submission try this.
$(function(){
$("#submit").on("click", function(){
var t = document.getElementById("search").value;
console.log(t);
e.preventDefault(); // this will also do the trick and avoid form submission.
return false; // return statement is included just as safety measure as this will make sure form is not submitted.
});
});

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

Keep old returned Ajax data in div instead of overwriting

I am using ajax to update a section of my website, it is all working great at the moment and updating a div with the response data I get back.
However, at the moment it is just replacing the text in the div everytime I keep submitting the ajax form, what I want is for the data to stay and just keep adding on underneath with the data returned from the ajax request. Here is the code
Html
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
<br /><br /><br /><div id="testarea" style="width: 200px; height: 100px; background-color: #9f1717; color: #fff;"></div>
Jquery
$(document).ready(function() {
$("#foo").submit(function() {
var url = "new_shout_ajax_test.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#foo").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
$('#testarea').text(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
});
Code in the new_shout_ajax_test.php
$bar = $_POST['bar'];
echo $bar;
Basically I want the data to return like this
Ajax request 1 Data
Ajax request 2 Data
Ajax request 3 Data
Instead of keep getting overwritten by the new data.
.append() is what you're looking for
$(document).ready(function() {
$("#foo").submit(function() {
var url = "new_shout_ajax_test.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#foo").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
$('#testarea').append(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
});
Just this :
$('#testarea').append(data); // Append the next data from ajax to the previous

jQuery submit doesn't handle "success"

I've gone through all of the solutions I could find on Stack Overflow and Google but none of them seem to help.
I have a function in Clojure (Noir framework) that takes two keys, "text" and "day-of-note" and inserts the values into a database. Regardless of whether or not that works, the function returns a JSON response with {"result":true} (for testing purposes).
(defpage [:post "/newpost"] {:keys [text day-of-note]}
[]
(println "newpost called")
(post text)
(response/json {:result true}))
My form is a simple form with one textarea, a checkbox and a button.
<form action="/newpost" id="new-post" method="post">
<textarea id="entry" name="text">Insert todays happenings</textarea>
<br />
<input checked="checked" name="day-of-note" type="checkbox" value="true">
<input type="submit" value="Add entry">
</form>
When submitting the form I have added a call to alert to show me the contents of dataString and they are formatted correctly ("text=lalala&day-of-note=true").
$(function () {
$("#new-post").submit(function (e) {
e.preventDefault();
var dataString = $("#new-post").serialize();
alert(dataString);
$.ajax({
url: "/newpost",
type: "POST",
dataType: "json",
data: dataString,
success: function () {
alert("Success!");
};
});
return false;
});
});
What happens here when the code is as it is above, there is a HTML call to /newpost when the user click on the button and the page shows {"result":true}. If I comment out the "$.ajax"-part the message box pops up with the correct content, but if I remove the comments -- no message box, just goes straight to /newpost.
What I thought was supposed to happen was that the /newpost page would never be rendered but a call with the dataString would be put to it by Ajax and a message box with "Success!" would be shown.
Where am I taking the wrong turn?
Remove the semi-colon after the success function declaration:
success: function () {
alert("Success!");
}
The success function declaration is part of an object, which separates declarations by comma.

Categories