JAVASCRIPT WITH PHP

JAVASCRIPT WITH PHP - Hallo sahabat Tutorials, Pada Artikel yang anda baca kali ini dengan judul JAVASCRIPT WITH PHP, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : JAVASCRIPT WITH PHP
link : JAVASCRIPT WITH PHP

Baca juga


JAVASCRIPT WITH PHP

Client-side JavaScript :

Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
  • Language − This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
  • Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language="javascript" type="text/javascript">
JavaScript code
</script>

Your First JavaScript Script

Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document
.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result −
Hello World!



(1)Variable example in javascript:
<html>
                <head>
               
                <script> 
                var x = 10;           
                var y = 20; 
                var z=x+y; 
                document.write(z); 
                </script> 
</head>
<body>
</body>
</html>

(2)Global variable example:

<html>
                <head>
                <script> 
                var data=200;//gloabal variable 
                function a(){ 
                document.writeln(data); 
                } 
                function b(){ 
                document.writeln(data); 
                } 
                a();//calling JavaScript function 
                b(); 
                </script>
                </head>
                <body>
                </body>
                </html>

(3)simple array example:

<script>
               
                var emp=["Sonoo","Vimal","Ratan"];

document.write(emp[0]+"<br>");
document.write(emp[1]+"<br>");
document.write(emp[2]);

</script>   
          
(4)New keyword using array example:

<script> 
                var  i; 
                var emp = new Array(); 
                emp[0] = "Arun"; 
                emp[1] = "Varun"; 
                emp[2] = "John"; 
                document.write(emp[0]+"<br>");
                document.write(emp[1]+"<br>");
                document.write(emp[2]+"<br>");
</script> 


(5)array  constructor :

<script> 
                var  emp=new Array("Jai","Vijay","Smith"); 
               
                document.write(emp[0] + "<br>"); 
                document.write(emp[1] + "<br>");
                document.write(emp[2] + "<br>");
                 
                </script> 

(6)function example:

<script> 
                function msg(){ 
                alert("hello! this is message"); 
                } 
                </script> 
                <input type="button" onclick="msg()" value="call function"/>

(7)argument function:

<script> 
                function getcube(number){ 
                alert(number*number*number); 
                } 
                </script> 
                <form> 
                <input type="button" value="click" onclick="getcube(4)"/> 
                </form> 

(8)return  function:

<script> 
                function getInfo(){ 
                return "hello javatpoint! How r u?"; 
                } 
                </script> 
                <script> 
                document.write(getInfo()); 
                </script> 

(9)alert example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

</body>
</html>

(10)confirm example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a confirm box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x;
    if (confirm("Press a button!") == true) {
        x = "You pressed OK!";
    } else {
        x = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

(11)Prompt  example:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var person = prompt("Please enter your name", "Harry Potter");
   
    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! How are you today?";
    }
}
</script>

</body>
</html>

(12)if example:

<html>
   <body>
     
      <script type="text/javascript">
        
            var age = 20;
        
            if( age > 18 ){
               document.write("<b>Qualifies for driving</b>");
            }
     
      </script>
     
     
   </body>
</html>

(13)if else example:

<html>
   <body>
  
      <script type="text/javascript">
        
            var age = 20;
        
            if( age > 18 ){
               document.write("<b>Qualifies for driving</b>");
            }
           
            else{
               document.write("<b>Does not qualify for driving</b>");
            }
        
      </script>
      </body>
</html>

(14)else if example :

<html>
   <body>
   <script type="text/javascript">
        
            var book ="history";
            if( book == "history" ){
               document.write("<b>History Book</b>");
            }
        
            else if( book == "maths" ){
               document.write("<b>Maths Book</b>");
            }
        
            else if( book == "economics" ){
               document.write("<b>Economics Book</b>");
            }
        
            Else
            {
               document.write("<b>Unknown Book</b>");
            }
        
      </script>
 </body>
<html>



(15)switch  example :

