ajax - no transmission of data - php

I am a newbie on ajax. I spend hours with "try and error", but unfortunately without success.
I have a form:
<form id="upload" method="post" name="form">
<input class="datepicker" type="text" name="date" value="<?php echo $date_bes; ?>"/>
<input class="chk" name="chk" type="checkbox" value="<?php echo $id_submit; ?>"
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
<textarea class="remark" name="remark" cols="30" rows="1"><?php echo $remark; ?> </textarea>
<input class="submit" type="image" src="save.jpg"></td>
</form>
Then I my ajax_script.js:
$(document).ready(function() {
$( "#upload" ).on("submit", function() {
var id = $('.chk').val();
var date = $('.datepicker').val();
var chk = $('.chk').prop('checked');
var remark = $('.remark').val();
$.ajax({
type: "POST",
url: "update.php",
data : "{'id':'" + id + "', 'date':'" + date + "', 'chk':'" + chk + "', 'remark':'" + remark + "'}",
success: function (data) {
if(data.success == true)
{
console.log('everything fine');
}
},
error: function(){
console.log('something bad happened');
}
});
});
});
and my update.php
<?php
$id = $_POST['id'];
$date = $_POST['date'];
$chk = $_POST['chk'];
if($chk == true){
$check = 1;
}else{
$check = 0;
}
$remark = $_POST['remark'];
$jahr = substr($date,6,4);
$mon = substr($date,3,2);
$tag = substr($date,0,2);
$date = $jahr.'-'.$mon.'-'.$tag;
echo $id ."<br>".$date."<br>".$chk."<br>".$remark;
require_once('config.php');
$link = mysqli_connect (
MYSQL_HOST,
MYSQL_BENUTZER,
MYSQL_KENNWORT,
MYSQL_DATENBANK
);
if(!$link){
die('Keine Verbindung möglich: ' .mysql_error());
}
$sql = "UPDATE mytable
SET date = '$date', chka ='$chk', remark = '$remark' WHERE id_submits = $id";
$result = mysqli_query( $link, $sql );
echo $sql."<br>";
?>
After push on the bottom, firebug deliver me following:
Can anybody help me - please!
Regards,
Yab86

I think that you do not really need the quotes around the variable in the data section of ajax.
data: {id: id, date: date, chk: chk, remark: remark},

To let AJAX pass data through JQuery you should simply put in the "data" part of the AJAX request your data in this format {'name':name_on_php,'name2':name_on_php2}
I've written "name_on_php" to remind you that the part after the " : " is the one that you GET or POST on your php page.
Hope it helped :)

Related

comments are not showing on godaddy

