Undefined value ajax JQuery php - javascript

HELP!
Undefined values for all fields
function UpdateData(){
var id = $('#id').attr('value');
var name = $('#name').attr('value');
var department = $('#departament').attr('value');
var phone = $('#phone').attr('value');
var mail = $('#mail').attr('value');
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: "submit=&name="+name+"&department="+department+"&phone="+phone+"&mail="+mail+"&id="+id,
success: function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
}
});
return false;}
When I call the function it doesn't work, the value stored in the db is undefined for all fields and I tried to solve it by adding {} to the string on data: -->
data: {"submit=&name="+name+"&department="+department+"&phone="+phone+"&mail="+mail+"&id="+id},
but if I do that, the next part is not executed
success: function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
}
updatePersonal.php -->
<?php
require('functions.php');
if(isset($_POST['submit'])){
require('clases/personal.class.php');
$objPersonal = new Personal;
$id = htmlspecialchars(trim($_POST['id']));
$name = htmlspecialchars(trim($_POST['name']));
$department = htmlspecialchars(trim($_POST['department']));
$phone = htmlspecialchars(trim($_POST['phone']));
$mail = htmlspecialchars(trim($_POST['mail']));
if ($objPersonal->actualizar(array($name,$department,$phone,$mail),$id) == true){
echo 'Saved';
}else{
echo 'There was an error...';
}
}else{
if(isset($_GET['id'])){
require('clases/personal.class.php');
$objPersonal = new Personal;
$consult = $objPersonal->show_person($_GET['id']);
$personal = mysql_fetch_array($consult);
?>
<form method="post" action="updatePersonal.php" onsubmit="UpdateData(); return false">
<input type="hidden" name="id" id="id" value="<?php echo $personal['id']?>" />
<p>
<label>Name<br />
<input class="text" type="text" name="name" id="name" value="<?php echo $personal['name']?>" />
</label>
</p>
<p>
<label>Department<br />
<input class="text" type="text" name="department" id="department" value="<?php echo $personal['department']?>" />
</label>
</p>
<p>
<label>Phone<br />
<input class="text" type="text" name="phone" id="phone" value="<?php echo $personal['phone']?>" />
</label>
</p>
<p>
<label>Mail<br />
<input class="text" type="text" name="mail" id="mail" value="<?php echo $personal['mail']?>" />
</label>
</p>
<p>
<input type="submit" name="submit" id="button" value="Send" />
<label></label>
<input type="button" name="cancel" id="cancel" value="Cancel" onclick="Cancel()" />
</p>
</form>
<?php
}
}
?>

Your data should be in JSON format:
{"submit": "", "name": name, "department": department}
and so on..

First, make sure your variables are being properly populated, maybe using a simple alert(varname) after the initialization... I suspect they are not being set.
Then I would suggest to try assigning the values like this:
var id = $('#id').val();
var name = $('#name').val();
var department = $('#departament').val();
var phone = $('#phone').val();
var mail = $('#mail').val();

Use val() function instead of attr() and write param in JSON format like so:
function UpdateData(){
var id = $('#id').val();
var name = $('#name').val();
var department = $('#departament').val();
var phone = $('#phone').val();
var mail = $('#mail').val();
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: {
id: id,
name: name,
department: department,
phone: phone,
mail: mail
}
}).done(function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
});
return false;
}
Instead of fetching value for each input field and using JSON format inside data object, use $('form').serialize() like so
function UpdateData(){
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: $('#form').serialize()
}).done(function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
});
return false;
}
On updatePersonal.php page the $_POST['param'] will be according to name attribute of input field. For eg. for phone input field it may be $_POST['phone'] if the name attribute value will be equal to phone.
Search for relevant questions here, before asking any question.

Related

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

Showing "Thank you message" with AJAX and running php script

