EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code
I've read up on as much AJAX as I can and I am flat out failing!
My HTML form looks like this:
<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
</form>
From Stack I've managed to get this AJAX:
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.
You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.
In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The following code may help you (though it's advised to not query the same page as your ajax request emits from):
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
Related
i have a form and i wanna use jQuery with it. but when i submit it it just doesnt use the code at all.
<form id="form">
<label>Name</label><br />
<input type="text" name="name"><br /><br />
<label>Message</label><br />
<textarea name="message"></textarea><br /><br />
<button type="submit">Submit form</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous">
//have to use jQuery to get the form data
jQuery(document).ready(function($){
$('#form').submit(function(e){
e.preventDefault();
alert('hello');
var data = $(this).serialize();
$.ajax({
url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
type: 'POST',
data: data,
success: function(response){
console.log(response);
}
});
});
});
</script>
i used a alert to see if it works but it just does nothing.
when i submit i get to a blank page. so the e.preventDefaults also doesnt work.
i tried using copilot but it didnt do anything usefull
You must declare your scripts in different tags.
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
<script>
//have to use jQuery to get the form data
jQuery(document).ready(function($){
$('#form').submit(function(e){
e.preventDefault();
alert('hello');
var data = $(this).serialize();
$.ajax({
url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
type: 'POST',
data: data,
success: function(response){
console.log(response);
}
});
});
});
</script>
I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)
I have like 143 form fields (text, textarea and select) that I would like to send through an AJAX post request. Is there a way I can do this quick without manually add every field to the query?
Alright so I've set up thing like this:
jquery
$("#submitbtn").click(function(){
$.ajax({url: "check_data.php", data: $("#form").serialize(), success: function(result){
alert(result);
}});
});
The form is declared like this:
<form class="pure-form" onsubmit="return false;" method="POST" id="form">
I tried also without the "return: false"
And the button as follow:
<button id="submitbtn" class="pure-button pure-button-primary">INSERT</button>
But it does not work, when I press the button I get no js or network activity whatsoever on the console, and nothing happens.
I solved it by using this:
$(function() {
$("#form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "check_data.php",
type: "POST",
data: $(this).serialize(),
success: function(d) {
alert(d);
}
});
});
});
I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>
im trying to achieve the following, in php i have a form like this:
<form method="post" id="form_1" action="php.php">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
the form action file is:
<?php
if( $_POST["sub"]=="add"){ ?>
<script>
alert("")
</script>
<?php echo "ZZZZZZ"; ?>
<?php } ?>
so this means if i press sub with value add an alert prompt will come up, how can i do the same thing(differentiate both submit) but using a Ajax request:
the following code so does not work:
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize()
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html)
}
})
})
})
</script>
</head>
<body>
<div id="1" style="width: 100px;height: 100px;border: 1px solid red"></div>
<form method="post" id="form_1" action="javascript:;">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
</body>
You could put the event handler on the buttons instead of on the form. Get the parameters from the form, and then add a parameter for the button, and post the form. Make sure the handler returns "false".
$(function() {
$('input[name=sub]').click(function(){
var _data= $('#form_1').serialize() + '&sub=' + $(this).val();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
You have to explicitly add the "sub" parameter because jQuery doesn't include those when you call "serialize()".
In this case you need to manually add the submit button to the posted data, like this:
$(function(){
$('form#form_1 :submit').submit(function(){
var _data = $(this).closest('form').serializeArray(); //serialize form
_data.push({ name : this.name, value: this.value }); //add this name/value
_data = $.param(_data); //convert to string
$.ajax({
type: 'POST',
url: "php.php?",
data: _data,
success: function(html){
$('div#1').html(html);
}
});
return false; //prevent default submit
});
});
We're using .serializeArray() to get a serialized version of the form (which is what .serialize() uses internally), adding our name/value pair to that array before it gets serialized to a string via $.param().
The last addition is a return false to prevent the default submit behavior which would leave the page.
Lots of semicolon missing, see below
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
});
});
jQuery Form plugin provide some advance functionalities and it has automated some tasks which we have to do manually, please have a look at it. Also it provides better way of handling form elements, serialization and you can plug pre processing functions before submitting the form.