jQuery Ajax not submitting data - php

I decided to have my first go with ajax to submit my data but I'm having problems. The form seems to reset but no data is sent to the database, I'm probably missing something obvious here:
jQuery (currently included in the header of my file)
<script>
// jQuery to submit form data via AJAX to add a recovery pack
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}}
</script>
The PHP/HTML form
<form id="rpack_add_form" class='small_form' name='rpack_form' method='post' onsubmit="return submitForm();">
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for 2nd form at a later date</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for 3rd form at a later date</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add Recovery Pack' name='add_rpack'>
</form>
<div class="form_result"> </div>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
The PHP for addrpack.php (this code works fully when I remove the ajax part from above and just submit as normal)
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if a number has been entered
if (empty ($number))
{
echo "You need to enter a number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}

Probably a syntax error - missing );
$('#rpack_add_form').submit(function(){
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});
return false;
});

$.ajax({
type:'POST',
url: 'addrpack.php',
data:{"data":$('#rpack_add_form').serialize()},
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});//Syntax misatke

Not sure what your onsubmit="return submitForm();" in form does but you have to stop the submit button from sending the data and instead make it use your ajax function.
$(function(){
$('.button').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response) {
$('#rpack_add_form').find('.form_result').html(response);
}
});
});
});

Related

Trying to get value from option on selected tag with jQuery and post to php page

I'm trying to get value from the selected option and post on a Php. But I also have a form to Post data as well. I'm trying to combine the two but now when I try to run the code I get a blank query page.
message.php
<form id="messageEmployeeForm" class="form table-striped" method="POST" action="core/query.php">
<select id='toEmployee' class='form-control formBlock' name='toEmployee_id' value='' type='text' class='form-control formBlock'>
<option value="">To...</option>
<?php
$employeesQuery = $db->query("SELECT * FROM employees");
while ($employee = mysqli_fetch_assoc( $employeesQuery)) {
?>
<option id='toEmployees_id' name='toEmployees_id' value="<?php echo $employee['employee_id'] ;?>">
<?php echo $employee['first_name'] ;?> <?php echo $employee['last_name'] ;?></option>
<?php } ;?>
</select>
//other inputs here...
<input name="sendMessage" id="submit" type="submit" class="formBlock btn btn-success" value="Send Message"/>
</form>
jquery
<script>
$(document).ready(function () {
$("#toEmployee").bind("change", function (e) {
$.ajax({
type: "POST",
data: { data: $("#toEmployee").val() }
});
});
});
</script>
query.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sendMessage']) && isset($_POST['data'])){
$var = $_POST['data'];
//other data to be posted and bind here using prepared statements...
]
Your query.php file is expecting two post keys to be present during the request, without these it won't run the inner code.
isset($_POST['sendMessage']) && isset($_POST['data'])
Therefore inside your jQuery, you need to additionally send the sendMessage key like so:
$.ajax({
type: "POST",
data: {
data: $("#toEmployee").val(),
sendMessage: 'your value'
},
success: function(data) {
// do something with output (data)
}
});

Submit page but dont refresh

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

Form with PHP and AJAX Request

I have the following simple form:
Here is my code behind the form:
<form action="javascript:void(0);" method="post">
<fieldset>
<legend>ROOM EQUIPMENT</legend>
<div class="inline_inputs">
<div class="input_box">
<input type="checkbox" name="equipment" value="computer" id="computer">
<label for="computer">Computer</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="projector" id="projector">
<label for="projector">Projector</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="whiteboard" id="whiteboard">
<label for="whiteboard">Whiteboard</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="visualiser" id="visualiser">
<label for="visualiser">Visualiser</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="desk" id="desk">
<label for="desk">Desk</label>
</div><!-- .input_box -->
</div>
</fieldset>
<div class="buttons">
<input type="submit" class="reg_button" value="GET ROOMS" />
</div><!-- .buttons -->
And finally here is how I am making the AJAX request on the same page where this form sits:
<script>
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
I am fairly new to PHP and I'm having an issue with the form submission. When I make a selection, my selection is not sent to the userLogic.php file. I get a print out of:
Sorry, You have not made a selection.
This is coming from the PHP code that sits inside the userLogic.php file which is this:
<?php
include("connect.php");
$items = array_key_exists('equipment', $_POST) ? $_POST['equipment'] : '';
if(!empty($items))
{
if ($_POST["equipment"] == "computer") {
echo "checked computer!";
} else if($_POST["equipment"] == "projector")
{
echo "checked projector!";
$sql = "SELECT room_name, day_avail, from_time, to_time, equip_name
FROM rooms
JOIN equipment ON (equipment.room_id = rooms.room_id)
JOIN room_availability ON (room_availability.room_id = rooms.room_id)
WHERE equip_name='Projector'
GROUP BY day_avail";
$myData = mysql_query($sql,$conn) or die(mysql_error());
} else if($_POST["equipment"] == "whiteboard")
{
echo "checked whiteboard!";
} else if($_POST["equipment"] == "visualiser")
{
echo "checked visualiser!";
} else if($_POST["equipment"] == "desk")
{
echo "checked desk!";
}
} else {
echo "> Sorry, You have not made a selection.";
}
?>
Look up the arguments for $.ajax. You're not POSTing... And you're not POSTing data, either.
type: "POST"
and
data: str
needs to be in:
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
Doesn't seem you are posting your data..do it like this.
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str,
//rest of your code

Prevent the default action when using jQuery for Ajax

I'm trying to prevent the default action when submitting a form with ajax but I believe I have my code wrong as the page seems to do a 'refresh' and the form clears but nothing is sent to the database. I tried adding the link to the php processing script in the 'action' part of the form and it does submit fine to the database so the problem seems to be with my jQuery code.
<script type="text/javascript">
$(document).ready(function(e){
e.preventDefault();
$("#rpack_add_form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $("#rpack_add_form").serialize(), function(data) {
$('#ajaxResult').html(data);
});
}
});
});
</script>
My form code:
<div id="rpacks_admin" style="display: none;">
<h5>Add A New Recovery Pack</h5>
<form id="rpack_add_form" class='small_form' name='rpack_add_form' action='' method='post'>
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for content</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for contentrm</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add' name='add_rpack'>
</form>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
and my PHP if needed
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
include_once 'bcrypt.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if password and username has been submitted then add to DB
if (empty ($number))
{
echo "You need to enter a recovery pack number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}
The .validate() object has a sendForm parameter. It is set to true by default, but you need to set it to false, as in the code below, to prevent the form from being submitted:
$(document).ready(function () {
$('#rpack_add_form').validate({
submitHandler: function (form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $('#rpack_add_form').serialize(), function (data) {
$('#ajaxResult').html(data);
});
},
sendForm: false
});
});
You can reference the docs for more info.

Categories