Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have created an application using xampp (apache and mysql). I have the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Name</title>
</head>
<body>
<div id="main">
<h1>Details</h1>
<div id="name">
<h2>Name</h2>
<hr/>
<Form Name ="form1" Method ="POST" ACTION = "name.php">
<label>Name: </label>
<input type="text" name="per_name" id="name" required="required" placeholder="please enter name"/><br/><br />
<label>Age: </label>
<input type="text" name="per_age" id="age" required="required" placeholder="please enter age"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</div>
</body>
</html>
and the following PHP code:
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "details";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "INSERT INTO persons (person_name, person_age)
VALUES ('".$_POST["per_name"]."','".$_POST["per_age"]."')";
if ($connection->query($sql) === TRUE) {
echo "person added";
} else {
echo "person not added";
}
$connection->close();
}
?>
Instead of calling the php file using <Form Name ="form1" Method ="POST" ACTION = "name.php"> how would i create a simple ajax file to call the PHP file? i have tried to do this but can't seem to get anywhere, can anyone help me please? AJAX:
$(document).ready(function(){
$("#submit").click(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "name.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
});
}
return false;
});
});
Better to handle form submit :
Add ID to your form :
<Form id="form1">
Then :
$(document).ready(function(){
$("#form1").submit(function(e) {
e.preventDefault();
$.post('name.php', $('#form1').serialize(), function(data) {
alert(data);
});
return false;
});
In form
remove these in <form>
Method ="POST"
ACTION = "name.php"
add ID in submit button
<input type="submit" value=" Submit" id="submit" name="submit"/>
In AJAX
<script>
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault(); # add this ++Important++
var name= $("#name").val();
var age= $("#age").val();
$.ajax(
{
type:"post",
url: "name.php",
data:{ name:name, age:age },
success:function(result)
{
alert(result);
}
});
});
});
</script>
Related
Actually, i making a form and have many buttons in the form so I want to know that how it can be done whether when I click the button during form submission it will store that button value and after click to the final submit button a mail will send all input field values including button values that I have clicked.
<script type="text/javascript">
$(document).ready(function() {
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: '',
data: $('#frmemail').serialize(),
success: function() {
$('.success').fadeIn(1000)
}
});
});
});
</script>
<?php
if (isset($_POST['garden']))
{
$but= $_POST['garden'];
}
?>
<?php
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
$garden = $_POST['garden'];
$to = "admin#rsfcrm.com";
$subject = "RIA Emails";
$body = "Name: ".$name."\nEmail: ".$email."\nGarden".$but."\nMessage:".$message;
$headers = "From: ". $email;
if (mail($to,$subject,$body,$headers))
{echo "<script>window.alert('Successfull!');
</script>";
}else
{echo "<script>window.alert('Fialed');
</script>";
}?>
<div class="container">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<form enctype="multipart/form-data" id="frmemail" method="post" action="test2">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input name="form_email" type="email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<button type="submit" id="garage" name="garden" value="gardening">button</button>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
</div> </body>`
You can use jquery and hidden variable functionality.
like on first button click store value in hidden field and on second button click submit form. if you want code then i can paste here
<input type='hidden' name='garage_val' id='garage_val' value='' />
<script>
$("#garage").click(function(){
$("#garage_val").val($(this).val());
});
</script>
In your form add this input field
<input type='hidden' name='gardening' value='gardening' />
In your Php code
<?php
$gardening= $_POST['gardening'];
echo $gardening;
?>
Jquery
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: 'yourphpfilename.php',
data: $('#frmemail').serialize(),
success: function() {
alert(data)
}
});
});
No jquery click functions are required to do this,this value will be passed along with the form,hope this helps
(Or)
If you wish the value to be passed only on button click use this
Html
<input type='hidden' name='gardening' class="hidden"/>
Jquery
$("#garage").click(function(e)
{
e.preventDefault();
$('.hidden').val('gardening');
});
Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.
I have a simple Database on a Server (for Testing).
This PHP File is on the Server and works when I open the URL. (http://**.com/search.php?id=abc) Echo gives back "30"
<?php
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$idV = $_GET['id'];
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{ $posV = $row['position']; };
echo $posV;
?>
The HTML is just for Testing
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id= "bt1">Info Button</button>
<div id= "div1"> </div>
I want that when i enter a Code in the Textfield and press the Button, the Echo from the PHP is Displayed in the Div.
I know i should use Ajax GET, but i tried so many things and nothing worked.
Could you help me pls?
Edit: Last try: https://jsfiddle.net/qz0yn5fx/
<input type="text" id="txt1">
<button type="button" class="btn btn-info" id="bt1">Info Button</button>
<div id="div1">Here </div>
<script>
$(document).ready(function() {
$("#bt1").click(function() {
$.ajax({
//create an ajax request to load_page.php
type: "GET",
url: "http://**.com/search.php?id=a10 ",
dataType: "html", //expect html to be returned
success: function(response){
$("#div1").html(response);
alert(response);
}
});
});
});
</script>
Better dont look at the next Fiddle i just copied all first Tries:
https://jsfiddle.net/jqv1ecpj/
You could just use a simple POST request instead of a GET request.
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Info Button</button>
</form>
<div id="div1">Here </div>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search.php", $("#search").serialize(), function(d){
$("#div1").empty().append(d);
});
});
});
And then in your PHP, (don't forget to use try{}catch{}):
try {
$pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
I think this should work (haven't tested it). Let me know if it doesn't work and I'll test and correct it.
First i am just learning about PHP prepared statements and sql injection. And my first question is, is this php code good enough to stop sql injection. And my second question how do i submit this php statement with Ajax. Thanks in advance
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['submit_req']))
{
$req_title = $_POST['req_title'];
$req_min = $_POST['req_min'];
$req_entry = $_POST['req_entry'];
$req_payment = $_POST['req_payment'];
$post_req = $_POST['post_req'];
$stmt = $db->prepare('INSERT INTO users_request (req_title, min_order, poi, pay_method, req_brief) VALUES (:req_title, :min_order, :poi, :pay_method, :req_brief)');
$stmt->bindValue(':req_title', $req_title, SQLITE3_TEXT);
$stmt->bindValue(':min_order', $req_min, SQLITE3_TEXT);
$stmt->bindValue(':poi', $req_entry, SQLITE3_TEXT);
$stmt->bindValue(':pay_method', $req_payment, SQLITE3_TEXT);
$stmt->bindValue(':req_brief', $post_req, SQLITE3_TEXT);
$result = $stmt->execute();
if ($result)
{
echo "<p>Request post successful</p>";
}
}
Ajax code i have tried but didn't work
$('#post_form').submit(function () {
$.ajax({
url: "req_exec.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$('.success').html(data);
}
});
The form
<div class="success"></div>
<div class="post_req">
<form action="req_exec.php" method="post" enctype="multipart/form-data" id="post_form">
<input type="text" name="req_title" id="req_title" placeholder="Request title. (Example: Dried Cashew Nuts)">
<input type="text" name="req_min" id="req_min" placeholder="Minimum Order. (Example: 2 Tons, 7800 units, 40 container, 1 Barrel)">
<div class="form_division">
<input type="text" name="req_entry" id="req_entry" placeholder="Point of Entry">
<input type="text" name="req_payment" id="req_payment" placeholder="Payment Method">
</div>
<textarea name="post_req" id="post_req" placeholder="Briefly describe your request" rows="6"></textarea><br>
<input type="submit" name="submit_req" id="submit_req" value="Post Request">
</form>
</div>
Thanks in advance.
<script>
$(document).ready(function(){
$("#agentsubmit").click(function(){
var ajaxurl = '<?php echo site_url();?>/wp-admin/admin-ajax.php';
$.ajax({
type: "POST",
dataType : "json",
url : ajaxurl,
data : {
action :'join_mailinglist_callback',
'email': email
},
success:function(data){
// your success call
$(".alert-message").html(data);
}
});
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<form class="agnet-contact-form" name="contact_form" method="post" action=" " id="agnet-contact-form1">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="text" name="full_name" placeholder="Name" required>
<input type="text" name="phone_number" placeholder="Phone" required>
<input type="text" name="email_address" placeholder="Email" id="contactemail" required>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<textarea name="message" placeholder="Message" required></textarea>enter code here
<input type="submit" class="agent_submit" name="submit" id="agentsubmit" value="submit now">
</div>
</form>
Here is code which I wrote in functions.php which is action of ajax.
/* send mail using ajax*/
add_action('wp_ajax_join_mailinglist', 'join_mailinglist_callback');
add_action('wp_ajax_nopriv_join_mailinglist', 'join_mailinglist_callback');
function join_mailinglist_callback() {
$email = $_POST['email'];
if(!empty($email)) {
$yourEmail = 'fc#abc.com';
$subject = 'contacting Us';
$success = mail($yourEmail, $subject, $email);
if(!empty($success)) {
echo 'Email sent successfullly.';
} else {
echo 'Email Does not send sorry please try again.';
}
}
die();
}
This code gave me error NetworkError: 404 Not Found - http://localhost/wordpress/functions.php
I have used jquery and also include min.js file in my code.And pass the url of admin ajax but alert is not working in a response I have tried out.
What is the reason for that and how solve it.
If email sent successfully give response and it will write on Div that Email sent successfully Otherwise it says that Email don't send from the functions.php file
Refer to wp_ajax.
The code in for ajax function is wrong try this :
<script>
$(document).ready(function(){
$("#agentsubmit").click(function(){
var ajaxurl = '<?php echo site_url();?>/wp-admin/admin-ajax.php';
$.ajax({
type: "POST",
dataType : "json",
url : ajaxurl,
data : {
action :'join_mailinglist',
'email': email
},
success:function(data){
// your success call
$(".alert-message").html(data);
}
});
});
});
</script>