Jquery & Ajax - cannot trigger submit on form after ajax request - javascript

I am having a page with a form on it that should use AJAX to save and load data to a file.
JavaScript
This is the java script I am using:
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function( data ) {
$('#configFormContainer').html(data);
});
});
HTML for a-tags
The class .configFile in the second function refers to a list of a-Tags. When I click on of of those, the script successfully loads the content from a file and displays it. This is the html for the mentioned a-Tags:
<div class="list-group">
<a href="#" class="configFile>config.json</a>
<a href="#" class="configFile>config_1504987517.json</a>
</div>
This part is working fine: The javascript-function is triggered. In showForm.php the config file is loaded. It is re-building the complete form with the content from the file.
HTML for the form
Whats not really working is the trigger on the submit-function. This is the form-html
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
Whats the problem
So, whats happening now:
When I load the page initially, I click the submit-Button and get the alert. This trigger .submit() is working.
When I click one of the a-tags to load a config-file, the file is being loaded without refreshing the page. This trigger .click() is working, too.
After that: When I click the submit-button, the page is being reloaded. The trigger .submit() is not working.
And after this "unwanted" reload of the page, the .submit()-trigger is working, again.
I have no clue what it is wrong here. Hope someone can help
cheers

Though this isn't your whole code set, I took what you posted and made a page. I could click either of the .configFile links, then click the submit button and I get the alert.
However I did close both class attributes of the .configFile elements with a ". I don't know if that's the difference. But, if it isn't then it's something that's occurring after the ajax request which of course I can't simulate with this code.
<html>
<body>
<div class="list-group">
config.json <!-- //added " to end of class attribute -->
config_1504987517.json <!--//added " to end of class attribute -->
</div>
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
if (window.XMLHttpRequest)
{
// AJAX for IE7+, Chrome, Firefox, Safari, Opera
xmlhttp = new XMLHttpRequest();
} else {
// AJAX for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$('#configFormContainer').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET","showForm.php?loadConfig=" + this.text, true);
xmlhttp.send();
});
});
</script>
</body>
</html>
The other thing that would be curious to me: Open the browser's developer console and paste in your submit binder again:
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
If your submit works after that, I'd suggest either binding the click event again after the new html is rendered. Or, binding the event to $(document) like:
$(document).on('submit', '#saveConfigForm', (e) => {
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
As a final note, I'm not trying to augment your code any more than necessary to help with the specific issue you're having. As another user commented, it would be cleaner to use the jQuery functions since you're using jQuery. But I don't take that as part of your question.

I kind of found out whats causing the problem: The ajax-call returns the html-form and put it to the form-container.
After this, the trigger to that form is gone, because the trigger was connected to the form, that I am overwriting with the ajax-data.
Quick'n'dirty
It will work, when I reset the trigger like that. But this looks more like quick'n'dirty
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#configFormContainer').html(data);
// re-init the trigger on "submit" here
// ------------------------------------
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
});
});
});
Clean-Fix
I needed to adjust the the showForm.php. If it's being called from the ajax-method, it will only return the form elements, not the form itself.
If it is being called from the scratch, it returns the complete form.
Furthermore, the java script now replaces the content of the form-element, not it's container. This way the trigger does not get lost.
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#saveConfigForm').html(data);
});
});
});
Just for the sake of completeness, this is the main part of the showForm.php now:
<?php
if (!isset($_GET['loadConfig']))
{
// do not return the complete form to prevent losing the trigger on it
echo '<form id="saveConfigForm" method="POST">';
}
echo '<a bunch of form elements />';
if (!isset($_GET['loadConfig']))
{
echo '</form>';
}

Related

how to ajax for chatting website without page reload

want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet

Autosave form on idleness

