The news feed on the sites dashboard I'm working on has multiple items from different users; and can also be commented on. However, whenever you write a comment under each post, it only posts to the post at the top of the feed (the most recent one). Comments are posted instantly by pressing the enter key, which then runs this JS code which is on the index.php page.
$(function(){
$('#comment_body').live( 'keypress' , function (e) {
var boxVal = $(this).val();
var sendTo = $('#to_id').val();
if ( e.keyCode == '13' ) {
e.preventDefault();
$.post( 'instantcom.php' , { 'comment_body' : boxVal , 'activity_id' : sendTo } , function () {
// reload data or just leave blank
} );
$('#comment_body').val('');
}
} );
});
Then, the HTML for the comment box on each post is as follows:
<p align="center" style="height:45px;">
<input type="text" name="comment_body" id="comment_body" style="margin-top:12px;border:1px solid blue !important;width:329px;height:21px;" />
<span class=" glyphicons-icon camera" style="position:relative;bottom:50px;left:155px;"></span></p>
<input name="type" type="hidden" value="a" />
<input name="activity_id" id="to_id" type="hidden" value="' . $act_item_id . '" />
The ' . $act_item_id . ' is just a PHP variable which contains the unique ID of the status update.
So then, any ideas as to why comments are only posting to the most recent posts instead of the ones they're meant to post to?
You're using an id to identify which post you're commenting against? to_id right? Well, that's an id on the page, id's should be unique to the page.
Related
I have this strange issue, which is hard for me to describe to be honest.
For testing purposes I have set up a SQL db containing id (autoincrement), first name, last name.
I have 2 entries there.
I call the db and list the entries in inputs like this:
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<div id='$id'>
<form method='post'>
<p>ID: <input type='text' name='id' id='id".$id."' value='$id' /></p>
<p>New first name: <input type='text' name='fname' id='fname".$id."' placeholder='$fname' /></p>
<p>New last name: <input type='text' name='lname' id='lname".$id."' placeholder='$lname' /></p>
<input type='submit' name='update' class='update' value='ID = $id' />
</form>
</div>";
}
Works perfectly fine and I get a page with both entries and a button to update them.
I am updating them with this function
$('.update').click(function(){
var row = $(this).parent().parent().attr('id'); // I've stored the SQL id in the parent div
// construct the input ids so i know where I am getting the data from
var idSource = '#id'+row;
var fnameSource = '#fname'+row;
var lnameSource = '#lname'+row;
// store the input values in variables
var id = $(idSource).val();
var fname = $(fnameSource).val();
var lname = $(lnameSource).val();
// use ajax to update sql table
$.ajax({
url : 'aiai.php',
method : 'post',
data : {id: id, fname: fname, lname: lname},
success: function(response){
console.log(response);
}
});
});
I am doing this so that every entry can be edited & updated on it's own.
An while this basically working I am getting a strange lag.
Example:
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am
getting the old value again
When I refresh the page I get the name update I just saved
Lag continues until I refresh the page
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am getting the old value again
When I refresh the page I get the name update I just saved.
Lag continues until I refresh the page.
It's like that info gets cached in the browser.
BUT, and this confuses me:
When I hardcode the inputs where I am calling the values from, everything works perfect.
So when I use
var id = $('#id2').val();
... instead of
var id = $(idSource).val();
... I am not experiencing this lag.
Anyone got an idea what I am doing wrong?
I'm currently implementing a feature that somebody can add addresses on my page. He can do this via a simple form. What I have now (to print the addresses) is:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: {{$address->name}}<br/>
Straße: {{$address->street}}<br/>
PLZ: {{$address->plz}}<br/>
Ort: {{$address->city}}<br/>
<a type="button" class="btn btn-info" href="/editAddress/{{$address->id}}">Bearbeiten</a>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
The variable addresses is passed into the view from the controller.
What I'm trying to achieve now, is that the user can simply click on one of those address parts, like name, straße, plz and ort, and it's converted to an input field, so the value can be changed. Then, when leaving the focus (so clicking somewhere else (or maybe add a save button next to it)), the new data has to be sent to the controller by ajax (the request itself should be no problem then). But: How can I convert it to an input field and how can I then convert it back and react to it (to then send the ajax request)?
I searched in the internet, but didn't find something...
Edit: found a fiddle here (http://jsfiddle.net/yXcZG/3) that does nearly what I want, but I have the problem, that it doesn't seem to keep the format, 1. it has much more space between the lines and: when clicking on it to edit, the input field jumps to the bottom of the page and doesn't stay on the same position. Also I just want the variables to be editable, not the text before the :.
So this is what I tried: (of course the AJAX thing is still missing, but first the other thing has to work)
In JS:
$(document).on('click', '.editableText', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var input = $('<input />', { 'type': 'text', 'id': id, 'class': 'editableText', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var input = $('<p />', { 'id': id, 'class': 'editableText', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
HTML:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: <span id="addressName{{$address->id}}" class="editableText">{{$address->name}}</span><br/>
Straße: <span id="addressStreet{{$address->id}}" class="editableText">{{$address->street}}</span><br/>
PLZ: <span id="addressPLZ{{$address->id}}" class="editableText">{{$address->plz}}</span><br/>
Ort: <span id="addressCity{{$address->id}}" class="editableText">{{$address->city}}</span><br/>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
Edit2: Found this answer on stackoverflow too (https://stackoverflow.com/a/6814092/3375021), so use contenteditable, but I have the problem, that I on blur neither know, which address should be changed in the database, nor which part of the address..
If you're looking for a jQuery working solution you can go with this
JsFiddle example
You have a listener for when you click an element that is editable, it'll take the value of it and put it inside an input.
After you blur you can take this value and do whatever you want with it..
Here is the javascript (jQuery) part.
$(function(){
$('body').on("click", ".changeable", function(e){
var text = $(this).text();
$(this).html("<input type='text' class='input-editable' value='" + text + "'>");
$(this).find('input').focus();
});
$('body').on("blur", ".input-editable", function(e){
var text = $(this).val();
$(this).parent().html(text);
console.log("Value changes to: " + text);
});
});
I think you should be using <?php echo $variable; ?> instead of blade {{$variabl}}
If you going to store a html tags or js into your database then you need to not use blade to echo it, you should use php simple echo function instead
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >
What I want to be able to is on button click I want to check a Server-Side directory for the existence of certain files.
If they exist I wish to display a checkbox corresponding to that file.
So far I have managed to use PHP and AJAX to check if the files exist or not and write to and array: 1 if the file exists, and a 0 if not.
Now...what I need to do at this stage is call upon this array, from my PHP file, or write this array to a div on my main HTML page. However when I go to echo it navigates away from my Main.html, opening a new page and writing on that.
Big question is can I write the array on my main html page from my PHP_Function.php file.
I have the following HTML code:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
<form action="available_evidence">
<input type="checkbox" name="vehicle" value="Bike"> Facebook<br>
<input type="checkbox" name="vehicle" value="Car" checked> Facebook Messenger<br>
<input type="checkbox" name="vehicle" value="Bike"> Twitter<br>
</form>
With the following array within PHP_function.php file:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
foreach ($IfPresentArray as $value) {
echo "$value<br />\n";
}
I am very new to PHP and HTML, and I have been banging my head off the wall with this for a while now.
Any help would be greatly appreciated.
You are using AJAX so all your communication will need to go back and forth over that medium. In brief, your PHP script (the one called by ajax) will echo JSON values (typically created by json_encode($myarray)) and this will then be available to your javascript over on your client-side.
A quick google for "jquery ajax json example" should get you some good, helpful ideas of how it fits together.
Here's the client-side from one of those google links above - note the .done part
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
var button = $(this).val();
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
})
.done(function(data) { // Variable data contains the data we get from serverside
$('#wines').html(''); // Clear #wines div
if (button == 'all') { // If clicked buttons value is all, we post every wine
for (var i in data.red) {
$('#wines').append('Red wine: ' + data.red[i] + '<br/>');
}
for (var i in data.white) {
$('#wines').append('White wine: ' + data.white[i] + '<br/>');
}
}
else if (button == 'red') { // If clicked buttons value is red, we post only red wines
for (var i in data) {
$('#wines').append('Red wine: ' + data[i] + '<br/>');
}
}
else if (button == 'white') { // If clicked buttons value is white, we post only white wines
for (var i in data) {
$('#wines').append('White wine: ' + data[i] + '<br/>');
}
}
});
return false; // keeps the page from not refreshing
});
});
</script>
You can store your array inside a $_SESSION variable, but you'll have to use a session_start(); on both pages.
On your php page, use: $_SESSION['array'] = $array; and then on your main page retrieve the array by the inverse: $array = $_SESSION['array'];.
You can now use said array on your main page.
To retrieve a specific value: $value1 = $_SESSION['array'][0];
For further reference:
Array as session variable
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).
You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});
You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/
You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})