Update div on AJAX submit jQuery is updating all divs - php

I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>

You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...

Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")

Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?

Related

Ajax get dynamic id for the submit button of the form PHP MySQL

I have a form in PHP & MySQL and I want to submit it with AJAX.
I Have similar data so I have put these data in a foreach loop.
The problem is that when I try to submit the first row data it all goes well but it changes the data in all rows. and when I try to submit other data except the first row it doesn't submit at all.
I think the problem is because the submit button always gets the same id and therefore goes to the first row always.
I don't know how to get the value in Ajax.
Here goes the code:
//php form
<?php
$pid = $_GET['pid'];
include('config.php');
$timeline_query="SELECT * FROM timeline_table WHERE pid=$pid";
$result_timeline=mysqli_query($conn,$timeline_query);
if(!$result_timeline){
echo "Error: " . $conn->error;
}
$timelines=array();
while($row_timeline=mysqli_fetch_assoc($result_timeline)){
$timelines[]=$row_timeline;
}
?>
<?php
$x = 0;
foreach ($timelines as $timeline):?>
<div class="card">
<div class="card-header" id="heading<?php echo $x; ?>">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse<?php echo $x; ?>" aria-expanded="true" aria-controls="collapse<?php echo $x; ?>">
<?php echo $timeline['timeline_title'];?>
</button>
</h5>
</div>
<div id="collapse<?php echo $x; ?>" class="collapse" aria-labelledby="heading<?php echo $x; ?>" data-parent="#accordion">
<div class="card-body">
<form id="register_form">
<input type="text" id="tid" name="tid" value="<?php echo $timeline['tid']; ?>"/>
<textarea class="form-control" rows="4" id="timeline_description" name="timeline_description"><?php echo $timeline['timeline_description'];?></textarea>
<input id="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</div>
<?php $x++; endforeach;
// ajax function
$(document).ready(function(){
$("#submit").click(function(){
var timeline_description = $("#timeline_description").val();
var tid = $("#tid").val();
alert(timeline_description);
alert(tid);
// Returns successful data submission message when the entered information is stored in database.
// var dataString = 'timeline_description='+timeline_description+'&pid='+ pid + '&tid='+ tid +;
var dataString = 'timeline_description='+timeline_description;
alert(dataString);
if(timeline_description=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "process.php?tid"=+tid,
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
//process.php
<?php
include('config.php');
$tid=$_GET['tid'];
if( $_POST['timeline_description']==NULL ){ $timeline_description=''; }
else { $timeline_description=$_POST['timeline_description']; }
$query_timeline = "UPDATE timeline_table SET
timeline_description='$timeline_description' WHERE tid=$tid ";
$result=mysqli_query($conn,$query_timeline);
if(!$result){
echo "Error: " . $conn->error;
}
?>
Any idea?
Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.
In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.
Instead of
var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();
try to get values in this way.
var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();
I see there a problem with Yours inputs id - <input type="text" id="pid" - this is in foreach, so You have multiple elements with same id. So var pid = $("#pid").val(); will return You always a value of first found element. Try to use arrays:
<input type="text" id="pid[$pid]" name="pid[$pid]" value="<?php echo $pid ?>"/>
<input type="text" id="tid[$pid]" name="tid[$pid]" value="<?php echo $timeline['tid']; ?>"/>
Please remember one thing: id of any element in html PAGE (whole document) must be unique.

Can only delete first row with Ajax

I have a page that prints out rows from a mysql table. I'm trying to create an ajax form that allows users to delete rows but for some reason I can only seem to get it to delete the very top row that is printed out.
I've only included the script that might be needed here and left out the database query(which works fine).Firebug only shows my form being posted when I click the top row of results, any other rows it does nothing. Can anyone tell me what's wrong? Thanks
My_reviews.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
//Delete Review
$(document).ready(function(){
$("#deleteReview").click(function (e) {
e.preventDefault();
var username=$("#username").val();
var film_id=$("#film_id").val();
var id=$("#id").val();
$.post('ajax_deleteReview.php', {username: username, film_id: film_id, id: id},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
</head>
<div class="container">
<div id="message"></div>
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
<p>
</p>
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
echo'
<p>
'.$review. '
</p>
<form>
<input type="hidden" id="username" name="username" value="'. $username.'">
<input type="hidden" id="film_id" name="film_id" value="'.$film_id .'">
<input type="hidden" id="id" name="id" value="'.$id .'">
<button type="submit" id="deleteReview" class="btn btn-danger btn-xs pull-right">delete</button>
</form>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js">
</script>
</div>
</body>
</html>
ajax_deleteReview.php
<?php
//include db configuration file
include_once("ajax_review/config.php");
//Configure and Connect to the Databse
$username=$_POST['username'];
$film_id=$_POST['film_id'];
$id=$_POST['id'];
//Delete Data from Database
$delete_row = $mysqli->query("DELETE * FROM `user_reviews` WHERE id='$id' AND username='$username' AND film_id='$film_id' LIMIT 1");
if($delete_row){
echo '<img src="images/tick_large.png"/>';
}
else{ echo "An error occurred!"; }
?>
You have duplicated IDs in inputs, so jQuery returns the 1st occurrence of input.
You can add film_id, id and film_name to the <a> link with a data attribute, then read with jquery.
JavaScript function for ajax request need to be assigned to the class:
$(".deleteReview").click(function (e) {...
and
<a class="deleteReview"....
so with this you eliminate duplicate IDs in HTML code.

How to get the values from a submitted do...while form

I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:
But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.
The code is as follow:
<script>
function submitForm() {
$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}});
return false;
}
</script>
</head>
<body>
<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
<form id="MyJobsForm" onsubmit="return submitForm();">
<?php do { ?>
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</form>
</li>
</ul>
<div id="myJobs_Right">
<div class="form_result"> </div>
</div>
</body>
The jQuery-ajax-demo.php page looks like this:
<?php
if(isset($_POST['name'])) {
$name = $_POST['name'];
?>
Your Name Is: <?php echo $name; ?><br />
<?php
die();
}
?>
If you have to do it this way, then you might try creating a new form for each button:
<?php do { ?>
<form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
</form>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:
function submitForm(form) {
var $form = $(form);
$.ajax({
type:'POST',
url: 'jQuery-ajax-demo.php',
data:$form.serialize(),
success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}
});
return false;
}

passing id name on click using ajax to php

i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}

Posting search value via html button

I am searching for a possibility to replace the lowre input text field with a button like: <input type="button" class="button" name="search" value="Urban" onclick="">.
HTML CODE:
<form method="post" action="search.php" id="search_form">
<input type="text" name="search" value="<?php echo $_POST['search']; ?>" class="search_sounds"/>
<input type="submit" value="" class="submit" />
</form>
The whole script is supposed to search the sounds of a database:
PHP CODE:
<?php if(isset($_POST['search']) && !empty($_POST['search']))
{
include('searchfunction.php');
if(count($data) > 0)
{
?>
<script type="text/javascript">
$(document).ready(function(){
var description = '';
var myPlaylist = [
<?php
echo(implode(',', $data));
?>
];
$('#main').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description, }
);
});
</script>
<?php
}
else
{
echo ('No sounds found.');
}
}
?>
add an id element to your button, like this (I removed the onclick="" code)
<input type="button" class="button" name="search" value="Urban" id="search_button">
Then use some simple jQuery:
$('#search_button').click(function() {
$('#search_form').submit();
});

Categories