Submit a form without reloading page [duplicate] - php

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;
})
;

Related

Using AJAX to launch PHP without reloading page

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.

Undefined index error in php using ajax

<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}

Processing Jquery Post with PHP

I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.

send post variables via jquery(ajax) to php himself document

I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!

Send single input with ajax/jquery/php

I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');

Categories