Javascript and PHP in harmony - Search function - javascript

I am currently constructing a "datatable"-ish search function.
When a user inputs something into a search box, I'd like to update the div containing its values.
Currently I do this using this input field:
<input type="text" id="IdSearch" onkeyup="Search()" value="<?php echo $searchtext; ?>" onfocus="this.value = this.value;" name="zoeken" autofocus>
The onfocus="this.value = this.value; makes sure the selector is behind the values after the page is reloaded.
<script>
function Search() {
var x = document.getElementById("IdSearch").value;
window.location.href = "index.php?search" + x;
}
</script>
And then
if (isset($_GET['search'])) {
$searchtext = $_GET['search'];
echo $searchtext;
$sql = "SELECT blabla FROM blabla";
//execute sql statement and update the table now..
} else {
//generate the standard table
}
This works, it outputs a correct result, but it's sluggish. The page needs to reload every time you input a character.
So maybe, just maybe, I can somehow retrieve the searchbox' value every time a key pressed, and update my table that way?
I know PHP runs and then doesn't run again without a page reload. Maybe I can reload certain elements? I don't know.
Please, don't go all "PHP runs on the server" on me. I know, that's why I'm currently using this method. I am not even going to attempt to learn ajax in the timespan I have to finish this.
Any help is appreciated.

I am not even going to attempt to learn ajax in the timespan I have to finish this.
I'm afraid you'll have to either learn AJAX or submit to using iFrames. If you are going to use AJAX, there's some great libraries out there (JQuery or Zepto.js, or maybe qwest) that make it super easy to learn, quickly.
Maybe I can reload certain elements?
Yes! The other option, using iframes is pretty strongly frowned-upon by the web developer community as a whole, but it does exactly what you ask for. Check out MDN's information about scripting iframes. You can use the same properties as you do on window now, but it will still probably be sluggish and most likely quite annoying to work with as well.
So, if you want my advice: use AJAX. But it's your choice!

-Either you use a button " " to submit the search....
and remove the onkeyup="Search()"
<button type="submit">Search</button>
-Or you can try to post your form into an Iframe.... but still will be sluggish.
-The way to go is AJax : dynamically update the content while type-in.

use AJAX (like $.ajax) and create a php response in json. then recreate your content with a javascript template or an MVVM framework like angular.
Another way is return the part of the content than you need and inject with $('#mycontent').html(response).

try jquery $.post it's everything you're looking for.
http://api.jquery.com/jquery.post/

Related

How to readout Data from a formular?

