Ajax sending date data - php

I have a problem with my jquery script, it is returning error when I try to send the date value from my form, when I leave it in blank, it doesn't show me an error.
<div class="field-wrap">
<input type="date" name="fecha_nacimiento" required autocomplete="off" maxlength="30" placeholder="Fecha de nacimiento">Fecha de nacimiento</input>
</div>
<script>
$(function(){
$('#entrarBt').click(function(){
$.ajax({
url: 'registro_dpb.php',
type: 'POST', // GET or POST
data: $("#miForm").serialize(), // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>

Your problem was pretty subtile... Making it hard to find.
But the solution is really simple.
You use a <button> inside a <form> which is absolutely correct.
But you have to know that in HTML5, if the type of a <button> is not explicitly defined as "button", its default type is "submit".
Reference here.
This was the issue...
Since you want to submit using an ajax request, which allow to receive a response without reloading the page, you have to "prevent" this normal behavior of a <button>.
The submit made by the button was not sent to your PHP script, but to your HTML page (there was no other action defined in the <form> tag, so the default is "self".
So the page reloads... Making your ajax request to fail.
So there is two ways to fix this:
1: Define the button type as "button":
<button type="button" id="entrarBt" [+ other attributes]>Entrar</button>
or
2: Prevent this default behavior using prevent.default() in you click handler.
$('#entrarBt').click(function(e){
e.preventDefault();
$.ajax({
//...
I think the second one is more evident for another programmer who could review your code, but the first is ok too.
For the benefit of the other SO readers:
We *(me and Javier)* checked almost every other error possibilities [in chat][3].
I finally found the cause when, for a test, I commented out the whole ajax block and then noticed that the page was still submitting.
Fixing this completely resolved the issue.
This is a tricky thing to absolutely know!
In short, a <button> within a HTML5 <form> is a submit by default!

Related

nesting <button> inside <form> causes unexpected behavior

I'm using ZURB Foundation 6.4 (ZURB template) for my Website.
I wanted to test out my newly implemented backend and tried to gather some input and send it to my php backend via jquery AJAX.
Meanwhile, I've managed to do so, but I encountered a very strange problem.
I've used the following building block:
https://foundation.zurb.com/building-blocks/blocks/floated-label-wrapper.html
I modified it a little, but just concerning the id's and placeholders and such stuff, nothing functional.
In the end, I had this markup used as a partial for one of the views I've generated:
<form class="callout text-center">
<h2>Become A Member</h2>
<div class="floated-label-wrapper">
<label for="full-name">Forename</label>
<input type="text" id="forenameInput" name="forename input" placeholder="forename">
</div>
<div class="floated-label-wrapper">
<label for="email">Surname</label>
<input type="text" id="surnameInput" name="surname input" placeholder="surname">
</div>
<div class="floated-label-wrapper">
<label for="pass">Email</label>
<input type="email" id="emailInput" name="email input" placeholder="email">
</div>
<button class="button expanded" id="submitUserDataButton">Sign up</button>
</form>
The button at the very end was once an input with type submit, I've changed that to a button since it suited my needs better.
However, the behavior, both with the input and the button, was always the same as long as the button/input was nested inside the form element:
After clicking it, the site would reload and the called function would execute until it hit my ajax.
Now for completeness, I'll post the AJAX here (it was wrapped intp/called by another function but this doesnt matter here):
function sendUserDataToBackend(userDataInputCollection){
console.log("sendUserDataToBackend was entered")
return $.post("http://localhost:8099/test2.php"
}).then((response) => {
console.log(response)
})
}
It entered the function and the console.log happened and then...nothing. The AJAX itself never executed.
I couldn't really find out why that is, I just figured out how to circumvent it.
I just put my button outside the form element and everything worked fine.
Now, why is that?
Why does having the button nested inside the form element cause such trouble, like causing a page reload and then even preventing an AJAX call from happening?
I mean, forms are made for taking input and sending it to the backend, aren't they? Or have they "gotten old" in some way and one should avoid using them?
How do these elements work, what are their "side effects"?
EDIT:
Here is the handler Code as requested
The logic for the handler is exported from file A
export async function executeRegistration(){
let userDataInputCollection = getUserDataInput()
userDataInputCollection = JSON.stringify(userDataInputCollection)
console.log(userDataInputCollection)
await sendUserDataToBackend(userDataInputCollection)
}
function getUserDataInput(){
let userDataForename = $('#forenameInput').val()
let userDataSurname = $('#surnameInput').val()
let userDataMail = $('#emailInput').val()
let userDataInputCollection = {
forename : userDataForename,
surname : userDataSurname,
email : userDataMail
}
return userDataInputCollection
}
function sendUserDataToBackend(userDataInputCollection){
console.log("sendUserDataToBackend was entered")
return $.post("http://localhost:8099/test2.php", {
userDataInputCollection : userDataInputCollection
}).then((response) => {
console.log(response)
})
}
And imported to file B, where it is attached via jquery:
import * as registrationJS from "./lib/registrationLogic.js"
$('#submitUserDataButton').on('click', function(){
registrationJS.executeRegistration()
})
Clicking a submit button will submit the form. That's the point of submit buttons!.
The browser will leave the page (and load the new page). JavaScript running in the old page will be cancelled (because JS runs in the page, leaving the page quits the program).
If you want to use Ajax instead of regular form submission, then you need to prevent the regular form submission.
Note that best practice is also to bind to the form's submit event and not the button's click event. This better captures form submissions triggered without using the button.
Replace:
$('#submitUserDataButton').on('click', function(){
registrationJS.executeRegistration()
})
With:
$('form').on("submit", function (event) {
event.preventDefault();
registrationJS.executeRegistration();
});

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

performing php post with jquery.ajax

I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.

Website design prevents data being posted to server

I have a big problem with my website.
I have made it in a way that seems to stop be from doing anything.
I have a number of containers, the main part of the page has three small containers all on top of each other and then a bigger container next to them that has the main content. The content that is shown in this main container is pulled from other pages so I don't have to refresh the whole page ever time a link is pressed. So I have one main page (the index) and a bunch of other content filled pages.
Now, if a page were to need to post data to the server to process it and then confirm with the user, this can't be done with normal PHP like I'm used to because the whole page is refreshed and it goes back to the default.
So I thought, I know Ajax can do this. I can post data to the server, process it and then change something on that page without loading anything.....
But I was wrong, it seems that it still wants to refresh the whole page meaning I lose my data. Also with the Ajax I am using "post" not "get" but for some reason it's putting the data into the address bar.
Is there a way I can keep my current structure and be able to do this, or am I doomed?
Any help, tips, code or advice would be MORE than welcome and thank you for the time and help.
Oh yeah, if I view the content outside of the index page the script runs just fine, it's only when the index pulls it from another page.
Ajax:
unction pass()
{
// Real Browsers (chrome)
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var oldPass = document.getElementById('oldPass').value;
var newPass = document.getElementById('newPass').value;
var newPassCheck = document.getElementById('newPassCheck').value;
xhr.open("POST","changeSettings.php");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
var obj = {oldPass: oldPass, newPass: newPass, newPassCheck: newPassCheck};
xhr.send("data=" + JSON.stringify(obj));
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
//grade = xhr.responseText;
document.getElementById("myDiv").innerHTML = xhr.responseText;
//document.write.grade;
//alert ("Nice essay. Your grade is " + grade);
}
}
return false;
}
Here is the original page:
<div id="content">
<form>
<h1>This page is still under construction please do not attempt to use it!</h1>
<p>
Old Password: <input type="password" name="oldPass" id="oldPass"><br />
new Password: <input type="password" name="newPass" id="newPass"><br />
Retype Password: <input type="password" name="newPassCheck" id="newPassCheck"><br />
<input type="submit" name="submit" value="Submit" onClick="return pass();">
</p>
</form>
<div id="myDiv" name="myDiv"> </div>
</div>
Just because you're supplying "POST not GET" in the form doesn't mean ajax will handle it this way.
What needs to be actually done is attach to the submit event of the form, then let AJAX handle it the rest of the way. On a confirmed submission (or even a failure) you can update content (or show errors).
To keep it simple with jQuery...
<div id="content-container">
<form method="post" action="/some/submission/page.php">
<!-- flag to let the landing page know it's an ajax request
this is optional, but IMHO it makes for a more seamless
experience -->
<input type="hidden" name="ajax" value="true" />
<!-- controls go here -->
</form>
</div>
So there's your form. Now, you need to attach to the submit event. Again, I use jQuery for simplicity, but feel free to use any method. I also am creating a very generic controller here so you could presumably use it for every form found on the page, but that's up to you. (And, because we still decorate the <form> an absence of javascript will still proceed, but when it IS there, it will use the nice ajax look and feel)
// use .live to catch current and future <form>s
$('form').live('submit',function(){
var target = $(this).prop('action'),
method = $(this).prop('method'),
data = $(this).serialize();
// send the ajax request
$.ajax({
url: target,
type: method,
data: data,
success: function(data){
//proceed with how you want to handle the returned data
}
});
});
The above will take a normal form found on the page and make it submit via AJAX. You may also want to bind to $.ajaxError so you can handle any failures.
Also, depending on the content you return from the AJAX call, you can either pass the entire response back to the container ($('#content-container').html(data); in the success call), or if it's JSON or plain text, display other data.
Oh, and using my example, you may want to have something like the following in your posted page:
<?php
$ajax_call = isset($_POST['ajax']);
if (!$ajax_call){
// not an ajax call, go ahead with your theme and display headers
}
// output content as usual
if (!$ajax_call){
// again, not ajax, so dump footers too
}
(That way when it's AJAX, only the info in your container is returned, otherwise display the page as usual because they probably don't support AJAX/JavaScript).
You need to put up the page or post a code example in order to get answers to this question.
If I were to take a guess, it would be that you are not preventing submission of the form, so it's firing off the ajax request like you asked, but also submitting the form. In order to prevent it, you need to select the submit button and have it return false. Here's a quick example with jquery of how you would do this
$('input[type=submit]').click(function(){
$.ajax({ ... request here ... });
return false
});
or you can also catch the click event and prevent default, as such
$('input[type=submit]').click(function(event){
event.preventDefault();
});
Since I can't see any of your code, this is not guaranteed to be right. If you post the code, I can revise this. In the meantime, hopefully I guessed it!

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories