AJAX call PHP same page and reload option values - javascript

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

Related

Retain ajax populated value in dropdown

I have a form where two dropdowns are kept. When the value on first is selected, ajax call is made to show related results as second dropdown list. My issue is when value is selected on second dropdown and form is submitted the second dropdown list(which is being populated on basis of first selection made in first select box) gets empty. I want to retain the value into the second dropdown selected after form submit. Can I have some insight over the same.
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Level:</label>
</div>
<div class="col-md-9">
<select name="levels" class="form-control" required="" id = "level">
<?php $fnc->selectBoxsearchLevel("tbl_levels_master","id","level_title", $level_id) ; ?>
</select>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#level").change(function() {
var level_id = $(this).val();
if(level_id != "") {
$.ajax({
url:"get_units.php",
data:{l_id:level_id},
type:'POST',
success:function(response) {
//console.log (response);
var resp = $.trim(response);
$("#unit").html(resp);
}
});
} else {
$("#unit").html("<option value=''>------- Selected --------</option>");
}
});
});
</script>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-3">
<label for="username" class="control-label">Select Unit:</label>
</div>
<div class="col-md-9">
<select name="units" class="form-control" required="" id= "unit">
<option>------- Select --------</option>
</select>
</div>
</div>
</div>
And my get_units.php
<?php
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$level_id = $_POST['l_id'];
$sql = "select * from tbl where level=$level_id";
$res = $db->query($sql);
echo "<option value=''>------- Select --------</option>";
while($row = mysql_fetch_array($res)) {
echo "<option value='".$row['id']."'>".$row['title']."</option>";
}
?>

Fill in radio input with database data

When I query the form returns the input radio filled with the data of the database, as shown:
<input type="radio" id="Estado" name="Estado" value="Pendente" ' . ( ($row6["Estado"]=='Pendente') ? 'checked' : '' ) .' readonly="true"> Pendente <input type="radio" id="Estado" name="Estado" value="Concluído" ' . ( ($row6["Estado"]=='Concluído') ? 'checked' : '' ) .' readonly="true"> Concluído
I also show in the completed image:
But when I click the edit button it changes the filled input radio and should not, because it no longer fills according to the data of the database, as I show in the image:
script:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
$('#Estado1').prop("checked", data.Estado);
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});
$('#insert_form6').on("submit", function(event){
event.preventDefault();
if($('#Colaborador6').val() == "")
{
alert("Colaborador é necessário");
}
else
{
$.ajax({
url:".conexao26",
method:"POST",
data:$('#insert_form6').serialize()
,
beforeSend:function(){
$('#insert6').val("Inserting");
},
success:function(data){
$('#insert_form6')[0].reset();
$('#exampleModal6').modal('hide');
$('#employee_table').html(data);
location.reload("exampleModal6");
}
});
}
});
HTML:
<form method="post" id="insert_form6">
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Data-name" class="col-form-label">Data</label></h6>
<h6><input type="date" name="data6" id="data6" value="<?php echo date("Y-m-d");?>"></h6>
</div>
</div>
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Colaborador-text" class="col-form-label">Colaborador</label></h6>
<h6><select style="width:150px" name="Colaborador6" id="Colaborador6" required>
<option></option>
<?php
$sql = "SELECT Funcionario FROM centrodb.InfoLuvas WHERE Ativo = '1' AND Funcao = 'Limpeza' AND Valencia = 'LAR'";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Funcionario'].'">'.$ln['Funcionario'].'</option>';
}
?>
</select></h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Tarefa Pendente</label></h6>
<textarea type="text" id="Observacao6" name="Observacao6" class="form-control"></textarea>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Estado</label></h6>
<div style="clear:both;"></div>
<h6><input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente <input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído</h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="disabled form-group">
<h6><label for="Observacao-name" class="col-form-label">Conclusão</label></h6>
<textarea type="text" id="Conclusao" name="Conclusao" class="form-control"></textarea>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="Nome6" id="Nome6" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="NomeConc" id="NomeConc" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
<input type="hidden" name="employee_id6" id="employee_id6" />
<input type="submit" name="insert6" id="insert6" value="Registo" data-toggle="modal" class="btn btn-success" />
</div>
</form>
I'm trying these ways but I still do not solve the problem:
1st form:
var tipo_conta = $('.tipo_conta').val(data.Estado);
if(tipo_conta == 'Pendente'){
$('#Estado1').prop('checked' , true);
}else{
$('#Estado2').prop('checked' ,true);
}
2st form:
var radios = document.getElementsByName("Estado");
if (radios.value == "Pendente") {
radios.checked = true;
}else{
radios.checked = true;
}
Can anyone help?
I found the issue inside the HTML file. As #daddygames suggested you have used the same ID in both Radio button. see below
<h6>
<input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente
<input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído
</h6>
An ID must be unique. Update the ID and make it unique. Then change the code in .ajax script according to your need. This will help you.
First I created the variable lis to receive the value that the radio input receives from the database:
var lis = $("#Estado").val();
Then inside the data function I created another variable with the value that the radio input receives from the function:
var teste = data.Estado;
and finally I check with if:
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
Full Code:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
var lis = $("#Estado").val();
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
var teste = data.Estado;
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});