I have a form and I want when someone click submit, run upis.js write thank you message and run php script for inserting into database. For now it takes values I can see them in my url but it doesnt run upis.php. Can you tell me why?
Here is the code for form:
<form>
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>
and upis.js
<script>
function upis(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var prezime_slavljenik = document.getElementById("prezime_slavljenik").value;
var email = document.getElementById("email").value;
var dataString = "ime="+encodeURIComponent(ime)+"&prezime="+encodeURIComponent(prezime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik)+"&prezime_slavljenik="+encodeURIComponent(prezime_slavljenik)+"&email="+encodeURIComponent(email);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
data: dataString,
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
and upis.php
<?php
require_once 'include/db.php';
require_once 'include/functions.php';
$allowed_params = allowed_post_params(['ime', 'prezime', 'ime_slavljenik', 'prezime_slavljenik', 'email','submit']);
// niz sadrzi dozvoljene maksimalne duzine za sva polja
$fields_lengths = ['ime' => 64, 'prezime' => 64, 'ime_slavljenik'=>64, 'prezime_slavljenik'=>64, 'email' => 64];
// provera da li su polja odgovoarajuce duzine
foreach ($fields_lengths as $field => $length) {
if (!has_length($_POST[$field], ['min' => 0, 'max' => $length])) {
header('Location: greska.html');
die();
}
}
try {
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO prijavljeni (ime, prezime, ime_slavljenik, prezime_slavljenik, email) VALUES(:ime, :prezime, :ime_slavljenik, :prezime_slavljenik, :email)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':ime_slavljenik', $ime_slavljenik);
$prep->bindParam(':prezime_slavljenik', $prezime_slavljenik);
$prep->bindParam(':email', $email);
$ime = isset($allowed_params['ime']) ? $allowed_params['ime'] : "";
$prezime = isset($allowed_params['prezime']) ? $allowed_params['prezime'] : "";
$ime_slavljenik = isset($allowed_params['ime_slavljenik']) ? $allowed_params['ime_slavljenik'] : "";
$prezime_slavljenik = isset($allowed_params['prezime_slavljenik']) ? $allowed_params['prezime_slavljenik'] : "";
$email = isset($allowed_params['email']) ? $allowed_params['email'] : "";
// izvrsavanja upita
$rez = $prep->execute();
$htmltable = "Hvala na poslatoj prijavi.";
echo $htmltable;
} catch (PDOException $e) {
echo 'greska kod upita';
}
?>
I cant see what can be problem here because js takes values from form but doesnt actually run upis.php(it doesnt take url upis.php) I dont understand why..
If you're developing your application using Firefox or Chrome look in the network tab of web inspector to ensure the JavaScript resource successfully sends an XHR request. Check the URL that the POST XHR request is sent to.
Is the URL set correctly in the url property of the AJAX settings?
You may need to prepend "upis.php" with a forward slash e.g. "/upis.php"
You should call script from index.php, you missed action and method in form
<form action="upis.php" method="post">
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>

How to add onkeypress save in php form

**This is my php index.php file. I want to type first name and last name type and auto it has to be save the database. I wrote the code using ajax. but, this is not working properly. Please can any one help me. **
index.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script type="text/javascript">
$(document).on('keyup','firstName','lastName',function(){
var rel = $(this).attr('rel');
var flatvalue = $(this).val();
$("#firstName"+rel).val(flatvalue);
});
</script>
</head>
<body>
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
</body>
</html>
onKeyPress event not proper because it call many times as per user hit.
Use onBlur event instead of onKeyPress for submit the form and save it to MySql users table.
Try below example,
PHP
<?php
$connection = mysql_connect("localhost", "jaydeep_mor", "jaydeep_mor");
$db = mysql_select_db("jaydeep_mor", $connection);
if(isset($_POST['firstName']) && isset($_POST['lastName'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName != '' || $lastName != ''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
header("Location: test.php?msg=Data Inserted successfully...!!");
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
HTML / JAVASCRIPT
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta><title>Home Page</title>
<script type="text/javascript">
function saveData(){
document.forms["userDataForm"].submit();
}
</script>
</head>
<body>
<?php if(isset($_GET['msg']) && trim($_GET['msg'])!=""){ ?>
<br /><div><?php echo $_GET['msg']; ?></div><br />
<?php } ?>
<form action="test.php" method="post" name="userDataForm">
<label for="firstName">First Name</label>
<input type="text" name="firstName" value="<?php echo isset($_POST['firstName'])?$_POST['firstName']:''; ?>" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" value="<?php echo isset($_POST['lastName'])?$_POST['lastName']:''; ?>" onblur="return saveData();" ><br><br>
<!--input type="submit" id="Submit" name="Submit" value="submit"/-->
</form>
</body>
</html>
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_REQUEST['firstName'])){
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
die();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
die();
}
}
//mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){ alert('d');
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url:'',
data:{'firstname':firstname,'lastname':lastname, },
type: 'POST',
success: function(data){
alert("Data Save: " + data);
}
});
});
});
</script>
</head>
<body>
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName"><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName"><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</body>
</html>
may be this can help you,
if you want to do it via form submit then just you need to give the url of your controller function in the action method of the form
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
if you want to do it via ajax then you can add id attribute for first_name and last_name input and can do it in following way,
$('#submit').on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: url of your controler, //url of your controller function
type: "POST",
data: {'first_name' : first_name,'last_name':last_name},
success: function (data) {
//whatever you want to do on success
} else {
//in case of no data
}
}
});
});
in the same way you can give a class attribute to the input box and on keyup event can save the data via class
have you try doing it this way
$('body').delegate('input[type="text"]', 'keypress keydown keyup change propertychange paste', function(event) {
event.stopImmediatePropagation();
if (event.type === 'keydown' || event.type === 'keypress') {
return;
}
//insert what you want to do here
//perform some ajax
/*
$.ajax({
url: 'index.php',
method: 'POST',
data: {
'firstName' : $('input[name=firstName]).val(),
'lastName' : $('input[name=lastName]).val()
},
success: function(mResponse) {
alert(mResponse);
}
});
*/
});