I have the below code that is supposed to autosubmit(save) a form with the name "project" when the user is idle. This is code I found on a tutorial website(forget the name), I tried it and it only refreshes the page?
<!-- Set auto save timeout in milliseconds
<script type="text/javascript">
attachEvent(window,'load',function(){
var idleSeconds = 5;
var idleTimer;
function resetTimer(){
clearTimeout(idleTimer);
idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
}
attachEvent(document.body,'mousemove',resetTimer);
attachEvent(document.body,'keydown',resetTimer);
attachEvent(document.body,'click',resetTimer);
resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
document.project.submit();
window.location = location.href;
}
function attachEvent(obj,evt,fnc,useCapture){
if (obj.addEventListener){
obj.addEventListener(evt,fnc,!!useCapture);
return true;
} else if (obj.attachEvent){
return obj.attachEvent("on"+evt,fnc);
}
}
</script> -->
Form Code :
<form name="project" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="invoice-form" method="post" class="invoice-form" role="form" novalidate>
This is the code that is refreshing the page window.location = location.href; Try removing it.
And you also need to make sure your form's attribute name is replacing "project" in document.project.submit();.
For example
<form name="test_form"></form>
document.test_form.submit();
Edit:
Alright, the the function should just be
function whenUserIdle() {
document.project.submit();
}
Rather than doing an actual form submission, consider doing an AJAX request:
function whenUserIdle(){
var formData = {}; // assemble the form data here
$.post( "/form-submission-route", formData, function( responseData) {
// do something with result, if you like
// perhaps clear the form or throw up a notification
});
}

Jquery $.post() gives same page in HTML back

I have written a page so i can create a friendship between users. But my Problem is that jquery wont post the parameters.
I need some help, to fix that issue.
My Code:
//currentURL -> e.g: firstname.lastname
$('#friendRequestButton').on("click",function(e){
if(currentURL != "" && typeof(currentURL) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL})
.done(function(data) {
console.log(data); // Here I get the same page(in HTML-format).. as result in the console.
});
//$('#friendRequestButton').attr("disabled","true");
}
});
If you need more details, let me know.
My PHP-Code:
<?php
if(isset($_POST['user1']) && isset($_POST['user2'])){
$user1 = $_POST['user1'];
$user2 = $_POST['user2']
die("OK!");
}else {
die("NOO!");
}
?>
EDIT: I changed the way you mentioned with e.preventDefault();
<?php
$friends = false;
if(!$friends){
?>
<center>
<button class="submit" id="friendRequestButton">Ask for friendship</button>
<br />
<br />
<button>Send Message!</button>
</center>
<script>
$(document).ready(function(e){
$('#friendRequestButton').on("click",function(e){
console.log(e.target);
e.preventDefault();
if(currentURL != "" && typeof(currentURL) != "undefined" && $.cookie("user-id") != "" && typeof($.cookie("user-id")) != "undefined"){
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"), user2:currentURL},function(data){
console.log(data);
}
);
//$('#friendRequestButton').attr("disabled","true");
}else {
console.log("NOOOOO");
}
});
});
</script>
<?php
}
?>
Without seeing the html it is a guess, but judging by the name of your element you are using a button. Probably that button submits the form the "normal" way, causing your page to reload and you to not see the results of your ajax call.
If that is the case, you need to prevent the default event for the button press (submitting the form in this case):
$('#friendRequestButton').on("click",function(e){
e.preventDefault();
// the rest of your code
use your ajax request like this-
$.post("sendFriendRequest.php",{user1:$.cookie("user-id"),user2:currentURL}),function(data){
console.log(data);
});
I found the ISSUE:
I'm SOOOO Stupid:
I have written the filename like this: sendFriendRequest..php (two dots)
It should be: sendFriendRequest.php
So thanks everyone for helping!! :D

Sending form with PHP through AJAX with no page refresh

So I have this code to POST data with PHP and AJAX without redirecting page, I'm using the same script on the login page. The login page works like a charm but the other pages don't. The only diffeence between these is that login php script page uses if (empty($_POST) === false) {} and the other pages use if (isset($_POST['save-settings'])) {}. I don't know what do to.. Here below is the script I'm using.
HTML BUTTON
<input id="save-settings" class="submit" type="submit" name="save-settings" value="Save" onclick="return false;" />
JS SCRIPT
$(document).ready(function() {
$("#save-settings").click(function() {
var name = $("#webname").val();
var charset = $("#webchar").val();
var meta = $("#webmeta").val();
var description = $("#webdesc").val();
var startsite = $("#webstartsite").val();
var starturl = $("#webstartsiteurl").val();
var footer = $("#webfooter").val();
$.post("../lib/action.php", {
name: name,
charset: charset,
meta: meta,
description: description,
startsite: startsite,
starturl: starturl,
footer: footer
}, function(data) {
$("#gy-main-notification-bar").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#gy-main-notification-bar").slideUp(500) }, 2500);
});
});
});
PHP SCRIPT
if(isset($_POST['save-settings'])) {
$updatesettings = "UPDATE `settings` SET
`name`='".escape($_POST['webname'])."',
`charset`='".escape($_POST['webchar'])."',
`meta`='".escape($_POST['webmeta'])."',
`description`='".escape($_POST['webdesc'])."',
`startsite`='".escape($_POST['webstartsite'])."',
`starturl`='".escape($_POST['webstartsiteurl'])."',
`footer`='".escape($_POST['webfooter'])."'
WHERE `id`= 1";
if ($update_settings = $db_connect->query($updatesettings)) {}
echo 'Success!';
}
I don't really want to change the isset to empty in the script due the fact that I have all my "onclick" script in one action.php file. When I remove onclick="return:false;" from input it works.. I'm so confused I appriciate any help!
Click event handler function can have event argument. When you catch this argument you can use preventDefault() method. With this method default action of click will be prevented and page won't be refreshed.
Change
$("#save-settings").click(function() {
var name = $("#webname").val();
to
$("#save-settings").click(function(ev) {
ev.preventDefault();
var name = $("#webname").val();
You Forgot to include the post save-settings. You probably should've included it with the ajax post like this:
$.post("../lib/action.php", {
'name': name,
'charset': charset,
'meta': meta,
'save-settings': true,
'description': description,
'startsite': startsite,
'starturl': starturl,
'footer': footer
},
change this in your sql statement for the correct posts
`name`='".escape($_POST['name'])."',
`charset`='".escape($_POST['charset'])."',
`meta`='".escape($_POST['meta'])."',
`description`='".escape($_POST['description'])."',
`startsite`='".escape($_POST['startsite'])."',
`starturl`='".escape($_POST['starturl'])."',
`footer`='".escape($_POST['footer'])."'
WHERE `id`= 1";
writing onclick="return false" in HTML cancels the execution of the javascript code. just delete this onclick="..." and add preventDefault() like this to prevent form submittion
$("#save-settings").click(function(e) {
e.preventDefault();
.....

Javascript - Prototype: Event.observe on a form is not working for IE

I have this JS which gets a XML response from a service, its a True or a False, well the script should catch the submit and get the response from the service.
The problem is that I see that its not working because when I do the submit, I see the XML response on IE (6/7/8), when the script should have catched it and validated the XML response.
<div id="eventForm" style="display:none;">
Event.observe('formDataPersonal', 'submit', function(event) {
$('formDataPersonal').request({
onSuccess: function(t) {
var xml = t.responseXML.documentElement;
var stateNode = '';
var msgNode = '';
if (navigator.appName == "Microsoft Internet Explorer"){
stateNode = xml.childNodes[0].nodeValue.toLowerCase();
msgNode = xml.childNodes[1].nodeValue;
}else{
stateNode = xml.childNodes[0].textContent.toLowerCase();
msgNode = xml.childNodes[1].textContent;
}
if (stateNode == 'true'){
$('transparentDiv').style.display='none';
$('popup').style.display='none';
validateIntegrationPopup();
}else{
var error = msgNode;
if (error != ''){
$('interfase').innerHTML = error;
}
}
}
})
});
</div>
I would be grateful for the help.
I think the problem may be that 'IE' does not see the submit event so it ends up just submitting the form normally:
See: https://rails.lighthouseapp.com/projects/8994/tickets/4411-railsjs-on-bodyobservesubmit-but-submit-doesnt-bubble-in-ie
This is an old question, but I managed to get it as my second result in a Google search, so:
You're not stopping the submit event from going through to the browser, which is why the form is submitting even though the event handler attached to it. Add in an event.stop():
<div id="eventForm" style="display:none;">
Event.observe('formDataPersonal', 'submit', function(event) {
event.stop();
$('formDataPersonal').request({
// .... code ....
});
});
</div>

Categories

Resources