Loading / executing .php file

I have been at this for a few hours now, i'm pretty sure it's a syntax error from my side, i'm trying to call a .php file and execute the contents, i'm passing through a textarea value to be used in the .php code.
HTML:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is - (<span class="results"><b>http://www.example.com/api.php?spinner=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="spinner.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right">
<label for="txtLanguage" class="control-label">Language:</label>
</div>
<div class="col-sm-8">
<select id="txtLanguage" name="txtLanguage" class="form-control" required="required">
<?php
$level = array("syn/en.syn" => "English", "syn/de.syn" => "German", "syn/pl.syn" => "Polish");
?>
<?php foreach ($level as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: { textData : text }
})
});
});
$("#mainContent").load('ajax-rewriter.php')
e.preventDefault();
</script>
ajax-rewriter.php
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
if (isset($_REQUEST['textData')) {
$articleBody = strtolower($_REQUEST['textData']);
echo $articleBody;
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
Pretty basic code, nothing is happening at all once i press the "Spin!" button, i'm still learning Ajax, i don't see any obvious errors, is there also a way i can debug what the issue is, normally php throws you an error to work from, any help is appreaciated!
Your Ajax should be like this.
$(document).ready(function() {
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val();
$.ajax({
url: "ajax-rewriter.php",
type: "POST",
data: text,
success: function(html) {
$("#mainContent").html(html); //This will load the data at ID "#mainContent".
}
});
});
});
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$data = $_POST['txtbody'] //where txtbody is the name in input form
}