store form data into database using ajax json php

I'm trying to store form data in database but my code is reflecting anything.
Here is my code
add.php
<form name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
</li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" id="address" type="text" rows="3" cols="40"></textarea></textarea>
</li>
</ul>
<p>Register</p>
</fieldset>
</form>
and javascript file is as
serve.js
$(document).ready(function () {
$("#btnBooking").on("click", function (e) {
// as you have used hyperlink(a tag), this prevent to redirect to another/same page
e.preventDefault();
// get values from textboxs
var name = $('#name').val();
// alert('name');
var lname = $('#lname').val();
var username = $('#username').val();
var password = $('#password').val();
var gender = $('#gender').val();
var mail = $('#email').val();
var mobNum = $('#mobile').val();
var address = $('#address').val();
$.ajax({
url: "http://localhost/project_cloud/fun.php",
type: "post",
dataType: "json",
data: {type: "add", Name: name, Lname: lname, User: username, Pass: password, Gen: gender, Email: mail, Mob_Num: mobNum, Addr: address},
//type: should be same in server code, otherwise code will not run
ContentType: "application/json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (err) {
alert(JSON.stringify(err));
}
})
});
});
and another php file which stores the result in database
fun.php
<?php
header('Access-Control-Allow-Origin: *');
mysql_connect("localhost", "root", "");
mysql_select_db("ocean");
if (isset($_GET['type'])) {
$res = [];
if ($_GET['type'] == "add") {
$name = $_GET ['Name'];
$lname = $_GET['Lname'];
$userN = $_GET['User'];
$passW = $_GET['Pass'];
$gen = $_GET['Gen'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mob_Num'];
$address = $_GET['Addr'];
$query1 = "insert into oops(username, password, firstname, lastname, gender, email, mobile, address) values('$userN','$passW','$name','$lname','$gen','$mail','$mobile','$address')";
$result1 = mysql_query($query1);
if ($result1) {
$res["flag"] = true;
$res["message"] = "Data Inserted Successfully";
} else {
$res["flag"] = false;
$res["message"] = "Oppes Errors";
}
}
} else {
$res["flag"] = false;
$res["message"] = "Invalid format";
}
echo json_encode($res, $result1);
?>
When I write my serve.js file code in add.php file it gives me result as stored in database .But when I tried to separate it js file it shows nothing. What wrong in it or I missing something.
You have
type:"post",
in your AJAX request, but server side handle $_GET parameters:
$lname = $_GET['Lname'];
Change $_GET to $_POST and you'll see your values.
But all your code is terrible. You can't publish this in Internet. You have bad JavaScript and many issues serverside, include MySQL Injection. Need to rewrite all of this with prepared statements and JS to:
$(function() {
$("#btnBooking").on("click", function(e){
e.preventDefault();
var data = $(this).parents('form').serializeArray();
data.type = 'add'
$.post('/project_cloud/fun.php',data)
.done(function(response){
alert(JSON.stringify(response));
})
.fail(function(err){
alert(JSON.stringify(err));
})
});
})

Form values via AJAX to PHP first being cut off and then not being recognized

Submitting the following form:
<form name="register" method="post" onSubmit="registerUser();">
<fieldset>
<label for="user_name">Name</label>
<input name="user_name" type="text" id="user_name" placeholder="Name" />
<label for="user_email">Email</label>
<input name="user_email" type="email" id="user_email" placeholder="Email"/>
<label for="user_password">Password</label>
<input name="user_password" type="password" id="user_password" placeholder="Password" />
<input name="s" type="hidden" value="register" />
</fieldset>
<input type="submit" value="Register" />
</form>
via AJAX
function registerUser(){
var myform = $("form[name='register']"),
data = {};
myform.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: urlService,
type: 'POST',
data: data,
success: function(response){
}
});
return false;
}
The "s" value of "register was being cut off to "regist" when echoed in following PHP statement. So in an effort correct it I escaped the values as so in the prior jQuery statement:
value = escape(that.val());
This then allowed the full value to be passed, although adding "%20" to the name value. I continued as follows...
forwarded on to PHP
print_r($_POST);
try{
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
switch($_POST['s']){
case 'register':
$response = 'registered ok + ';
break;
case 'login':
break;
}
$response = 'services read';
echo $response;
} catch(PDOException $e){
echo $e->getMessage();
}
At this point all of the $_POST values are being echoed, HOWEVER the value of "register" is not being recognized by the SWITCH statement.
I am not sure what I am doing incorrectly nor at which point... any help in cleaning up these glitches would be greatly appreciated.

Categories

Resources