I am doing an exercise for school. Task is to readout Data from a formular. Though I do not know much and I am stuck with the first Task. The result of the first task should be: "Your name has .... Characters." So basically if I enter a name in the text field and press the submit button it should give me the .length of the Name.
HTML:
<form>
<input id="Name" type="text" name="Name">
<input id="Ausgabe" type="submit" value="Ausgabe" onclick="ausgabe"()>
<p id="yournamehas" class="ptags">Your Name has:</p>
<p id="lname" class="ptags"></p>
<p id="Characters" class="ptags"> Characters</p>
</form>
Javascript:
function namelength() {
var Namee = document.getElementById('#Name').value.length
document.getElementById('lname').innerHTML = Namee
};
function ausgabe() {
$("#Ausgabe").on("click",function(){
{
document.getElementById("#Ausgabe").innerHTML =
namelength();
}
})
};
I seriously dont know whats wrong. Can you guys help me out?
var a = document.getElementById('Name');
function ausGabe(){
var b = a.value;
var name = document.getElementById('yournamehas').innerHTML = "Your Name has:" + " " +b;
var len = document.getElementById('Characters').innerHTML = "Characters" + " " + b.length;
}
<form>
<input id="Name" type="text" name="Name">
<input id="Ausgabe" type="button" value="Ausgabe" onclick="ausGabe()">
<p id="yournamehas" class="ptags">Your Name has:</p>
<p id="lname" class="ptags"></p>
<p id="Characters" class="ptags"> Characters</p>
</form>
As this is a school exercise, some pointers may be useful, to go along with the other answer which is a working solution...
jQuery vs Vanilla JS
You are using jQuery, which is a JavaScript library (a reusable bit of code) to make some jobs easier, especially regarding manipulation of elements in the browser (DOM elements). Way back, jQuery also did a more important job of 'normalising' the different browsers (Internet Explorer, Firefox, Opera, Netscape, etc.) before they adhered to the standards.
Nowadays jQuery is less vital as a normaliser, but still very handy for selecting elements and changing the styling, content, and handling events.
In your example you are doing some things the basic "Vanilla JS" way and some with jQuery. In a few places you have got things a bit mixed up and tried doing it a mix of ways, which won't work...
Referencing an element
by id
If you have an element such as <div id="myDiv"></div> then you can access it using Vanilla JS:
document.getElementById("myDiv");
or jQuery:
$("#myDiv");
Notice that you only provide the real id with getElementById, no hash.
by CSS selector
Another thing that jQuery did, which was amazing at the time, was that it allowed you to access DOM elements using the same selectors as CSS. That is why the jQuery version has a hash (#) because that is the CSS selector for "id=". Nowadays there is a Vanilla JS version of that which is widely supported:
document.querySelector("#myDiv"); // returns a single element
document.querySelectorAll("div"); // returns multiple div elements
Event handling
with jQuery
In your example you have used jQuery to attach some code to the click event of your button.
$("#Ausgabe").on("click",function(){
// blah
});
That's great and attaches your function to be run later when the button is clicked.
with element attributes (the bad way)
However, you have put that in another function which is explicitly called when you click the button, using the old-fashioned onclick attribute.
<input id="Ausgabe" ... onclick="ausgabe()">
Your jQuery event is not initially attached. It only becomes so when the onclick attribute handles the first click. So you have to click the button to attach an event handler to deal with clicking the button. Have you seen the film Inception? You need to make your mind up about which approach to take. You should definitely be attaching to the event rather than using onclick.
Vanilla JS
However, you can also do that with Vanilla JS:
document.getElementById("Ausgabe").addEventListener("click", function() { /* your code goes here */ });
Setting content
Vanilla JS
You have used the Vanilla JS approach for setting content of your element, which is great:
document.getElementById('lname').innerHTML = Namee;
jQuery
But that's another thing that jQuery provides a method for:
$("#lname").html(Namee);
Be consistent
Vanilla JS vs jQuery
To make it easier to both write and read your code, it is better to be consistent. Decide if you are going to use Vanilla JS or jQuery and then stick to it. Although you might use jQuery for some of the more difficult things even when using Vanilla JS (like adding or removing a CSS class name).
Semi-colons
JavaScript instructions are supposed to end with a semi-colon;
You don't always have to do it, and there are people who claim that you shouldn't unless absolutely necessary. But it does make code clearer to read because JavaScript is allowed to split across multiple lines. So the semi-colon tells your reader that you've finished the instruction. My advice is to always use them.
Quotes
JavaScript is flexible on the use of 'single' and "double" quotes. There are different opinions on this, and plenty of arguments for/against each, but it really doesn't matter which. However it is nicer if you stick to one approach:
var string1 = "Stick to one set of quotes";
var string2 = 'else your code will look weird';
var string3 = `even this is allowed in modern JS`;
var string4 = "But this one is BROKEN';
form submit buttons
One more thing, which also harkens back to 'the old days'...
When the world wide web was new there was no JavaScript and web pages were just a little better than plain text. The only interaction was by filling in a form and 'submitting' it back to the server.
If you have a <form> element which contains an <input type="submit"> button then that's what the browser expects to do. If you press that button it will submit the form. Nowadays that's actually quite rare!
If you use that arrangement then you might find that your page doesn't act the way you expect. Therefore it is safer to use non-submit buttons which don't have any special behaviour:
<input type="button" value="My non-submit button">
Good luck and enjoy
That's a lot of advice. Hopefully you can now see where you were going wrong before and have a better understanding of things.
I hope you enjoy coding. It's not scary and if you get properly good at it then you can have a good job in the future. But only go down that route if it really appeals to you. It's actually a horrible job if you spend most of your time on StackOverflow asking for help! ;)
TL;DR
If that was too long and you didn't want to read it then I advise you to not become a developer. Going into the details of how things work is a very important lesson that you never stop learning.

Should I use a submit button, a regular button, or a link to perform this action?