Simple Ajax form submit!? (Can't understand)

I will try to explain my code simple. Basicly I got 2 different files:
fun.php
class.fun.php
I want to post my forms with ajax, so it won't refresh page.
In class.fun.php I have got reportForm for each post.
<!-- REPORT MODAL -->
<div class="modal fade report_post_<?php echo $post['id'];?>" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<b><center><div class="modal-header">Report Post</div></center></b>
<form class="horiziontal-form" id="reportForm" action="../Pages/fun.php?action=reportPostForm" method="post">
<center><textarea name="report" style="width:80%; height:200px; margin-top:20px; resize:vertical;" placeholder="Please describe your Report!"></textarea></center>
<input type="hidden" name="addedby" class="form-control col-md-7 col-xs-12" value="<?php echo $myRow['id']; ?>" />
<input type="hidden" name="image_id" class="form-control col-md-7 col-xs-12" value="<?php echo $post['id']; ?>" />
<div class="modal-footer"> <input type="submit" name="submit" value="Submit Form" /></div>
</div>
</div>
</form>
</div>
<!-- END OF REPORT MODAL -->
And after form I got ajax function:
<script>
$("#reportForm").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});
</script>
When I click button submit I want to send form data to fun.php
This is how I receive data in fun.php
if(isset($_POST['reportPostForm'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
}
And send them to other function in class.fun.php
But at this moment nothing happens. I have been looping trought many
tutorials and can't understand how to make this work. Im newbie in
javascript. I have got working upvote/downvotes scripts where I pass only post_id and it works.
I have got script for upvote that works:
$("#upvote_<?php echo $post['id'];?>").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
$('#upvote_<?php echo $post['id'];?>').load(document.URL + ' #upvote_<?php echo $post['id'];?>');
$('#downvote_<?php echo $post['id'];?>').load(document.URL + ' #downvote_<?php echo $post['id'];?>');
$('#comment_<?php echo $post['id'];?>').load(document.URL + ' #comment_<?php echo $post['id'];?>');
$('#share_<?php echo $post['id'];?>').load(document.URL + ' #share_<?php echo $post['id'];?>');
$('#report_<?php echo $post['id'];?>').load(document.URL + ' #report_<?php echo $post['id'];?>');
$('#report_btn_<?php echo $post['id'];?>').load(document.URL + ' #report_btn_<?php echo $post['id'];?>');
document.getElementById("result-box").innerHTML = result;
}
});
});
On fun.php you are checking for $_post['reportPostForm'] but this is not sent via post on this ajax call. your firm doesn't have this inputime and that's why nothing is happening. Try if(isset($_POST['report'])
Change this:
if(isset($_POST['report'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
echo "Done";
}
Also add the <div id='server-results'></div> to your form so that you can show the resutls.
<div class="modal-dialog modal-lg">
<div class="modal-content">
<b>
<center>
<div class="modal-header">Report Post</div>
</center>
</b>
<form class="horiziontal-form" id="reportForm" action="../Pages/fun.php?action=reportPostForm" method="post">
<center>
<textarea name="report" style="width:80%; height:200px; margin-top:20px; resize:vertical;" placeholder="Please describe your Report!"></textarea>
</center>
<input type="hidden" name="addedby" class="form-control col-md-7 col-xs-12" value="<?php echo $myRow['id']; ?>" />
<input type="hidden" name="image_id" class="form-control col-md-7 col-xs-12" value="<?php echo $post['id']; ?>" />
<div class="modal-footer">
<input type="submit" name="submit" value="Submit Form" />
</div>
</div>
</div>
<div id='server-results'></div>
</form>
</div>
It is not very clear what is not working.
The file is correct.
Only problem is in fun.php as you do:
if(isset($_POST['reportPostForm'])){
$image_id = strip_tags($_POST['image_id']);
$report = strip_tags($_POST['report']);
$addedby = strip_tags($_POST['addedby']);
$fun->reportPost($image_id,$report,$addedby);
}
But you are sending $_POST['addedby'], $_POST['image_id'] and $_POST['report'].
The one you are checking $_POST['reportPostForm'] do not exists.
Try to do the if against one of the three values you are passing.

I am trying to auto update mysql database using ajax and no click button

My database is not updating dynamically. Am I missing something?
It was working before removing some field names and also it was updating the user records automatically. But now it seems some issue in updating dynamically.
Form javascript used for updating
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
<script type="text/javascript" src="materialise/js/jquery-1.8.0.min.js"></script>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" >
<label for="firstname">Firstname: * <?php echo $firstname; ?></label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
update php used
<?php
// DATABASE: Connection variables
include_once("../php_includes/check_login_status.php");
// DATABASE: Clean data before use
function clean($value) {
global $db_conx;
$value = preg_replace('#[^a-z0-9. ]#i', '', $value);
$value = mysqli_real_escape_string($db_conx, $value);
return $value;
}
// FORM: Variables were posted
if (count($_POST)) {
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = "UPDATE users SET ".$col."='".$val."' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $result);
}
?>
below is the updated code working on my local...hope it will help you
did it without creating jquery plugin
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('input').blur(function() {
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
});
});
</script>
</head>
<body>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" value="<?php echo $firstname; ?>">
<label for="firstname">Firstname: * </label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
</body>
</html>
**Here’s the code example of a POST method call and AJAX database update –**
<div id="c">
<input id="text1" type="text" name="text1" />
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>``
**Now we declare the JQuery code to make a POST call**
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>
**This code block receive value and update database**
$t = $_POST['t'];
$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);
// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());
if(mysql_affected_rows()>=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'Try this again'; }

Categories

Resources