I have a simple option for users to check the "title" or "username" for availability. The function runs the ttck.php and displays the appropriate alert. Problem is the function() will not reset to allow multiple checks without reloading the entire page.
function checkTitle() {
$.post('ttck.php', $(".pubttl").serialize(), function(data)
{ $('.tresult').html(data).delay(5000).fadeOut('slow'); });
}
<span class="udo" onclick="checkTitle()"> check title availability</span>
What am I not seeing here to reload/reset this event so users can check as many times as necessary?
EDIT: This is the PHP
if(empty($TITLE)) { echo 'Please enter a Title';}
else { $que=mysql_query("SELECT * FROM `pubs` WHERE TITLE='$TITLE'");
$result=mysql_num_rows($que);
if($result>0) { echo 'Sorry, Title is already published. Try an alternate'; }
else { echo 'Huzzah, your Title is Available!'; }}
There are a few extended parameters in this statement, but none that would effect the function.
Did you try this
<span class="udo" onKeyUp="CheckTitle()"> check title availilibilty </span>
in your earlier script you were trying to run the function by using an Onclick function, whereas this one will run as the person is keying in the title. Hope this is what you want.
Related
I got a html page with 2 forms which are using the same php script..
<?php
if ($conn) {
if (isset($_POST['form_student'])) {
if ($_POST['form_student'] == 'Send') {
if (!empty($_POST["Ime"]) && !empty($_POST["Prezime"]) && !empty($_POST["BrojIndeksa"]) && !empty($_POST["TipNastave"])) {
header('Location: forme.html');
echo "<script>alert('Processing data to sql.');</script>";
} else {
echo 'You didnt fill all fields!';
echo "<script>alert('You didn't fill all fields!');</script>";
}
}
}
if (isset($_POST['form_subject'])) {
if ($_POST['form_subject'] == 'Send') {
// same checks just like above with redirecting
// and displaying alert box
}
}
}
?>
First problem is when I don't fill all fields in, it does work and echo 'You didn't fill al fields!' but doesn't display alert box message, and it only doesn't work when I don't fill all fields. And I'm wonder how can I actually by processing php script, without redirecting to that php script page, show msg box on html page, is it possible with out ajax or jquery, or I should instead using html extension change into php, and do all checks there and avoid processing script into action=""?
That's because of the row ..
echo "alert('You didn't fill all fields!');";
Try this one instead ..
echo "alert(\"You didn't fill all fields!\");";
What you did wrong was that you had an apostrophe in the string and around the string. I don't know how to explain this but I simply made the two quotation marks to not conflict with the php echo.
Update:
Regarding the second question about the redirect and such. Could you explain it further because I don't understand a word?
I have an active session in my page using: $_session_start(); I want to hide part of my form and show another based on the users previous entries.
Basically I offer Direct Deposit and Paper Check I want to be able to have the user only see the fields required for them to complete previously (in signup so the values are already in the database)
Right now the database table is set up like this:
paper_check with a value of 1 (yes pay this way) or 0 (no pay this way)
and the same thing with direct deposit. I need a way to show/hide the fields associated with each based on the users previous selections.
I typed this up but it doesn't seem to do anything. Please help me!!!!! (The class names hide and show are in my css and working properly!)
<?php
if ($_SESSION['direct_deposit'] == 1)
{
$doc->getElementById('check_payable_to')->className+" hide";
}
else
{
$doc->getElementById('name_on_account')->className+" hide";
$doc->getElementById('check_payable_to')->className+" show";
}
?>
I don't see a className property in the PHP DOM library. It looks like this is the way to add a class to an element:
$doc->getElementById('check_payable_to')->setAttribute('class',
$doc->getElementById('check_payable_to')->getAttribute('class') . " hide");
Do you have error reporting enabled? It should be warning about the unknown property.
If you want to do this in Javascript instead of PHP, have your PHP do something like:
<script>
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1) {
/* Do what you want */
} else {
/* Do what else you want */
}
</script>
In your question you said "I have an active session in my page using: $_session_start();" You shouldn't use $_session_start(). It should be session_start() .
className+" hide" should be className .= " hide"
By wrapping each section in it's own div like so:
<div id="paperCheck class="show">
<!--Your Paper Check Information here-->
</div>
<div id="directDeposit" class="show">
<!--Your Direct Deposit Information here-->
</div>
And then by using javascript you are able to do the following:
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1)
{
document.getElementById('paperCheck').className ="hide";
}
else
{
document.getElementById('directDeposit').className ="hide";
}
I want to enable or disable a div according to the session if it starts with an user or a guest. I want to do something like this:
First, i will evaluate if it is user or not by doing this:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
?>
then in jquery, i would like to say:
$('.box').click(function(){ // labBox appears when box is clicked
if(<?php $guest?>)
$("#LabBox").hide();
else
$("#LabBox").show();
});
Question: how can i use my php boolean var $guest to disable or hide some elements of my website?
Do i have to do two distinct php files? one for users and other for guest (e.g, home.php and home_guest.php)?
you could do the alternative such as
<script>
var guest = '<?php echo $guest; ?>';
$('.box').click(function(){ // labBox appears when box is clicked
if(guest === "true") {
$("#LabBox").hide();
} else {
$("#LabBox").show();
}
});
</script>
This would simply allow you to pass the PHP value to a Javascript variable, in order for you to use it within the onClick.
Remember: everything that reaches the client can be manipulated. Therefore, if you send an hidden element (say, an hidden <div>) any tech-savvy user can, and will, easily make them visible.
You MUST perform the checks about the login/guest status in your PHP script, and don't rely on jQuery to assemble the page at client side (hey, after all, the user may have disabled javascript altogether!)
You don't need two pages (eg: home.php and home_guest.php) to render different content based on the user level. Just use appropriately session/cookies and different echos.
Use a hidden input, populated by PHP, which jQuery can grab:
<?php
echo "<input type=hidden id=guestcheck value=$guest/>"
?>
if ("#guestcheck").val()) {
}
I personally like this method because it allows me to check the source when debugging to find out where any errors may be (for instance you can plainly see in the source when viewing the page whether or not GUEST is true)
It depends on contents of those files. If the only difference is visibility of the block, it's more reasonable to do the check inline.
<?php if (isset($_SESSION['idUser'])) { ?>
$('.box').click(function() { $("#LabBox").show(); }
<?php } ?>
Personally I would do it in the HTML rather than the JS file...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$loggedin=true;
} else {
$loggedin=false;
}
?>
Then later on..
<?php if($loggedin===true){?>
<div>User is logged in</div>
<?php }else{?>
<div>Guest is viewing page</div>
<?php }?>
This means that the div for the user is not shown to the guest, whereas your currently solution only hides it from view (user could just use firebug/viewsource!
Why don't you just show/hide your div in the php depended on if they are a guest or not...
So...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
if($guest===true){
echo "<div></div>";
}
else{
//dont echo div
}
?>
PHP / server-side:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
// add #LabBox element from here to avoid junk/hidden elements for guests
}
?>
JQuery / client-side:
$('.box').click(function(){ // labBox appears when box is clicked
if (!<?php echo $guest?> && $('#LabBox').length > 0) {
$('#LabBox').show();
}
});
Then it is critical that any action requested by the user pass the "guest or not?" test before being granted from the server-side.
I am currently doing a project, and I want to know if it's possible if I could click an image then it will send a query to the database. since I am doing a project about Online menu. where I will click the image then there'll be query to be sent in the database, and after that the customers order wil appear in the side of the screen. is this possible? if so how ?
You really have several options of how you want to do this. The most basic being to surround your image in a link tag like so:
<image />
You can then either handle the click with an actual refresh. Or, you can handle it with ajax if you don't want the page to refresh.
Do your work on another php page.
If you need to do this through ajax. Let's suppose you want to load the content sent from the server in the div 'itemdetails'. You can specify this as the image tag(using jquery:
<img src="url/of/image" onclick="$('#itemdetails').load('http://yoursiteurl/items?id=itemid')">
The best way of doing that for me is using jquery like this:
Javascript:
function orderedSomething(id) {
$.post("ajaxOrder.php",{ orderID:id,rand:Math.random() } ,function(response) {
if(response=='ok') {
$("#alert").fadeTo(250,0.1,function() {
$(this).html('Your order is coming.').fadeTo(150,1);
});
} else {
$("#alert").fadeTo(250,0.1,function() {
$(this).html(response).fadeTo(150,1);
});
}
});
}
The php file ajaxOrder:
<?php
if($_POST['orderID']) {
$res = $query('check stock'); //Assuming that there is no info related to your table
if(mysql_num_rows($res)>0) {
$query('insert DB'); //Assuming that there is no info related to your table
echo 'ok';
} else {
echo 'Your order is out of stock';
}
}
?>
So your html should be:
<div id="alert"></div>
<img src="images/ice-cream.gif" onClick="orderedSomething(<?=$iceId?>)" style="cursor:pointer" />
I've been searching about deleting db entries in Codeigniter and I finally created a solution that I think is secure. I would really appreciate any feedback! I'm not sure if I'm doing this right..
Advantages:
Uses POST request
ID of entry to be deleted is
validated
Uses CSRF protection (automatically
generated by Codeigniter)
In my example I'm deleting user submitted links (a DB table row contains a link title, link URL, an link description).
HTML: Database entires are contained within a form. Each entry has a form button with the respective link id in the id attribute.
<?php echo form_open('profile/remove_link'); ?>
<?php echo form_hidden('link_id', ''); //value will be populated via jquery ?>
<ul id="user_links">
<?php foreach($query as $row): ?>
<li><?php echo $row->link_title; ?></li>
<li><?php echo auto_link($row->link_url, 'url', TRUE); ?></li>
<li><?php echo $row->link_description; ?></li>
<button type="submit" class="remove" id="<?php echo $row->link_id ?>" value="remove">Remove Link</button>
<?php endforeach; ?>
</ul>
</form>
JQUERY: When user clicks on the remove button, the respective link id is added to the the hidden text input named link_id.
$(document).ready(function(){
$('.remove').click(function() {
var link_to_remove = $(this).attr("id");
$("input[name=link_id]").val(link_to_remove);
});
});
Upon clicking a remove button, it sends the id of link to be removed to controller profile and function remove_link
function remove_link()
{
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'trim|required|xss_clean|max_length[11]|numeric'); //validate link id
if ($this->form_validation->run() == FALSE) //if validation rules fail
{
$this->load->view('profile/edit_links_view', $links_data);
}
else //success
{
$link_id = $this->input->post('link_id'); //get id of link to be deleted
$seg = 'user_links'; //used to redirect back to user links page
$this->Profile_model->links_delete($link_id, $seg); //send link id to model function
}
}
MODEL
function links_delete($link_id, $seg)
{
$this->db->where('user_id', $this->tank_auth->get_user_id());
$this->db->where('link_id', $link_id);
$this->db->delete('user_links');
redirect("/profile/$seg/");
}
If the ids are unique integers in your database, you could remove these rules:
trim|xss_clean|numeric
And add this one:
is_natural_no_zero
Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
The numeric rule allows some characters you probably don't want, like decimals and negative. Here's the source (one line):
return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
If for some reason you are echo'ing the input back in your HTML output before validating, or are just paranoid, then by all means: xss_clean it up. Otherwise it's not really needed, as I don't think there's any possible method of XSS attacks that only use a number.
Reference:
https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
http://ha.ckers.org/xss.html
Also, you might want to add a LIMIT 1 clause to your query, and definitely make sure to return a value (probably TRUE/FALSE) from your model so you know whether or not the query was successful, so you can give feedback to the user instead of assuming everything went well.
The only thing that I see wrong is that you don't validate who can and can't delete records. That's the only issue you should focus on. Permissions to check if the person sending the request of deletion is allowed to perform such operations. Other than that it's just a matter of preference.
I would suggest rewriting controller and model a bit to make the flow more logical and provide better performance:
controller:
function remove_link()
{
if ($this->input->post('link_id'))
{
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'is_natural_no_zero');
if ($this->form_validation->run())
{
$seg = 'user_links'; //do you really need to assign it to variable ??
$this->load->model('Profile_model');
if ($this->Profile_model->links_delete($this->input->post('link_id')) //send link id to model function
{
redirect('/profile/user_links'); // redirect user in controller and only when model returns true
}else{
// inform user about error somehow, eg. by setting session flashdata and redirecting back to /profile/user_links
}
}
} // else statement here was a mistake as in case of form_validation failure nothing happened
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
$this->load->view('profile/edit_links_view', $links_data);
}
model:
function links_delete($link_id)
{
$this->db->where('user_id', $this->tank_auth->get_user_id())
->where('link_id', $link_id)
->delete('user_links'); // you can chain methods without writing always $this->db->
return $this->db->affected_rows(); // returns 1 ( == true) if successfuly deleted
}
And as a side note in your jQuery code I suggest using $('#some_id') instead of $('input[name=XXXX]') - it saves some javascript code execution thus is faster