jQuery submit doesn't handle "success" - javascript

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.

Related

jquery-modal keeps last input

I want to use the jquery-modal plugin to make comments for several form elements. Its working fine, as long there is no keyboard input. Otherwise it remembers the last input and keeps that in the textarea, even if I empty it before.
This is the form that is shown in the modal window.
<a title="" href="#" onclick="getRechKomm('12345'); return false;" class="edit_komm">Kommentar</a>
<form id="RechKommForm" class="none">
<h3></h3>
<p><textarea name="kommentar" id="ptrRechKomm"></textarea></p>
<p><input type="hidden" name="rechid" id="ptrRechKommID" value=""></p>
</form>
<script>
function getRechKomm(rechnr){
$('#ptrRechKomm').html('');
$.ajax({
type: "POST",
url: "ptr_getrechkomm.php",
data: {rechnr: rechnr},
success: function(data){
readSession();
$('#ptrRechKomm').html(data);
$('#ptrRechKommID').val(rechnr);
$('#RechKommForm').modal({
escapeClose:false,
clickClose: false,
fadeDuration:500
});
}
});
}
$('#RechKommForm').on($.modal.BEFORE_CLOSE, function(event, modal) {
$.ajax({
type: 'POST',
url: 'ptr_putrechkomm.php',
cache: false,
data: $("#RechKommForm").serialize(),
success: function (data) {
$('#ptrRechKomm').html('');
$('#ptrRechKommID').val('');
}
});
});
</script>
So if call the comment for the ID 12345 and write a comment "Komm 12345", everything is fine. After that I call the comment for ID 23456, that may be already "Komm 23456". It is loaded from the database and put into the textarea #ptrRechKomm, but the first text is still there. So in the textarea is "Komm 12345Komm 23456".
Where is the old content coming from and how to delete it?
Update: Forget that all! Don't know why, but I thought that a textarea has to be filled by html(). Thats working, but only once. Filling it by val() is the correct way!

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) {
...
}
})

hidden form field not submitting

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

Toggle div depending on controller variable value

EDITED
I have a "Save Changes" button that I want to click and toggle a div with the message "Changes saved". I do it like this:
HTML:
<input type="submit" id="savebtn" name="save" value="Save Changes"/>
<input type="hidden" id="res" name="res" value="#ViewBag.result"/>
<div class="success">Changes saved</div>
JQuery
$('#saveButton').click(function () {
var aux = res.value.toString();
if ($('#res').val() == "OK")
$(".success").show();
alert(aux);
});
However, I need the button to actually save the changes and, if the operation was successful, then show the message div. So, in my cshtml file I have a result variable that contains the success or failure of the operation.
CSHTML:
ViewBag.result = result;
Now, I need to show that message div depending on the result variable: I need to somehow make it a parameter for the JQuery function. I'm passing it in a ViewBag.
NOTE: when the page loads, the viewbag is empty. It only gets its value after the button click. And after that, the viewbag is filled and I wanted it to be used in the jQuery function but I'm not getting any luck.
Pass that result in a viewbag,
Acces that viewbag value in jquery and show/hide your div accordingly
Assuming you can store the result in input hidden field, use below query to access result and initially success div is hidden :
<input type="hidden" id="result" value"success"/>
jQuery :
$(function(){
if($('#result').val()=="success")
$(".success").show();
});
you can check it in a simple if condition
if($('#result').val()=="success")
$(".success").toggle();
or You can use Ajax method
function Save() {
$.ajax({
url: "Your Url", // Current Page, Method
data: Your data // better if you parameter map as JSON
type: "POST",
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 100000, // AJAX timeout
success: function (result) {
$(".success").toggle();
},
error: function (xhr, status) {
alert("An error occurred while processing");
}
});
}
Now call this save() in your button click

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Categories