I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!
Related
I'm using Ajax to display a comments widget on my site and am trying to upgrade from Recaptcha v2 to Recaptcha v3. So far it's gone well, comments successfully post, but instead of displaying the "thanks for submitting" modal, it just redirects to the form submission URL with the success data. This is not ideal.
The main change I made was to change the button code in my comment_form.html to this:
<button class="button g-recaptcha" id="comment-form-submit"
data-sitekey="{{ site.reCaptcha.siteKey }}"
data-callback='onSubmit'
data-action='submit'>
Submit
</button>
</form>
<script>
function onSubmit(token) {
document.getElementById("new-comment").submit();
}
</script>
(and added the id="new-comment" to the top of the form)
previously i had
<button class="button" id="comment-form-submit">Submit</button>
the relevant javascript code is:
(function ($) {
var $comments = $('.js-comments');
$('.js-form').submit(function () {
var form = this;
$("#comment-form-submit").html(
'<svg class="icon spin"><use xlink:href="#icon-loading"></use></svg> Sending...'
);
$(form).addClass('disabled');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
showModal('Comment submitted', 'Thanks! Your comment is pending. It will appear when approved.');
$("#comment-form-submit")
.html("Submit");
$(form)[0].reset();
$(form).removeClass('disabled');
grecaptcha.reset();
},
error: function (err) {
console.log(err);
var ecode = (err.responseJSON || {}).errorCode || "unknown";
showModal('Error', 'An error occured.<br>[' + ecode + ']');
$("#comment-form-submit").html("Submit")
$(form).removeClass('disabled');
grecaptcha.reset();
}
});
return false;
});
I'm pretty sure it's like a one line change to make the Ajax process the reply, but I'm totally out of my depth with javascript, so any thoughts are greatly appreciated.
--
Edit: The other example I saw calls the onSubmit function from their callback but since I'm using this weird main.js I don't know how to reference $('.js-form').submit(function (event) { from onSubmit
The default browser behaviour after submitting a form is to redirect on success, try preventing this by calling preventDefault on the event, eg:
$('.js-form').submit(function (event) {
event.preventDefault();
// the rest of your code
});
I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.
My form:
<form id="new-protocol-form" method="post" role="form">
<textarea name="text"></textarea>
</form>
My jquery ajax:
$('#submitProtocol').click(
function() {
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function() { alert{'ok'} },
error: function() { alert('error'); }
});
}
);
My newProtocol.php:
<script>
alert(<?php echo $_POST['text']; ?>);
</script>
Alert window with 'ok' text triggered by ajax 'success' method is shown, but I can't get alert window with $_POST['text'] value from newProtocol.php file. No error in javascript console.
You need to use $_POST['text']. You're using parentheses where you shouldn't be.
In addition, since you're using AJAX you probably don't want to navigate to the other page. Your alerts in your success function will never fire if you don't prevent the default behavior.
newProtocol.php
<?php
echo $_POST['text'];
?>
jQuery
$('#submitProtocol').click(function(event) {
event.preventDefault(); // stop the default click behavior
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function(data) {
console.log(data); // show the text being returned
},
error: function() { console.log('error'); }
});
}
);
Also, quit using alert() for getting return values and trouble-shooting.
First, $_POST is not a function, it's an array. So it should be $_POST['text']. Also,
<script>
alert(<?php $_POST('text'); ?>);
</script>
will not create an alert like you expect since an async request does not run any javascript in the target page.
Since you're trying to test if the AJAX is working, the best way is to check what was the date returned from that request. Example:
//...
success: function(data) { console.log(data) },
//...
I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have two files. This is my main file - index.php which has javascript in the head, here's the javascript:
<script
src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function () {
$('form#revisionnotes').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: $('form').serialize(),
success: function () {
alert('You have successfully saved the revision notes.');
}
});
e.preventDefault();
});
});
</script>
So when my form:
<form id="revisionnotes" name="revisionnotes" method="post">
<textarea style="width:100%;height:290px; padding:10px;" id="notes" > <?php echo $db->result("SELECT * FROM revision_notes", "notes");?></textarea><br/>
<input type="submit" value="Save" name="submit" id="submit" class="btn btn-primary">
</div>
</form>
From there in my updatenotes.php I was going to do a database INSERT, however that didn't work so I then tried adding a javascript alert to see if that'd work either:
<script type="text/javascript">
alert("hi");
</script>
And that didn't work either, I'm completely stumped. Could somebody please explain to me where I'm going wrong? I've never used this type of form-submitting before.
Thanks.
You do not say where exactly the trouble lies, so this is an incomplete answer:
$(function () {
alert("Alpha - jQuery is called");
$('#revisionnotes').on('submit', function(e) {
alert("Bravo - submit received");
var data = $(this).serialize();
alert("Charlie - data serialized");
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
});
The above should allow you to see where (if) the workflow fails to follow the plan.
At this point the POST should have been fired, and using Firebug or WebDev you should be able to inspect the results. Otherwise, temporarily convert the POST to GET, copy the URL and paste into another browser window.
Note: do not put Javascript in the POST-receiving script, since chances are that it won't be executed. You're not "going" to that page, just doing a submit; that's why you don't see your alert.
Ordinarily you would return some information from the submission page in JSON format and let success() extract it from the data variable. Note that "success" only means that the target script received the submission, not that it did handle it properly.
Example of success function (and how to "talk" to it)
success: function(data, textStatus, jqXHR) {
if (data.status != 'OK') {
alert("ERROR " + data.message);
return;
}
if (data.message) {
alert(data.message);
// do not return
}
// other
}
So you'd start with a submit script like this (I repeat, this is awkward. You really want to do this with proper logging and Firebug!), commenting the various jqExit's once you check they code is working up to any given point:
<?php
function jqExit($status, $message = false) {
$packet = array('status' => $status);
if (false !== $message) {
$packet['message'] = $message;
}
exit(json_encode($packet));
}
jqExit('ERROR', "Alpha - got POST");
// Connect to database
jqExit('ERROR', "Bravo - connected to DB");
// Decode and validate POST
jqExit('ERROR', "Charlie - data ready");
// Perform update
if (...update failed...) {
jqExit('ERROR', "reason why it failed");
}
// Finally everything is OK
jqExit('OK');
?>