I've created a feed of comments which are retrieved from a MySQL database using a while statement in PHP. The code for this looks similar to the following:
<?
$con = mysqli_connect("localhost","username","password","database");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
$query = "SELECT * FROM table ORDER BY timestamp DESC LIMIT 0 , 1000";
$comments = mysqli_query($con, $query);
echo "<h1>Recent Posts</h1><br><br><hr>";
while($row = mysqli_fetch_array($comments, MYSQLI_ASSOC))
{
$comment = $row['comment'];
$timestamp = $row['timestamp'];
echo " <div class='card'>
<h3>Handle: $handle</h3><br />
<p>$comment</p><br /><br />
<img src='$file' style='width:60%; margin-left:20%; margin-right:20%; margin-top:5px; border-style:solid;'><br>
<p style='color: grey'>$timestamp</p><hr>
</div>
";
}
mysqli_close($con);
?>
I now wish to make it possible for users to upvote these posts. To do this, the following process would be used:
To do this, I suppose you would need to add something like one of the following to the echo part of the feed code:
<button onclick = "likefunction()">Upvote Comment</button>
<form name="$postid" method="post"><input type="submit" value="Upvote Comment"></form>
<a onclick = "likefunction()">Upvote Comment</a>
and then create the necessary function.
Which of these input types would be the correct one for this purpose?
Apologies if this is a rather basic question - I'm still learning the basics of all this.
There are many ways you can make this possible in professional and more organisable way , i always have used data attributes to perform javascript actions for these kind of functionalities , for example:
<button type="button" class="js_vote" data-type="upvote" data-post="32323">Upvote</button>
data-type can be used for upvote/downvote just to identify type of vote
data-post can be used for placing the post id and use it inside the javascript function to identify the post
and then inside javascript function it should look something like:
$('.js_vote').on('click',function(e){
var type = $(this).data('type');
var post_id = $(this).data('post');
// and from here perform the ajax request to send the data to the server.
});
or if you want to use onclick then you can do something like below:
Upvote
javascript
function js_vote(type,post_id){
// and from here perform the ajax request to send the data to the server.
}
Everyone has it's own different way of thinking and logics about implementing the layout / structure of it's own system , i have recommended you the simple and easy way in which you can better organise your data.
At last its your choice on how you want to design it .. Same attributes data attributes you can use them with anchor tags or even with div or span or any tag you want.
I guess it depends on whether you want to rely on javascript or the form submit for the action.
If you don't want to use Javascript to submit the form then I'd use the form method.
An alternative method would be using the button element in the form (as a button will submit the form by default) and the 'action' attribute:
<form name="$postid" action="./upvote-comment.php" method="post">
<button>Upvote Comment</button>
</form>
If you want/need to use javascript then it depends on whether you want to use the default button styles defined by browsers or the link style. Other than how it looks, I can't see any reason that using a link vs a button would behave any differently.
In summary:
Form is a non-javascript solution which is perfectly reasonable
button/link 'onclick' are equivalent to one another
It's probably easier to do it in javascript (as you can just manipulate the dom without reloading the page to change the counter).
Use button or <a> depending on which is easier to style ( their functionality will be the same). Use ajax inside that javascript function to do the logic.
Any of these elements would work, as long as you have some way of passing a meaningful identifier to your likefunction() which indicates the post that is being upvoted.
Both button and input[submit] are useful if you want to submit user data from form fields along with the event click. But in this case, I'm guessing this is unnecessary, since all the info you need can be injected into the dom attributes of the element being acted upon.
So it's really a matter of which element will be simplest for you to theme and integrate into your dom structure. Personally I would choose <a> as it requires the least syntax, but that's just me.

How to send a value from a search box to a URL?

I have a search box and I have no clue how to append the string that the user searches to url after a user clicks search.
How would this work?
I have a reference code but I want to know how to append the value that a user searches:
onclick="location.href = $(this).attr('href')+'?q1=Asustablet&x=70&y=14=siys';return false"
Here is my jsFiddle
yu can't use jquery inline. you can use its events like this:
$('#search-button-4').click(function(){
window.location.href = $(this).attr('href')+'?q1=Asustablet&x=70&y=14=siys';
});
DEMO
May I suggest using PHP as it will be much easier,
Add this inside PHP tags and set the variable for $user_search_input
header("Location: ".$_SERVER['REQUEST_URI']."?search=".$user_search_input);
I'm sorry if you needed a Javascript version but if not I highly suggest PHP for it has a lot of functionality being very powerful and has a lot of potential.

how to avoid fetching a part of html page which is being called inside another page?

I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();​
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.

Validation before Submitting on prompt page

I am trying to use some sort of script on prompt page using HTML Item, what i am trying to accomplish is after clicking finish button script checked if there is nothing left black. Nothing means any of the prompt/filter (text, prompt, date/time) and if it is than it doesn't go through.
Hope i made things clear.
Thank You
Personally I think the fastest and easiest way if you don't already have a js framework is jQuery validate... check out this page, see the examples and give this a go. I should think the description you've provided will be covered in the basic usage examples for this plugin.
http://docs.jquery.com/Plugins/Validation
If you don't want to use jQuery as in Ben's answer, you can use the form's onSubmit event:
<form id="datform" action="http://path.to/action.script" onsubmit="return isValidated()">
...
...
'</form>
You'll then use a javascript function, ala
<script type="text/javascript">
function isValidated(){
var so=false;
return so;
}
</script>
Personally, I prefer jQuery but this allows for some on-the-fly validation

Categories

Resources