I am trying to get response trough ajax,my code (index.html) :
<button id="register">Register</button>
<p id="result">xxx</p>
<script>
$("#register").click(function(){
$.ajax({
url:'registration.php',
type: 'POST',
success:function(response){
$("#result").html(response)
}
})
})
</script>
and php (registration.php):
<?php
echo "yyy"
?>
I am working with xampp, I get response but it fades from page instantly. And again xxx is present inside p tag, does anyone know what is the reason why this happens.
Thanks
It appears that when you click the button to get your response, it also refreshes the page in your browser. You can try the following to prevent this:
<script>
$("#register").click(function(evt) {
evt.preventDefault()
$.ajax({
url:'registration.php',
type: 'POST',
success: function (response) {
$("#result").html(response)
}
})
})
</script>
This prevents your browser from doing what it normally does when you click a button.Any button inside <form>tags will automatically send a GET request within the current window, causing the page to refresh. The other alternative to preventDefault() is to use the attribute type="button" on your button and this will stop the button from being a type="submit" button.
You can read more detailed information about the function I've used here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
https://api.jquery.com/event.preventdefault/
Just prevent page before submitting.
<input type='submit' id='register'>
<div id='result'></div>
$("#register").click(function(e){
e.preventDefault();
$.ajax({
url:'registration.php',
type: 'GET',
success:function(response){
document.getElementById("result").innerHTML = response;
}
})
});
Related
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 searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/
I don't get why the modal is showing my html's body content when I submit an input instead of the result of php.
I tried debugging it,then i found out that the modal shows its own content when I add data-toggle and data-target to the input/form, but the problem is that the modal shows after I click on the input even before I can even type something,and even I managed to type something, the same problem still exists
Here's the form:
<form id="form_id" action="some_php.php" method="POST">
<input id="input_id" type="text" name="input_name">
</form>
Here's the script:
$(document).ready(function()
{
$("#form_id").submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
data: $("form_id").serialize(),
url: 'some_php.php',
success: function(data) {
$("#fetched-data").html(data);
$("#myModal").show('show');
}
});
return false;
});
});
I have the following HTML form:
<form class="clearfix" method="POST">
<input name="name" type="textbox" placeholder="Name:">
<input name="email" type="textbox" placeholder="Email:">
<textarea name="message" placeholder="Message:"></textarea>
<input name="submit" type="submit" id="submit" value="submit">
</form>
Which launches a PHP script (which works) but re-directs the user to the empty page containing the PHP (ie. goes to mywebpage.com/send_mail.php). Using AJAX, how can I launch the PHP script in the background without re-loading the page?
I have the following AJAX request but it doesn't seem to work:
$('#submit').click(function(e) {
e.preventDefault();
var data = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#msg").val()
};
$.ajax({
url: '../send_mail.php',
type: 'POST',
data: data,
success: function(msg) {
alert('Email Sent');
}
});
});
Any assistance as to why it's not working? At the moment, all it does (when hitting submit) is go straight to the PHP page and seems to ignore the AJAX
It's getting reload because it's a submit button and that is added inside form so it's submitting the form on click without waiting for AJAX to get submitted.
You can use preventDefault() jQuery method to stop the page redirect. Like this,
$('#submit').click(function(e) {
e.preventDefault();
var data = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#msg").val()
};
$.ajax({
url: '../send_mail.php',
type: 'POST',
data: data,
success: function(msg) {
alert('Email Sent');
}
});
});
When preventDefault(); method is called, the default action of the
event will not be triggered.
You've also missed quotes to specify URL in .ajax().
jsFiddle: https://jsfiddle.net/3Lpft17y/
Use input type as button type = "button" instead of submit.
I would like to destroy $_SESSION['userList'] after cliking 'Cancel' button. However, the $_SESSION['userList'] is destroied when page load.
Below is my code:
<span>Cancel</span>
<script type="text/javascript">
function resetForm() {
<?php
unset($_SESSION['userList']);
?>
}
</script>
Really appreciate for any help.
You cannot execute PHP (server-side) in your javascript (client-side). You need to issue an HTTP request to invoke PHP. You can do that using AJAX.
JAVASCRIPT
$.ajax({
type: "POST",
url: "phppage.php",
data: "action=unsetsession",
success: function(msg){
alert(msg);
if(msg == "success"){
//cleared session
}else{
//failed
}
},
error: function(msg){
alert('Error: cannot load page.');
}
});
PHP
if($_POST['action'] == "unsetsession"){
unset($_SESSION['userList']);
echo "success";
}
You can not execute php code in the client side like you try in your example. If you want to to destroy session withou reload then you must use ajax request.
You better use jquery for this
<span>Cancel</span>
<script>
function resetForm()
{
jQuery.ajax({
type: "POST",
url: "cancel.php",
data:,
cache: false,
success: function(response)
{
}
});
}
</script>
And create a new cancel.php which will be like this -
<?php
unset($_SESSION['userList']);
?>
You can't call PHP from JS like this. You'll need to do a call back to the server.
Use submit button for Cancel (You can use CSS to make it look the away you want)
//HTML
<form method="post" >
<input type="button" value="Cancel" name="cancel" id="cancel" />
</form>
//PHP
if(isset($_POST['cancel'))
{
unset($_SESSION['userList']);
}