i am poorly trapped and also not getting any proper support from the Godaddy customer care. I have a comment section which is working perfectly on localhost and some other hosting but it is not working on Godaddy hosting. I don't understand, why this only occurs on godaddy.
Here is my html :
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId" placeholder="Name" /> <input class="input-field" type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment" id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<input type="button" class="btn-submit" id="submitButton" value="Publish" /><div id="comment-message">Comments Added Successfully!</div>
</div>
</form>
</div>
<div id="output"></div>
Here is my script :
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response) {
//var result = eval('(' + response + ')');
//var result = eval('(' + JSON.stringify(response) + ')');
if (response) {
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else {
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{
comments = "<div class='comment-row'>"+
"<div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$("#output").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "<div class='comment-row'>"+
" <div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
And I am 100% sure that there is no connectivity problem with database. Please help me out.
here is comment-add.php
<?php
require_once ("db.php");
date_default_timezone_set('Asia/Kolkata');
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date("Y-m-d H:i:s", time());
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
here is comment-list.php
<?php
require_once ("db.php");
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
?>
here is db.php
<?php
$conn = mysqli_connect("localhost","xxxxxxxxx","xxxxxxxx","xxxxxxxxxx");
?>

jQuery Ajax working for only first result in while loop

The loop works fine, it display what it supposed to do, but there is a mysql update button of which updates only the first row value displayed:
$(document).ready(function() {
$("#update").click(function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var recordId = $("#recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
async: true,
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
}
});
});
});
<?php
$conn = new mysqli('localhost', 'root', '123456', 'lc');
$sql = "SELECT * FROM lc where customer='souhail'";
$result = $conn->query($sql);
// while ( $row=mysqli_fetch_assoc($result)) {
while($row = $result->fetch_array()) {
echo 'LC ID :<input type="text" id="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" id="lname" value="'.$row['element_101'].'"><br>';
$recordId = $row['lc_id'];
echo '<input id="recordId" name="recordId" value="' . $recordId . '" >';
?>
<button type="button" style="background-color:<?php
if($row['element_101'] == '1'){
echo '#0000FFF';
}elseif ($row['element_101'] == '2'){
echo '#ffff00';
}elseif ($row['element_101'] == '3'){
echo '#00FF00';
}elseif ($row['element_101'] == '4'){
echo '#ffffff';
}
//echo $row['element_101'];
?>;color:#000000" id="update">Go Forward ></button>
<br><br>
<?php
} ?>
You must have unique IDs but instead wrap each set in a container and access relative tags:
$(".update").on("click", function() {
var $container = $(this).closest(".container");
var fname = $container.find(".fname").val();
var lname = $container.find(".lname").val();
var recordId = $container.find(".recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
Php
while($row = $result->fetch_array()) {
echo '<div class="container">
echo 'LC ID :<input type="text" class="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" class="lname" value="'.$row['element_101'].'"><br>'; $recordId = $row['lc_id'];
echo '<input class="recordId" name="recordId" value="' . $recordId . '">';
echo '<button type="button" clsss="update">Go Forward ></button>';
echo '/div>';
} ?>

how to generate automatically id number based on the drop down selection with last id from the database

I have a form in which there is a field called index. What I want to do is to generate a index number automatically as follows.
ex: option1_01 , option2_01 , option1_02 .. etc
option1 comes based on the drop down selection. and _01 comes from the database using the last id number of table option1.
here is my form.php
<body>
<form id="" method="post" action="send.php">
<select name="name" id="name">
<option value="">please select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
</select><br>
<label for="index">Index</label>
<input type="text" id="index" name="index" readonly="readonly" value=""/><br>
<label for="fname">fname</label>
<input type="text" name="fname"/><br>
<label for="lname">lname</label>
<input type="text" name="lname"/><br>
<label for="age">age</label>
<input type="text" name="age"/>
<button name="submit">sumit</button>
</form>
</body>
Also I have two tables to insert data. when we select option1, rest of details should go into option1 table.
db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "testing01";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully <br/>";
?>
here is my jquery code
$(document).ready(function() {
$("#name option").filter(function() {
return $(this).val() == $("#index").val();
}).attr('selected', true);
var index1 = $("#index").val();
$("#name").on("change", function() {
$.ajax({
url:'table.php',
type:'post',
data:{index1:index2},
success:function(){
$("#index").val($(this).find("option:selected").attr("value"));
}
});
});
});
table.php
<?php
$index2 = $_POST['index2'];
include("db.php");
$sql = "SELECT MAX(id) FROM ".$index2." ";
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['MAX(id)'] + 1;
}
?>
send.php
<?php
if(isset($_POST['submit'])){
$option=$_POST['name'];
$index=$_POST['index'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
include('db.php');
if($option=="option1"){
$result1=mysqli_query($conn,"INSERT INTO option1(options,fname,lname,age) VALUES('$option','$fname','$lname','$age');");
if($result1){
echo "data inserted to option1 table";
}
}
if($option=="option2"){
$result2=mysqli_query($conn,"INSERT INTO option2(options,fname,lname,age) VALUES('$option','$fname','$lname','$age');");
if($result2){
echo "data inserted to option2 table";
}
}
}
?>
I think I have the problem in $ajax code snippet. it pass index2 varible into table.php. but i am unable to get back $next_id because I am new to jquery.
anyone help me to solve this?
Use alias MAX(id) as maxId in query to get record.
Table.php
<?php
$index2 = $_POST['index2'];
include("db.php");
$sql = "SELECT MAX(id) as maxId FROM ".$index2." ";
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['maxId'] + 1;
}
?>
finally I solved myself
my jquery code snippet should be changed as here
$(document).ready(function(){
$('#name').on('change', function() {
$('#index').val($(this).find('option:selected').attr('value'));
var index1 = $('#index').val();
$.ajax({
url:'table.php',
type:'post',
data:{index1:index2},
dataType:'json',
success:function(data){
var next_id = data;
$("#index").val(index1 + "_" + next_id);
//alert('success');
}
});
});
});
and
$sql = "SELECT MAX(id) AS max_id FROM ".$index2." ";
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['max_id'] + 1;
echo $next_id;
your ajax script has no result.
try this
$("#name").on("change", function() {
$.ajax({
url:'table.php',
type:'post',
data:{index1:index2},
success:function(result){
//result = $next_id from your table.php script...
$("#index").val($(this).find("option:selected").attr("value"));
}
});
});
and in your insert script:
......
$res = mysqli_query($conn,$sql);
$get = mysqli_fetch_array($res);
$next_id = $get['maxId'] + 1;
echo $next_id;
$next_id will be passed back to the ajax script in the result variable. (you can actually call this whatever you want...)
you can then do what you want with result as it will = $next_id
EDIT:
Also, I dont see a definition for index2 in your jquery code.

Javascript Not Updating Database

I have a Edit Profile, for the user's profile. Well, The Javascript seems to be only getting the value of the Age's Form. The PHP File is getting the Age, but no others and it's not updating the database.
Javascript:
function UpdateProfile() {
var newage = $("#NewAge").val();
var newimage = $("#NewImage").val();
var newbio = $("#NewBio").val();
var dataString = 'newage=' + newage || 'newimage=' + newimage || 'newbio=' + newbio;
if (newbio.length , newage.length , newimage.length == 0) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_profile.php",
data: dataString,
cache: false,
success: function (UpdateProfile) {
$('#EditInfo').hide();
$("#UpdatedProfile").html(UpdateProfile);
$("#UpdatedProfile").fadeIn('slow');
$("#Age").html('Age: ' + newage);
$('#Image').html('<img src="' + newimage +'" width="150" height="100" />');
}
});
}
}
Here's The update_profile.php File:
<?php session_start() ?>
<?php include 'connect.php' ?>
<?php
$newimage = $_POST['newimage'];
$newbio = $_POST['newabout'];
$newage = $_POST['newage'];
$update = "UPDATE members SET bio=(".$newbio.") age=(".$newage.") image=(".$newimage.") WHERE id='".$id."'";
$res = mysql_query($update);
echo 'Success: Profile Updated!<br />';
echo $update . '<br />';
?>
HTML:
<input type="text" id="NewAge" value="<?php echo $age ?>" maxlength="2" />
<input type="text" id="NewImage" value="<?php echo $image ?>" maxlength="500" />
<textarea id="NewBio" style="width: 500; max-width: 500; height: 100; max-height: 150;"><?php echo $bio ?></textarea>
<input type="submit" value="Update Profile" onClick="UpdateProfile()" />
The Code The Update outputs is this:
Success: Profile Updated!
UPDATE members SET bio=() age=(18) image=() WHERE id='1'
Try this instead:
$.ajax({
...
data: { newimage: newimage,
newage: newage,
newbio: newbio }
...
});
Update this line:
$newbio = $_POST['newabout'];
to
$newbio = $_POST['newbio'];
And it should work.

