trouble using ajax to send form values to php file - php

I am trying to send the form values to another php file. After confirming to send the data, I will not receive the alert notification from the php file.
What i tried doing: I tried creating a test file with the shortened down version of the code, surprisingly that works
This is the first file.
<!DOCTYPE html>
<?php
include('../class/Appointment.php');
include('../main/databaseConnection.php');
$object = new Appointment;
if(!$object->is_Adminlogin()){
header("Location: ../main/error.php");
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doctor's Schedule</title>
<link rel="stylesheet" href="../css/add_schedule_popup.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="add_schedule_button" >Add Doctor Schedule</button>
<div id="add_schedule_popup" class="modal">
<div class="modal-content">
<div class="form-header">
<span class="close">×</span>
<h2>Add Doctor Schedule</h2>
</div>
<div class="form-body">
<form method="POST" action="" id="doctor_schedule_form">
<input type="hidden" name="action_type" id="action_type" value="add">
<div class="form-group">
<label>Select Doctor</label>
<select name="doctor_id" id="doctor_id" class="form-control" required>
<option value="">Select Doctor</option>
<?php
$object->query = "SELECT * FROM doctor_info ";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["doctor_id"].'">'.$row["doctor_firstname"].' '.$row["doctor_lastname"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Select Schedule Date</label>
<input type="date" name="schedule_date" id="schedule_date" required><br>
</div>
<div class="form-group">
<label>Select Timeslot</label>
<select name="schedule_timeslot" id="schedule_timeslot" class="form-control" required>
<option value="">Select Timeslot</option>
<?php
$object->query = "SELECT * FROM timeslot";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["schedule_timeslot"].'">'.$row["starting_time"].'-'.$row["ending_time"].' ('.$row["duration"].')</option>';
}
?>
</select>
</div>
<div>
<label>Select Availability</label>
<select name="schedule_status" id="schedule_status" class="form-control" required>
<option value="1">Available</option>
</select>
</div>
</div>
<br><br>
<div class="form-footer">
<button type="button" id="close_button">Close</button>
<input type="submit" id="submit_button" value="Confirm" name="submit_button">
</div>
</form>
</div>
</div>
<script>
var modal = document.getElementById("add_schedule_popup");
var btn = document.getElementById("add_schedule_button");
var span = document.getElementsByClassName("close")[0];
var close_button = document.getElementById("close_button");
btn.onclick = function() {
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
span.onclick = closeModal;
close_button.onclick = closeModal;
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
}
$(document).ready(function() {
$("#submit_button").click(function(){
e.preventDefault();
var doctor_id = $("#doctor_id").val();
var schedule_date = $("#schedule_date").val();
var schedule_timeslot = $("#schedule_timeslot").val();
var schedule_status = $("#schedule_status").val();
var action_type = $("#action_type").val();
console.log(doctor_id, schedule_date, schedule_timeslot, schedule_status, action_type);
$.ajax({
url: "modify_schedule_action.php",
type: "POST",
data: {doctor_id:doctor_id,schedule_date:schedule_date,schedule_timeslot:schedule_timeslot,schedule_status:schedule_status,action_type:action_type},
success: function(data) {
alert(data);
// Refresh the page or show a success message
},
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log(jqXHR.responseText);
}
});
});
});
</script>
</body>
</html>
And this is the php file that i am trying to send the values to
<?php
include('../class/Appointment.php');
$object = new Appointment;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'Received form data: ' . var_export($_POST, true);
}
if($_POST['action_type'] == 'add')
{
$data = array(
':schedule_date' => $_POST['schedule_date'],
':schedule_day' => date('l', strtotime($_POST["schedule_date"])),
':schedule_status' => $_POST['schedule_status'],
':schedule_timeslot' => $_POST['schedule_timeslot'],
':doctor_id' => $_POST['doctor_id'],
);
$object->query = "INSERT INTO `schedule` (`schedule_date`, `schedule_day`, `schedule_status`, `schedule_timeslot`, `doctor_id`)
VALUES (:schedule_date,:schedule_day,:schedule_status,:schedule_timeslot,:doctor_id)";
$object->execute($data);
$output = 'Data added successfully';
}
until now, the php file does not react to anything i do inthe first file. can anyone help me troubleshoot this error?