<html>
   <body>
  
      <script type="text/javascript">
        
            var grade='B';
            document.write("Entering switch block<br />");
            switch (grade)
            {
               case 'A': document.write("Good job<br />");
               break;
           
               case 'B': document.write("Pretty good<br />");
               break;
           
               case 'C': document.write("Passed<br />");
               break;
           
               case 'D': document.write("Not so good<br />");
               break;
           
               case 'F': document.write("Failed<br />");
               break;
           
               default:  document.write("Unknown grade<br />");
                                                   break;
            }
                                               
</script>
 </body>
</html>

(16)for loop example:

<html>
   <body>
     
      <script type="text/javascript">
    
            var count;
            document.write("Starting Loop" + "<br />");
        
            for(count = 0; count < 10; count++){
               document.write("Current Count : " + count );
               document.write("<br />");
            }
        
            document.write("Loop stopped!");
   
      </script>
     
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

(17)while loop example:

<html>
  <body>
   <script type="text/javascript">
        
            var count = 0;
            document.write("Starting Loop ");
        
            while (count < 10){
               document.write("Current Count : " + count + "<br />");
               count++;
            }
         document.write("Loop stopped!");
         </script>
      </body>
</html>

(18)do while :

<html>
   <body>
   <script type="text/javascript">
        
            var count = 0;
           
            document.write("Starting Loop" + "<br />");
            do{
               document.write("Current Count : " + count + "<br />");
               count++;
            }
           
            while (count < 5);
            document.write ("Loop stopped!");
        </script>
     </body>
</html>

(19)Simple Object    Example   :

<script> 
                emp={id:102,name:"Shyam Kumar",salary:40000} 
                document.write(emp.id+" "+emp.name+" "+emp.salary); 
                </script> 





 (20)object using new keyword:

<script> 
var emp=new Object(); 
emp.id=101; 
emp.name="Ravi Malik"; 
emp.salary=50000; 
document.write(emp.id+" "+emp.name+" "+emp.salary); 
</script>

(21)Object  Constructor example:
                <script> 
                function emp(id,name,salary){ 
                this.id=id; 
                this.name=name; 
                this.salary=salary; 
                } 
                e=new emp(103,"Vimal Jaiswal",30000); 
                document.write(e.id+" "+e.name+" "+e.salary); 
                </script>


(22)addition of two number using form using JavaScript :

n1<input type = "number" id = "n1" value=15 />
n2<input type = "number" id = "n2" value=20 />

<p>Sum?</p>

<button onclick="sum()">Try it</button>
<p id="demo2">Result?? </p>


<script type="text/javascript">
 function sum()
{
    var fn, ln;
    fn = parseInt(document.getElementById("n1").value);
    ln = parseInt(document.getElementById("n2").value);
    result =  (fn+ln);
    document.getElementById("demo2").innerHTML = result;
}
</script>


Another example for addition  using name  of  field  using  parseInt() function :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="Javascript">
function showResult()
{
a = document.Order.Mortgage.value;
b = document.Order.Debt.value;
c = document.Order.Income.value;
d = document.Order.Years.value;
Total = document.Order.Total.value = parseInt(a) + parseInt(b) + parseInt(c)+parseInt(d);
}
</script>
</head>
<body>
<pre>
<form name="Order" action="" method="POST" enctype="text/plain"><br>
<font color=000099 size="4">Mortgage</font>   <input type=text name="Mortgage"   size="20"><br>
<font color=000099 size="4">Debt</font>   <input type=text name="Debt"   size="20"><br>
<font color=000099 size="4">Income</font>     <input type=text name="Income" size="20"><br>
<font color=000099 size="4">Years</font>      <input type=text name="Years"   size="20"><br>
<font color=000099 size="4">Total</font>      <big>$</big><INPUT maxLength="8" size="7" name="Total"><br>
<INPUT name="Submit"  type="button" class="style2" onclick="javascript:showResult();" value="Submit">
</form>
</pre>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------
Same  example for addition  using name  of  field  using  parseFloat() function :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="Javascript">
function showResult()
{
a = document.Order.Mortgage.value;
b = document.Order.Debt.value;
c = document.Order.Income.value;
d = document.Order.Years.value;
Total = document.Order.Total.value = parseFloat(a) + parseFloat(b) + parseFloat(c)+parseFloat(d);
}
</script>
</head>
<body>
<pre>
<form name="Order" action="" method="POST" enctype="text/plain"><br>
<font color=000099 size="4">Mortgage</font> <input type=text name="Mortgage"   size="20"><br>
<font color=000099 size="4">Debt</font><input type=text name="Debt"   size="20"><br>
<font color=000099 size="4">Income</font> <input type=text name="Income" size="20"><br>
<font color=000099 size="4">Years</font><input type=text name="Years"   size="20"><br>
<font color=000099 size="4">Total</font><big>$</big><INPUT maxLength="8" size="7" name="Total"><br>
<INPUT name="Submit"  type="button" class="style2" onclick="javascript:showResult();" value="Submit">
</form>
</pre>
</body>
</html>

