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.
Related
I have an application for rating a service. A on the form page has inputs for comment, giving it a star etc.
I want to make it in a way that when a user clicks on a star it should send the value of the star input to a php script for processing without having to click on the submit button. I thought of using separate forms for this, however, i just want to use one form because different forms will bring the layout.
HTML Form
<form action="" method="POST">
<input type="text" name="name">
<textarea name="comment"></textarea>
<input type="radio" name="rate" value="1">
<input type="radio" name="rate" value="2">
<button type="submit" name="submit">Submit</button>
</form>
JQuery for the sending rate to php
$("input[name=rate]").change(function(event){
var rating_num = $(this).val();
$.ajax({
url: '../handlers/rating.php',
type: 'POST',
data: rating_num,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
},
success: function (data) {
alert(data);
}
});
})
rating.php
echo $_POST['rating_num'];
The output I get is "undefined index:rating_num"
The above code is just a sketch.
First of all, you can debug your $_POST variable with var_dump function.
However, the reason why you have this error is that you need to put an object in the 'data' parameter.
{
...
data: {
rating_num: rating_num
},
...
}
Also, you could use $.post instead of $.ajax. See examples in jQuery API documentation.
$.post('rating.php', {rating_num: rating_num})
.done(function(data) {
console.log(data);
});
After following the example and answers by the following threads
jQuery AJAX submit form
submitting a form via AJAX
I have built a similar test form to get to learn the ajax request on submit. Your guess was right, it doesn't work for me (no alert popping up).
My testajax.php with the form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../test.js"></script>
<form name="feedback" id="idForm" action="(myurl)/testajax.php" method="post">
<input id="name" type="text">
<input type="submit" name="feedbacksent" value="Send" />
</p>
</form>
My test.js:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "(myurl)/testajaxinput.php"; // the script where you handle the form input.
e.preventDefault(); // avoid to execute the actual submit of the form.
alert("bla"); // does not work either
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
My testajaxinput.php that should handle the input:
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
}
Try this :
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
return true;
}
Then try your alert and also check have you got any error in console.
This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 5 years ago.
I know there are tons of questions like this one, but I still can't get this to work properly. Even a comment of what I should do to make this correct is more than enough since I understand like 80% of the jQuery..
<form action="meddelanden.php" id="fromen2" method="post">
<input type="text" name="message" id="type" autocomplete="off" placeholder="type your chat message">
<input class="lg" type="submit" name="submit" value="Send">
</form>
Meddelanden.php
<?php
session_start();
$meddelanden = $_POST['message'];
$username = $_SESSION['user'];
include ("connect.php");
$sql = $con->prepare('INSERT INTO messages (message,username) VALUES (?,?)');
$sql->bind_param("ss",$meddelanden,$username);
$sql->execute();
$sql->close();
$con->close();
?>
Scripts (which mess things up for my head)
$('#fromen2').submit(function(){
$.ajax({
type: 'POST',
url: meddelanded.php,
data: {
user: username, // <-- is this what i should write in data?!
message: message // <-- and this?!
},
success: function(msg){
alert('Message Sent');
}
});
return false;
});
So, my problem is what I should write in the data:, and I have no clue what I'm supposed to type there! Can anybody help me, or is it something else that makes it not work?
Try something like this. You might have to mess around with it a bit, though. I first prevented the form from automatically submitting when you pressed the submit button, then I use the value entered by the user into message, and input the value for messageInput in the data. Hope this helps.
$('#fromen2').submit(function(e){
e.preventDefault();
var userMessage = $('#messageInput').val();
$.ajax({
type: 'POST',
url: meddelanded.php,
data: {
//You dont need to send user data becaues you are setting the user variable with $_SESSION in php file
message: userMessage
},
success: function(msg){
alert('Message Sent');
}
});
return false;
});
HTML
<form id="fromen2" method="post">
<input type="text" id = "messageInput" autocomplete="off" placeholder="type your chat message">
<input class = "lg" type="submit" name="submit" value="Send">
</form>
Alternatively, instead of using the .submit() as the event, you could add a function to an onclick event that will retrieve the data from the form and post the data with AJAX to your PHP script.
$('#submitButton').on('click', function(e){
e.preventDefault();
var userMessage = $('#messageInput').val();
$.ajax({
type: 'POST',
url: meddelanded.php,
data: {
//You dont need to send user data becaues you are setting the user variable with $_SESSION in php file
message: userMessage
},
success: function(msg){
alert('Message Sent');
}
});
});
HTML
<form id="fromen2">
<input type="text" id = "messageInput" autocomplete="off" placeholder="type your chat message">
<input class = "lg" id="submitButton" name="submit" value="Send">
</form>
Just serialize form data using jQuery serialize:
$('#fromen2').submit(function(){
$.ajax({
type: 'POST',
url: meddelanded.php,
data: $(this).serialize()
success: function(msg){
alert('Message Sent');
}
});
return false;
})
;
I have the following code:
$(document).on('submit', function (event) {
event.preventDefault();
console.log('submitting');
hostingURL = '/<?echo $this->CI->uri->uri_string();?>';
$('form').attr('action', hostingURL);
var form = $(this);
$.ajax({
type: "POST",
url: hostingURL,
data: form.serialize()
}).done(function (data) {
$(document).unbind("submit");
$("#maincenter").html(data);
console.log('posted');
}).fail(function (data) {
alert('failed');
});
});
this is getting the requested url, and change the form to the action needed, then posting it to the server, and returning data.
server sided i have:
echo print_r($_POST);
echo "<br> type: ".$_SERVER['REQUEST_METHOD']." <br>";
It seems like whatever i do in my form wont acually submit it. The data back is correct, but from the server side code response i do get: Array ( ) 1 type: GET no matter what im doing.
So my question is: How can i acually make the form submit the post data?
The jquery function will be used on all my forms, so i need to get every field in the form to be submitted to.
Below is one example form.
example form:
<form method="POST">
<textarea class="textarea col-12" style="height:150px;" id="messageholder" name="profiltekst" placeholder="Profiltekst">
<? echo $userprofile->profiletext ?>
</textarea>
<div class="bottomform">
<input type="submit" class="makecenter" name="updateprofile" value="Endre profiltekst">
</div>
</form>
How do I serialize a form in jquery that is generated by php output?
$qrform = '<form action="" method="post" id="qrgen">
<p><strong>Bookmark a Website</strong></p>
Title<input type="text" name="title"><br />
Url<input type="text" name="url"><br />
<input type="submit" value="Generate"></form>';
echo $qrform ;
Now this data is displayed by an AJAX request. A php function outputs the data and then shows the form in the browser window.
How do I serialize this form in jquery, when the form is submitted?
what you need is
jQuery('#qrgen').serialize();
Updated code if your getting the form via ajax you will need to bind the submit button like this:
$(function () {
$(document).on('submit', '#qrgen', function (e) {
e.preventDefault(); //Prevent normal form submittion
var $form = $(this);
$.ajax({
url: $form.attr('action'),
data : $form.serialize(),
success: function(data) {
alert('Ajax was successful');
},
type : 'POST' //'POST' or 'GET'
});
});
});