You have e.preventDefault(); in your event handler but e is not defined.
This will cause an error preventing your ajax code from running and your form will submit normally to itself as its action is blank.
$("#submit_button").click(function(e){// define the event parameter
e.preventDefault();

Related

How to pass a dropdown menu value in a Ajax JsonList in order to save the values in the database?

I want to pass a dropdown value to a JsonList and save it to the DB. Json list is first sent to the controller file and then it'll call the relevant Model and class. It works when the input type is a text. But doesn't work when it's a dropdown. Below are my codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="Psychlarity">
<!--<link rel="shortcut icon" href="../images/favicon.png" type="image/png">-->
<title>Psychlarity</title>
</head>
<body>
<form method="POST" id="add_article_station" data-toggle="validator">
<div class="panel-heading">
<h4 class="panel-title"><i aria-hidden="true" class=""></i>Add New Question </h4>
<p>Use this form to add a new question to the system</p>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-md-4">
<label>Age Category <span class="text-danger"></span></label>
<select name="age" id="age" class="select-css" >
<option disabled="disabled" selected="selected" >Select Age Category</option>
<option value="t">Teen</option>
<option value="a">Adult</option>
<option value="e">Elder</option>
<option value="">Any</option>
</select>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Relationship Status Category <span class="text-danger"></span></label>
<select name="RS" id="RS" class="select-css" >
<option disabled="disabled" selected="selected">Select Relationship Status Category</option>
<option value="m">Married</option>
<option value="n">Single</option>
<option value="">Any</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Employement Status Category <span class="text-danger"></span></label>
<select name="ES" id="ES" class="select-css" >
<option disabled="disabled" selected="selected" >Select Employement Status Category</option>
<option value="e">Employed</option>
<option value="s">Student</option>
<option value="u">Unemployed</option>
<option value="">Any</option>
</select>
</div>
</div> <br> <br>
<div class="row pull-right">
<div class="col-md-12">
<button class="btn btn-success btn-quirk btn-wide mr5">Submit</button>
<button class="btn btn-quirk btn-wide btn-default" type="reset">Reset</button>
</div>
</div>
</div></div></div></div></div></div></form></div></section>
<script>
$("#add_article_station").validator().on('submit', function (event) {
if (!event.isDefaultPrevented()) {
var formData = new FormData($('#add_article_station')[0]);
console.log(formData);
$.ajax({
url: "../../Controller/AddquestionController.php",
type: 'POST',
data: formData,
async: false,
success: function (data) {
try {
var json = JSON.parse(data)
if (json.code == 200) {
window.location = "?msg=suc";
// alert(json.message);
} else {
window.location = "?msg=err";
}
} catch (e) {
window.location = "?msg=err";
}
}, error: function (data) {
toastr.error("Error In Saving");
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
$(document).ready(function () {
'use strict';
function getParam(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
$(function () {
if (getParam("msg") == "suc") {
toastr.success("Sucssfully saved.");
} else if (getParam("msg") == "err") {
toastr.success("Question saved.");
}
});
</script>
<?php include '../includes/notificationJS.php'; ?>
</body>
</html>
The below is my Model where the DB query is.
public static function Addquestion($article, $logedUser) {
if (TokenValidationModelClass::TokenValidate($logedUser)) {
$dbh = dbconnect::Connection();
$addquestionStmtStmt = $dbh->prepare("INSERT INTO questions
(age_cat,employment_status,relationship_status)
VALUES
(:age_cat,:employment_status,:relationship_status); ");
$addquestionStmtStmt->bindParam(':age_cat', $article->age);
$addquestionStmtStmt->bindParam(':employment_status', $article->es);
$addquestionStmtStmt->bindParam(':relationship_status', $article->rs);
if ($addquestionStmtStmt->execute()) {
return HttpStatusMessageRest::getHttpStatusMessage(200);
}
}
return HttpStatusMessageRest::getHttpStatusMessage(401);
}
If anyone needs, below is the controller file of it.
<?php
include '../Model/session_include.php';
require_once("../Model/articleModelClass.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = (object) $_POST;
// print_r($data);
if (!empty($data)) {
if (!empty($data->token)) {
echo articleModelClass::Addquestion($data, $data->token);
} else {
$token = (object) $_SESSION;
// print_r($token);
echo articleModelClass::Addquestion($data, $token);
}
} else {
$error["error"] = "Empty field.";
echo json_encode($error);
}
}
?>

PHP jQuery ajax submit button not working

I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding
repeater.js
jQuery.fn.extend({
createRepeater: function (options = {}) {
var hasOption = function (optionKey) {
return options.hasOwnProperty(optionKey);
};
var option = function (optionKey) {
return options[optionKey];
};
var generateId = function (string) {
return string
.replace(/\[/g, '_')
.replace(/\]/g, '')
.toLowerCase();
};
var addItem = function (items, key, fresh = true) {
var itemContent = items;
var group = itemContent.data("group");
var item = itemContent;
var input = item.find('input,select');
input.each(function (index, el) {
var attrName = $(el).data('name');
var skipName = $(el).data('skip-name');
if (skipName != true) {
$(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
} else {
if (attrName != 'undefined') {
$(el).attr("name", attrName);
}
}
if (fresh == true) {
$(el).attr('value', '');
}
$(el).attr('id', generateId($(el).attr('name')));
$(el).parent().find('label').attr('for', generateId($(el).attr('name')));
})
var itemClone = items;
/* Handling remove btn */
var removeButton = itemClone.find('.remove-btn');
if (key == 0) {
removeButton.attr('disabled', true);
} else {
removeButton.attr('disabled', false);
}
removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');
var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
newItem.attr('data-index', key)
newItem.appendTo(repeater);
};
/* find elements */
var repeater = this;
var items = repeater.find(".items");
var key = 0;
var addButton = repeater.find('.repeater-add-btn');
items.each(function (index, item) {
items.remove();
if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
addItem($(item), key);
key++;
} else {
if (items.length > 1) {
addItem($(item), key);
key++;
}
}
});
/* handle click and add items */
addButton.on("click", function () {
addItem($(items[0]), key);
key++;
});
}
});
index.php
<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Add Remove Panel Group and Category</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="repeater.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<br/>
<h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
<br/>
<div style="width:100%; max-width: 600px; margin:0 auto;">
<div class="panel panel-default">
<div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
<div class="panel-body">
<span id="success_result"></span>
<div id="div1"><h2></h2></div>
<form method="post" id="repeater_form">
<div class="form-group">
<label>Pilih Group</label><br>
<select class="form-control" name="cat">
<option value="" disabled selected>Sila Pilih Kategori</option>
<option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
<option value="B">B - Pembinaan dan Bahan</option>
<option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
<option value="D">D - ICT & Multimedia</option>
<option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
<option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
<option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
<option value="H">H - Pengajaran dan Pembelajaran</option>
<option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
</select>
<label>Sila Pilih Kumpulan Panel</label><br>
<select name="group" class="form-control">
<option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
<option value="1">Panel 1</option>
<option value="2">Panel 2</option>
<option value="3">Panel 3</option>
<option value="4">Panel 4</option>
<option value="5">Panel 5</option>
<option value="6">Panel 6</option>
<option value="7">Panel 7</option>
<option value="8">Panel 8</option>
<option value="9">Panel 9</option>
<option value="10">Panel 10</option>
<option value="11">Panel 11</option>
<option value="12">Panel 12</option>
<option value="13">Panel 13</option>
<option value="14">Panel 14</option>
<option value="15">Panel 15</option>
</select>
</div>
<div id="repeater">
<div class="repeater-heading" align="right">
<button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
</div>
<div class="clearfix"></div>
<div class="items" data-group="programming_languages">
<div class="item-content">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<label>Pilih Nama Ahli Panel</label>
<select class="form-control" data-skip-name="true" data-name="skill[]"
required>
<?php
echo "<option>Sila Pilih Ahli Panel</option>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
}
} else {
echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
}
mysqli_close($conn);
?>
</select>
</div>
<div class="col-md-3" style="margin-top:24px;" align="center">
<button id="remove-btn" class="btn btn-danger"
onclick="$(this).parents('.items').remove()">Remove
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="form-group" align="center">
<br/><br/>
<input type="submit" name="insert" class="btn btn-success" value="insert"/>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#repeater").createRepeater();
$('#repeater_form').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: "insert.php",
method: "POST",
data: $(this).serialize(),
success: function (data) {
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
/*setInterval(function(){
location.reload();
}, 3000);*/
}
});
});
});
</script>
</body>
</html>
insert.php
<?php
connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
if (isset($_POST["name"])) {
$skill = implode(", ", $_POST["skill"]);
$data = array(
':panel_cat' => $_POST["cat"],
':panel_group' => $_POST["group"],
':panel_mem' => $skill
);
$query = "
INSERT INTO panel_penilai
(panel_cat, panel_group,panel_mem)
VALUES (:panel_cat, :panel_group, :panel_mem)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
echo '
<div class="alert alert-success">
Data Successfully Inserted
</div>
';
}
}
//?>
You can use XMLHTTP request to send the request. It is easier than your function and fully working. Check a sample request here XMLHTTP REQUEST
Let me know if you were successfull
Remove event.preventDefault(); .
preventDefault() method is used to stop submitting the form. Removing it will allow the form to submit the data to insert.php
first in insert.php your code will run if there is a "name" parameter that is posted, whereas in the index.php form there is no field with the name "name".
so the insert.php file doesn't display any results when you post with the current form
And as reminder you forget about $ and there is a database difference between insert.php and index.php
connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
should be
$connect = new PDO("mysql:host=localhost;dbname=icompex", "root", "bptm2012");
and in ajax you better add error handling so that you can see the error information in the console browser
$.ajax({
url:"insert.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
/*setInterval(function(){
location.reload();
}, 3000);*/
},
// like this
error : function(err){
console.log(err);
}
});
You just change the submit button type to button
<input type="submit" name="insert" class="btn btn-success" value="insert" />
change to
<input type="button" id="submit" name="insert" class="btn btn-success" value="insert" />
And event must be click not submit
$('#repeater_form').on('submit', function(event){}
change to
$('#submit').on('click', function(event){}
so page will not redirect, data post throw ajax.

Print success notice in their own div depending on the form that I sent

I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>

Unable to get jquery response when form is submited using submit button

I am sending state,city,zip code to ajax.php file. using jquery.
I am unable to get those values in response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
-->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function() {
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = 'reg_state='+ reg_state;
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data)
{
//$("#state").html(data);
alert(data);
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="submit" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
This is the ajax.php file , from where i need to send response, and make it visible in div id="state
<?php
if($_POST['reg_state'])
{
echo $_POST['reg_state'];
}
else{
echo 'nothing';
}
?>
Try create an object
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
I believe your problem lies in the type=submit. Replacing this with type=button gives you the result you want.
I'm unsure why this is, but I'm guessing it type=submit gives extra functionality to the input. The page seems to reload after hitting the submit button.
ps. don't forget you actually need to click the button in order for the function to trigger. Hitting enter after filling out the input fields will do nothing.
When ever we use input['type']="submit" in form
we have to use
$('#id-submit').click(function(e) {
e.preventDefault();
}
Here is the full working code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function(e) {
e.preventDefault();
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(data)
{
$("#state").html(data);
// alert('hi');
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
ajax_city.php
<?php
if($_POST['reg_state'])
{
echo 'STATE: '.$_POST['reg_state'].'<br/>';
echo 'CITY: '.$_POST['reg_city'].'<br/>';
echo 'ZIP: '.$_POST['reg_zip'].'<br/>';
}
else{
echo 'nothing to respond';
}
?>

Inserting comment to database using ajax

I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});

Categories