--------------------------------------------------------------------------------------------------------------------------
another exmaple for simple calculator using else-if:

<form name=myform>

n1<input type = "number"  name= "n1" value=15 />
n2<input type = "number"  name= "n2" value=20 />

<select  name=cal>

<option value=1>Add</option>
<option value=2>sub</option>
<option value=3>Division</option>
<option value=4>Multiplication</option>
</select>



<button onclick="sum()">Try it</button>

</form>


<script type="text/javascript">


function sum()

{

var  n1=parseInt(document.myform.n1.value);

var  n2=parseInt(document.myform.n2.value);

if(document.myform.cal.value=="1")

{

alert(parseInt(n1+n2));


}



else if(document.myform.cal.value=="2")


{


 alert(parseInt(n1-n2));



}


else if(document.myform.cal.value=="3")


{


 alert(parseInt(n1/n2));


}



else if(document.myform.cal.value=="4")


{


 alert(parseInt(n1*n2));


}


else 


{


alert('no cal');


}


 }



</script>

--------------------------------------------------------------------------------------------------------------------------

another exmaple for simple calculator using switch :
========================================================================
<form name=myform>
n1<input type = "number"  name= "n1" value=15 />
n2<input type = "number"  name= "n2" value=20 />

<select  name=cal>
<option value=1>Add</option>
<option value=2>sub</option>
<option value=3>Division</option>
<option value=4>Multiplication</option>
</select>



<button onclick="sum()">Try it</button>
</form>


<script type="text/javascript">

function sum()
{

var  n1=parseInt(document.myform.n1.value);
var  n2=parseInt(document.myform.n2.value);
   var cal=parseInt(document.myform.cal.value);
   switch(cal)
   {

   case  1:

alert(parseInt(n1+n2));
break;
case 2:

alert(parseInt(n1-n2));

break;


case 3:

 alert(parseInt(n1/n2));

break;


case 4:

 alert(parseInt(n1*n2));

break;

default:



alert('no cal');

break;

 }

 }


</script>


========================================================================
-------------------------------------------------------------------------------------------------------------------------
From validation code in javascript :



<html>
<head>
<title>
Simple Client Side Validation
</title>
<script  type="text/javascript">

function  valid()
{

if(myform.name.value=="")
{

alert("enter your name");

return false;

document.myform.name.focus();
}


if(myform.contact.value=="")
{
alert("enter your contact");
return false;
document.myform.contact.focus();
}
if(isNaN(myform.contact.value))
{

alert("enter numeric value in contact");
return false;
document.myform.contact.focus();
}

if(myform.city.value=="")
{

alert("enter your city");

return false;

document.myform.city.focus();

}

if(myform.email.value=="")
{

alert("enter your email");

document.myform.email.focus();

return false;

}



if(myform.address.value=="")
{

alert("enter your address");

document.myform.address.focus();

return false;

}

var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(!myform.email.value.match(mailformat))

{
alert("You have entered an invalid email address!");
document.myform.email.focus();
return false;
}


return true;
}

</script>

</head>
<body>
<form name="myform"  action="submit.php" method="post"  onsubmit="return(valid());" >
Name <input type="text" name="name"  >
contact<input type="text" name="contact">
city<input type=text   name="city">
email<input type=text name="email">
address<input type=text name="address"">
<input   type=submit     name=submit>
</form>
</body>
</html>


========================================================================
NOW  LEARN HOW TO USE JAVASCRIPT  WITH PHP SCRIPT :
========================================================================
(1)write code for form .php  file given below:


