Showing posts with label PHP Ajax. Show all posts
Showing posts with label PHP Ajax. Show all posts

Tuesday, 8 January 2019

PHP: Xajax and PHP: JavaScript without the pain Automatic for the people

While it shares LAMP honors with Perl and Python, though, PHP has become the most commonly used server-side platforms for Ajax and, of all the Ajax frameworks for PHP, Xajax is the most commonly used. If you are not familiar with JavaScript, which forms the basis of Ajax, but still would like to use Ajax with PHP, Xajax is the obvious choice because Xajax generates the required JavaScript for you.
In this Hands On, I’ll demonstrate a simple way to use Ajax and PHP within Xajax, with an Oracle database, while sidestepping the need for the problematic XMLHttpRequest.

Xajax backrounder

Xajax is an open source, object oriented, PHP class library that can be used with PHP scripts for server-side processing. Xajax is used to communicate asynchronously between a client- and a server-side application comprised of PHP scripts, and generates JavaScript wrapper functions so that PHP functions on the server can be accessed from a client application.
When a client application invokes the wrapper functions, a XMLHttpRequest object is initiated and a XMLHttpRequest object is sent to the server. On the server, the Xajax object receives the XMLHttpRequest and invokes the PHP functions corresponding to the JavaScript wrapper functions.
The default request type of PHP functions registered through Xajax is POST. The PHP functions return an XML response that is returned to the client application by the Xajax object. Based on the instructions in the XML response, the Xajax’s JavaScript message pump updates the content of the client input page. Xajax has a feature that, data is updated only if data has been modified.

Download and go

As Xajax is a PHP class library, first download and install PHP 5 and Apache2 HTTP server as explained in an earlier. The example application shall store and fetch data from Oracle database 10g. Therefore, enable the Oracle database extension in the php.iniconfiguration file.
extension=php_oci8.dll
Create an example database table in OE schema with a PHP script, Table.php, which is available in resources zip. Download Xajax0.2.4/0.2.5. Extract xajax_0.2.4.zip file to the C:/Program Files/Apache Group/Apache2/htdocs directory.

Thursday, 30 August 2018

Use jquery ajax to refresh PHP data on the same page


I have a PHP page with a mysql connection, a select query and then i'm building a table using PHP. If i wanted to use jQuery AJAX to refresh the data on a setInterval, on the same page, how would i go about doing that? (by the way i can do it to another PHP page but i've never done it if the PHP stuff is on the same page)



If you want to keep making ajax calls i suggest you do long polling, which basically means you have a script that is requesting content via ajax every given time, and it will verify every time if the content has been modified, if not it will wait again and make another call.

PHP: Unable to add data to the database using jquery ajax with php


I want to store data into database using jquery ajax using php but when i click on submit button a empty alert shows up and a message below submit button submitted succesfully but no data is added on my databse.i am at very beginer level in jquery and ajax...Any Help will be appreciated.


Here is my HTML
<form method="POST" >
        <pre>
            <label for="">Enter Post Topic</label><input type="text" id="txt_topic_name" name="txt_topic_name"><br>
            <label for="">Enter Detail</label><textarea id="txt_detail" name="txt_detail"></textarea><br/>
            <label for=""></label><input type="button" id="btn_submit" name="btn_submit" value="submit"><br>
        </pre>
    </form>
    <div id="results"></div>

And here is my javascript
$(document).ready(function(){
        $('#btn_submit').on('click',function(){
            var topic_name = $('#txt_topic_name').val();
            var detail     = $('#txt_detail').val();
            $.ajax({
                url   : "ajax/add_topic.php",
                type  : "POST",
                data  : {'txt_topic_name' : topic_name ,'txt_detail' : detail},
                success : function(data){
                    alert(data);
                    console.log(data);
                    $('#results').html("submitted succesfully");
                },
                error  : function(data){
                    // alert(data);
                    // console.log(data);
                }

            });
             // return false;

        });

     });

And PHP
if (isset($_POST['btn_submit'])) {
    mysql_connect("localhost","root","") or die("Could not coonnect");
    mysql_select_db("forum") or die("could not select db");

    $topic_name  = mysql_real_escape_string($_POST['txt_topic_name']);
    $detail = mysql_real_escape_string($_POST['txt_detail']);

    $sql    = "INSERT INTO Topics(name,detail)  VALUES('$topic_name','$detail')";
    $query  = mysql_query($sql);
    if ($query) {
        echo "Sucess";
    }
    else{
        echo "Failed";

    }

}


if (isset($_POST['txt_topic_name'])) {
    mysql_connect("localhost","root","") or die("Could not coonnect");
    mysql_select_db("forum") or die("could not select db");

    $topic_name  = mysql_real_escape_string($_POST['txt_topic_name']);
    $detail = mysql_real_escape_string($_POST['txt_detail']);

    $sql    = "INSERT INTO Topics(name,detail)  VALUES('$topic_name','$detail')";
    $query  = mysql_query($sql);
    if ($query) {
        echo "Sucess";
    }
    else{
        echo "Failed";

    }

}

To send php variables to the php file using jquery ajax?


I want to send a php variable $thread_id to php file using jquery ajax, so the php file can get all posts for $thread_id and echo it back to main file.


it doesnt work when i type:
$.get("ajaxcall_reply.php", thread_id: $thread_id, function(data) {
     $("#threads").html(data);
});

