I want to make a availability button on my registration page - php

Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.

Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>

$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});

Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.

Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}

I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.

Related

Speeding up a form fill submission with email response in PHP?

I'm incredibly new to PHP, so I'll try and be as clear as possible. Through a bit of trial and error, I created a simple form on a website I manage where people can provide a few bits of information (about four lines total). In turn, I will receive an email using ()mail with the information, which I intend to use for remarketing purposes.
The problem? It takes a good 20-30 seconds for the person who filled out their info to be taken to the Thank You page. I still end up receiving the email, but people are definitely not going to wait around for the Thank You page to load before closing the window. This is obviously not good if I'm planning on tracking conversions.
Any suggestions? A friend suggested I set up a MySQL database to collect the info, but that's way beyond my level of expertise. Are there alternatives that can help?
Many thanks.
If the form submits to PHP you could use an AJAX script of which runs the PHP page. You can setup BeforeSend to show a div that simply says "Loading please wait..." and the user is more likely to wait. I'm not saying this is the best solution but its one.
AJAX Script:
<script>
$(document).ready(function() {
$('#submitBtn').click(function() {
var variable1=$("#variable1").val();
var variable2=$("#variable2").val();
var dataStr = 'variable1='+variable1+'&variable2='+variable2;
if($.trim(variable1).length>0 && $.trim(variable2).length>0) {
$.ajax({
type: "POST",
url: "process.php",
data: dataStr,
beforeSend: function(){ $("#submitBtn").val('Loading Please wait...');},
success: function(data){
if (data!="success") {
$("#submitBtn").val('Submit')
} else {
window.location.href = "http://example.com/thankyou";
}
}
});
} return false;
});
});
</script>
I've provided you with an AJAX example above. In the PHP script you simply need to get it to echo "success" if the email is sent. If the script ends and nothing is sent back or something else is echo'd then it will set the submit button back to "Submit".
I recommend you create a div below the submit button of which is empty by default or not visible but if the AJAX fails it is shown.

PHP send form data more than one form/pages

I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.

jquery update html with returned mysql data after POST

I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

jQuery/Ajax SQL live update via PHP help

I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.

Categories