<form action="form.php"   method="post">
name <input type=text name=name>
city <input type=text name=city>
<input type=submit name=submit value=submit>
</form>
<?php
if(isset($_POST['submit']))
{
$con=mysql_connect("localhost","root","");
mysql_select_db("abhi",$con);
$name=$_POST['name'];
$city=$_POST['city'];
$sql="insert into myrecord(name,city)values('$name','$city')";
$result=mysql_query($sql) or die(mysql_error());
if($result)
{
echo "<script type='text/javascript'>alert('record added successfully')</script>";
echo "<script type='text/javascript'>window.location='dashbord.php'</script>";
}
else
{
echo "<script type='text/javascript'>alert('Failed registration try again!')</script>";
echo "<script type='text/javascript'>window.location='form.php'</script>";
}

}

?>

(2)write code for   dashboard.php file:

<?php

echo "welcoem to dasboard";

?>

========================================================================
NOW  LEARN HOW TO USE  YES NO CONFIRMATION CODE OF JAVASCRIPT  WITH PHP SCRIPT TO ASK FOR CONFIRMATION BEFORE DELTE A RECORD :
========================================================================
(1)create   a  database   ajax  and then create a table users  :

SQL>

CREATE TABLE  users (
user_id INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
first_name VARCHAR( 25 ) NOT NULL ,
last_name VARCHAR( 25 ) NOT NULL ,
user_city VARCHAR( 45 ) NOT NULL

);

insert at least  5 records into your table and then 

(2)then write code  for  index.php file:

<html>
<head>
<script type="text/javascript">
function delete_id(id)
{
     if(confirm('Sure To Remove This Record ?'))
     {
        window.location.href='index.php?delete_id='+id;
     }
}
</script>
</head>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax");
$sql_query="SELECT * FROM users";
$result_set=mysql_query($sql_query);
?>
<table align="center">
    <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>City</th>
    <th>Delete</th>
    </tr>
    <?php
 if(mysql_num_rows($result_set)>0)
 {
  while($row=mysql_fetch_row($result_set))
  {
   ?>
            <tr>
            <td><?php echo $row[1]; ?></td>
            <td><?php echo $row[2]; ?></td>
            <td><?php echo $row[3]; ?></td>
            <td align="center"><a href="javascript:delete_id(<?php echo $row[0]; ?>)"><img src="b_drop.png" alt="Delete" /></a></td>
            </tr>
            <?php
  }
 }
 else
 {
  ?>
        <tr>
        <th colspan="4">There's No data found !!!</th>
        </tr>
        <?php
 }
 ?>
 </table>
 <?php

 if(isset($_GET['delete_id']))
{
     $sql_query="DELETE FROM users WHERE user_id=".$_GET['delete_id'];
     mysql_query($sql_query);
     header("Location: index.php");
}


?>


now get understanding about above code:



following is the anchor link that call the below javascript function.

<a href="javascript:delete_id(<?php echo $row[0]; ?>)">Delete</a>

put the following javascript just above your closing </head> tag

<script type="text/javascript">
function delete_id(id)
{
     if(confirm('Sure To Remove This Record ?'))
     {
        window.location.href='index.php?delete_id='+id;
     }
}
</script>


window.location.href='index.php?delete_id='+id; This javascript object creates the QueryString like index.php?delete_id=any_value
and the rest of work is php if the querystring is set the selected row will be deleted using following php condition.


if(isset($_GET['delete_id']))
{
     $sql_query="DELETE FROM users WHERE user_id=".$_GET['delete_id'];
     mysql_query($sql_query);
     header("Location: index.php");
}





Important  Javascript and Jquery  Code for web development:

(1)how to make multiple preview of single  image:


(2)javascript code  for confirmation before delte and update: 


(3)how to pass image file  with text to php using Ajax:



(4)how to preview  form entered  value  in text:


(5)Drag and Drop  file  upload  :





Demikianlah Artikel JAVASCRIPT WITH PHP

Sekianlah artikel JAVASCRIPT WITH PHP kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel JAVASCRIPT WITH PHP dengan alamat link https://othereffect.blogspot.com/2016/05/javascript-with-php.html

0 Response to "JAVASCRIPT WITH PHP"

Post a Comment