how should i type?

Do you know what $thread_id is outputting? Try putting it into a variable of its own and looking at the output before putting it in the get function. It might have symbols or things that are messing up your javascript syntax. Do you have an example output? Additionally the get method returns the XMLHttpRequest object (data) so you might want to look into setting the type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".

Call PHP Function using jQuery AJAX


I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.


function.php
function generateCode() {
//code here
}

function generateResult() {
//code here
}

How can I catch the function result using jQuery AJAX? I don't want to change function.php structure because it related to another pages.
Refer to using jquery $.ajax to call a PHP function, no answer can solve my problem. Thank You

To use PHP classes and functions nearly directly, you can use xajax.

My ajax call does not pull dynamic data from PHP / Mysql


I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. 
All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.

So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php file…
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url:  'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
    $('#ajax_content').html(response);
}
});

and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
    // AJAX request
    $answer = $_GET['answer'];
    $div_id=$answer;

    echo "div id is: " . $div_id . "<br/>";

mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database!       Please try again later.');
mysql_select_db($dbname);

$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");

while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}

}
?>

So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...

Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
    cache: false,
    type: 'GET',
    ...

The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.

Monday, 20 July 2015

PHP: Active and inactive users concept using php and Ajax

Today i have posted Active and inactive users script. This concept mostly using E-commerce website administrator access to check product available or not, delivery status, user block and activate like that similar concept related on this concept. Here i am using php with ajax let see the code.
Database
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `address` varchar(100) NOT NULL,
  `status` enum('0','1') NOT NULL DEFAULT '0'
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Html
 'btn-success': 'btn-danger'  - Checking class
 'Active' : 'Inactive'  - Checking Active or inactive value
 data="<?php echo $user['id'];?>"  - User id to pass javascript valuetat
$db= Database connection.

<?php $db= new mysqli('localhost','root','','mostlikers'); ?>
<html>
<head></head>
  <body>
  <table border="1">
  <tr>
  <th>#</th>
  <th>name</th>
  <th>email</th>
  <th>Action</th>
  </tr>
  <?php $sql=$db->query("Select * from user");
        foreach ($sql as $key => $user) {
  ?>
  <tr>
  <td><?php echo $user['id'] ?></td>
  <td><?php echo $user['name']; ?></td>
  <td><?php echo $user['email']; ?></td>
  <td><i data="<?php echo $user['id'];?>" class="status_checks btn
  <?php echo ($user['status'])?
  'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
 </i></td>
  </tr>
  <?php } ?>
  </table>
  </body>
</html>

Ajax
$(this).hasClass- Class suceess (Active) or (Inactive).
var msg - Status message.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
      var status = ($(this).hasClass("btn-success")) ? '0' : '1';
      var msg = (status=='0')? 'Deactivate' : 'Activate';
      if(confirm("Are you sure to "+ msg)){
        var current_element = $(this);
        url = "ajax.php";
        $.ajax({
          type:"POST",
          url: url,
          data: {id:$(current_element).attr('data'),status:status},
          success: function(data)
          {  
            location.reload();
          }
        });
      }     
    });
</script>

Ajax.php
<?php $db= new mysqli('localhost','root','','mostlikers');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>


CSS
.btn-success {
   background-color: #65B688;
   border-color: #65B688;
   }
   .btn-danger {
   color: #fff;
   background-color: #d9534f;
   border-color: #d43f3a;
   }
   .btn {
   color: white;
   display: inline-block;
   margin-bottom: 0;
   font-weight: 400;
   text-align: center;
   vertical-align: middle;
   cursor: pointer;
   background-image: none;
   border: 1px solid transparent;
   white-space: nowrap;
   padding: 6px 12px;
   font-size: 14px;
   line-height: 1.42857143;
   border-radius: 4px;
   -webkit-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
   }

Thursday, 4 September 2014

Ajax with PHP

What is AJAX ?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
  • Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
  • With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

PHP and AJAX Example:

To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command.
NOTE: We are asuing you have sufficient privilege to perform following MySQL operations
CREATE TABLE `ajax_example` (
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `sex` varchar(1) NOT NULL,
  `wpm` int(11) NOT NULL,
  PRIMARY KEY  (`name`)
) 
Now dump the following data into this table using the foloowing SQL statements
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

Client Side HTML file

Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!
 
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
NOTE: The way of passing variables in the Query is according to HTTP standard and the have formA
URL?variable1=value1;&variable2=value2;
Now the above code will give you a screen as given below

NOTE: This is dummy screen and would not work
Max Age: 

Max WPM:

Sex:
Your result will display here

Server Side PHP file

So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into "ajax-example.php" file
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
 //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
 //Select Database
mysql_select_db($dbname) or die(mysql_error());
 // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
 // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
 //build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
 $query .= " AND age <= $age";
if(is_numeric($wpm))
 $query .= " AND wpm <= $wpm";
 //Execute query
$qry_result = mysql_query($query) or die(mysql_error());

 //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
 $display_string .= "<tr>";
 $display_string .= "<td>$row[name]</td>";
 $display_string .= "<td>$row[age]</td>";
 $display_string .= "<td>$row[sex]</td>";
 $display_string .= "<td>$row[wpm]</td>";
 $display_string .= "</tr>";
 
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
Max Age: 

Max WPM:

Sex:
Your result will display here

If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.