Problem with Mootools Ajax request and submitting a form

I have a table with content comming from a database. Now i tryed to realize a way to (a) delete rows from the table (b) edit the content of the row "on the fly". (a) is working perfectly (b) makes my head smoking!
Here is the complete Mootools Code:
<script type="text/javascript">
window.addEvent('domready', function() {
var eDit = $('edit_hide');
eDit.slide('hide');
var del = new Request.HTML(
{
url: 'fuss_response.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
eDit.slide('in');
}
});
$$('input.delete').addEvent( 'click', function(e){
e.stop();
var aID = 'delete_', bID = '';
var deleteID = this.getProperty('id').replace(aID,bID);
new MooDialog.Confirm('Soll der Termin gelöscht werden?', function(){
del.send({data : "id=" + deleteID});
}, function(){
new MooDialog.Alert('Schon Konfuzius hat gesagt: Erst denken dann handeln!');
});
});
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
var safe = new Request.HTML(
{
url: 'termin_safe.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
}
});
$$('input.edit').addEvent( 'click', function(e){
e.stop();
var aID = 'edit_', bID = '';
var editID = this.getProperty('id').replace(aID,bID);
edit.send({data : "id=" + editID});
$('edit_hide').slide('toggle');
});
});
</script>
Here the PHP Part that makes the Edit Form:
<?php
$cKey = mysql_real_escape_string($_POST['id']);
$request = mysql_query("SELECT * FROM fusspflege WHERE ID = '".$cKey."'");
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
}
echo '<form id="termin_edit" method="post" action="">';
echo '<div><label>Name:</label><input type="text" id="nns" name="name" value="'.$name.'"></div>';
echo '<div><label>Vorname:</label><input type="text" id="nvs" name="vorname" value="'.$vor.'"></div>';
echo '<div><label>Ort:</label><input type="text" id="nos" name="ort" value="'.$ort.'"></div>';
echo '<div><label>Telefon:</label><input type="text" id="nts" name="telefon" value="'.$tel.'"></div>';
echo '<div><label>eMail:</label><input type="text" id="nms" name="email" value="'.$mail.'"></div>';
echo '<input name="id" type="hidden" id="ids" value="'.$id.'"/>';
echo '<input type="button" id="sst" value="Speichern">';
echo '</form>';
?>
And last the Code of the termin_safe.php
$id = mysql_real_escape_string($_POST['id']);
$na = mysql_real_escape_string($_POST['name']);
$vn = mysql_real_escape_string($_POST['vorname']);
$ort = mysql_real_escape_string($_POST['ort']);
$tel = mysql_real_escape_string($_POST['telefon']);
$em = mysql_real_escape_string($_POST['email']);
$score = mysql_query("UPDATE fuspflege SET name = '".$na."', vorname = '".$vn."', ort = '".$ort."', telefon = '".$tel."', email = '".$em."' WHERE ID = '".$id."'");
As far as i can see the request does work but the data is not updated! i guess somethings wrong with the things posted
For any suggestions i will be gladly happy!
PS after some comments: I see the problem in this part:
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
The "Edit" request opens the form with the prefilled input fields and then attaches a click event to the submit button which should call a new request when clicked.
This third request i fail to pass the data of the input fields. i tried to get the value of each field like this:
var name = $('nns').getProperty('value');
and pass it this way
.send({data : "name=" + name});
did not work so far
PPS:
as requested the code that makes the html from main site
<?php $request = mysql_query("SELECT * FROM fusspflege");
echo '<form id="fusspflege" method="post" action="">';
echo '<table class="fuss_admin">';
echo '<tr><th>Name</th><th>Vorname</th><th>Ort</th><th>Telefon</th><th>eMail</th><th>Uhrzeit</th><th>Datum</th><th></th><th></th></tr>';
echo '<tr><td colspan=8 id="upd"></td></tr>';
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
$dat = $row->datum;
$uhr = $row->uhrzeit;
echo '<tr><td>'.$name.'</td><td>'.$vor.'</td><td>'.$ort.'</td><td>'.$tel.'</td><td>'.$mail.'</td><td>'.$uhr.'</td><td>'.$dat.'</td>';
echo '<td><input id="delete_'.$id.'" class="delete" type="button" value="X"></td>';
echo '<td><input id="edit_'.$id.'" class="edit" type="button" value="?"></td>';
echo '</tr>';
}
echo '</table>';
echo '</form>';
echo '<div id="edit_hide"></div>';
?>
UPDATE:
<form action="" method="post" id="termin_edit">
<div>
<label>
Name:
</label>
<input type="text" value="NAME" name="name" id="nns">
</div>
<div>
<label>
Vorname:
</label>
<input type="text" value="Marianne" name="vorname" id="nvs">
</div>
<div>
<label>
Ort:
</label>
<input type="text" value="MArkt Wald" name="ort" id="nos">
</div>
<div>
<label>
Telefon:
</label>
<input type="text" value="" name="telefon" id="nts">
</div>
<div>
<label>
eMail:
</label>
<input type="text" value="info#rudolfapotheke.de" name="email" id="nms">
</div>
<input type="hidden" value="115" id="ids" name="id">
<input type="button" value="Speichern" id="sst">
</form>
Update:
This is the mootools script based on the form you gave me that should work with your html:
$('sst').addEvent('click', function(event) {
var data;
event.stop();
var myInputEl = $$('#termin_edit input');
for(var i=0; i<myInputEl.length; i++){
if(i == 0)
data = myInputEl[i].name + "=" + myInputEl[i].value;
else
data += "&" + myInputEl[i].name + "=" + myInputEl[i].value;
}
myRequest.send(data);
});
Also add alert to your Request call back for the edit just to test if the ajax worked:
onSuccess: function(responseText) {
alert("done! " + responseText);
},
onFailure: function() {
alert("failed");
}
On the php side create a new PHP file and put the following in it and have ajax target it:
<?php
print_r($_POST);
?>
The Ajax should return the $_POST array in the alert box.

Categories