Showing posts with label PHP Jquery. Show all posts
Showing posts with label PHP Jquery. 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.

Friday, 26 June 2015

PHP: How to Select / Deselect all Checkboxes with jQuery

In this tutorial i am going to explain you that how to do “Select / Deselect all checkboxes using jQuery”, Most of newbie learners face this issue that how to select all and deselect all checkboxes of any needable forms , this one is simple script but yet useful, hence we can also select checkbox values individually but we frequently need this type of snippets to perform multiple operations, like gmail you can select all emails and perform any operations it have, so this will guide you that how to use jQuery to select and deselect all checkboxes, and at the end of this tutorial we will also see that how to get selected (multiple) checkboxes value and print them so have a look. 

The jQuery code : in the following code there is a parent class called “.select-all” which changes the attribute of sub checkboxes on “.click” function and all the functionality done by including the “jQuery.js” library in your head document.
<script type="text/javascript">
$('document').ready(function()
{
 $(".select-all").click(function () 
 {
  $('.chk-box').attr('checked', this.checked)
 });
  
 $(".chk-box").click(function()
 {
  if($(".chk-box").length == $(".chk-box:checked").length) 
  {
   $(".select-all").attr("checked", "checked");
  } 
  else 
  {
   $(".select-all").removeAttr("checked");
  }
 });
});
</script>

The HTML code :

simple HTML form containing multiple checkbox
<ul>
 <li><input type="checkbox" class="select-all" /> Select / Deselect All</li>
    <li><input type="checkbox" class="chk-box" /> PHP</li>
    <li><input type="checkbox" class="chk-box" /> Ajax</li>
    <li><input type="checkbox" class="chk-box" /> jQuery</li>
    <li><input type="checkbox" class="chk-box" /> Android</li>
    <li><input type="checkbox" class="chk-box" /> XML</li>
</ul>

Complete Script

complete script with html form for selecting / deselecting checkboxes.
<!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>Select / Deselect All Checkboxes with jQuery</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$('document').ready(function()
{
 $(".select-all").click(function () 
 {
  $('.chk-box').attr('checked', this.checked)
 });
  
 $(".chk-box").click(function()
 {
  if($(".chk-box").length == $(".chk-box:checked").length) 
  {
   $(".select-all").attr("checked", "checked");
  } 
  else 
  {
   $(".select-all").removeAttr("checked");
  }
 });
});
</script>
</head>

<body>

<h1>Select / Deselect All Checkboxes with jQuery</h1>

<ul>
 <li><input type="checkbox" class="select-all" /> Select / Deselect All</li>
    <li><input type="checkbox" class="chk-box" /> PHP</li>
    <li><input type="checkbox" class="chk-box" /> Ajax</li>
    <li><input type="checkbox" class="chk-box" /> jQuery</li>
    <li><input type="checkbox" class="chk-box" /> Android</li>
    <li><input type="checkbox" class="chk-box" /> XML</li>
</ul>

</body>
</html>

Get the Values of Selected Checkboxes

now let's take a look at the following code which helps you to get the multiple selected values and print them, suppose we have following form.
<form method="post">
<ul>
 <li><label><input type="checkbox" class="select-all" /> Select / Deselect All</label></li>
    <li><input type="checkbox" name="chk[]" class="chk-box" value="PHP" /> PHP</li>
    <li><input type="checkbox" name="chk[]" class="chk-box" value="Ajax" /> Ajax</li>
    <li><input type="checkbox" name="chk[]" class="chk-box" value="jQuery" /> jQuery</li>
    <li><input type="checkbox" name="chk[]" class="chk-box" value="Android" /> Android</li>
    <li><input type="checkbox" name="chk[]" class="chk-box" value="XML" /> XML</li>
    <li><button type="submit" name="save">submit</button></li>
</ul>
</form>

PHP CODE :

and PHP code would be as follow, using "foreach" loop we can retrieve the selected checkboxes values.
<?php
if(isset($_POST['save']))
{
 if(isset($_POST['chk'])=="")
 {
  echo "please select at least one";
 }
 else
 {
  foreach($_POST['chk'] as $languages)
  {
   echo $languages."<br />";
  } 
 }
}

?>

PHP: Dynamic Dependent Select Box using jQuery and PHP

This tutorial will cover creating a simple and Dynamic Dependent Select Box using jQuery and PHP for selecting state and city based on choosing the country, means Loading records from database dynamically and display it in select box without refreshing the whole page with the help of Ajax and jQuery and PHP code, Ajax is used to submit and get records from MySQL Database without page refresh. when you choose country box it will allows state box to choose country based state and same with city using Ajax code integrating with PHP and MySQL.

Database Design & Tables

create database "dbcountries" this database consist three tables country, state and city as below.
state table has relation with country table and city table has relation with state table.

tbl_country :
stores country name and country id
CREATE TABLE `tbl_country` (
`country_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`country_name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM ;

tbl_state :
stores state name and state id based on country id foreign key
CREATE TABLE `tbl_state` (
`state_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`country_id` INT( 3 ) NOT NULL ,
`state_name` VARCHAR( 35 ) NOT NULL
) ENGINE = MYISAM ;

tbl_city :
stores city name and city id with state id foreign key
CREATE TABLE `tbl_city` (
`city_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`state_id` INT( 3 ) NOT NULL ,
`city_name` VARCHAR( 35 ) NOT NULL
) ENGINE = MYISAM ;

dbconfig.php

common database configuration file.
<?php

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "dbcountries";

try
{
 $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
 $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
 $e->getMessage();
}

index.php

contains jQuery/JavaScript and PHP code which displays three select box , country drop down box already filled with countries and state , city will be automatically change based on parent selection.
<?php
include_once 'dbconfig.php';
?>
<!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=iso-8859-1" />
<title>Dynamic Dependent Select Box using jQuery and PHP</title>
<script type="text/javascript" src="jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
 $(".country").change(function()
 {
  var id=$(this).val();
  var dataString = 'id='+ id;
 
  $.ajax
  ({
   type: "POST",
   url: "get_state.php",
   data: dataString,
   cache: false,
   success: function(html)
   {
      $(".state").html(html);
   } 
   });
  });
 
 
 $(".state").change(function()
 {
  var id=$(this).val();
  var dataString = 'id='+ id;
 
  $.ajax
  ({
   type: "POST",
   url: "get_city.php",
   data: dataString,
   cache: false,
   success: function(html)
   {
    $(".city").html(html);
   } 
   });
  });
 
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
div
{
 margin-top:100px;
}
select
{
 width:200px;
 height:35px;
}
</style>
</head>

<body>
<center>
<div>
<label>Country :</label> 
<select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
 $stmt = $DB_con->prepare("SELECT * FROM tbl_country");
 $stmt->execute();
 while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
        <option value="<?php echo $row['country_id']; ?>"><?php echo $row['country_name']; ?></option>
        <?php
 } 
?>
</select>

<label>State :</label> <select name="state" class="state">
<option selected="selected">--Select State--</option>
</select>


<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>

</div>
<br />
<a href="http://cleartuts.blogspot.com/">cleartuts</a>
</center>
</body>
</html>

get_state.php

contains PHP code which selects state records from state table and load data dynamically when selection made on country box.
<?php
include('dbconfig.php');
if($_POST['id'])
{
 $id=$_POST['id'];
  
 $stmt = $DB_con->prepare("SELECT * FROM tbl_state WHERE country_id=:id");
 $stmt->execute(array(':id' => $id));
 ?><option selected="selected">Select State :</option><?php
 while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
        <option value="<?php echo $row['state_id']; ?>"><?php echo $row['state_name']; ?></option>
        <?php
 }
}
?>

get_city.php

contains PHP code which selects city records from city table and load data dynamically when selection made on state box.
<?php
include('dbconfig.php');
if($_POST['id'])
{
 $id=$_POST['id'];
 
 $stmt = $DB_con->prepare("SELECT * FROM tbl_city WHERE state_id=:id");
 $stmt->execute(array(':id' => $id));
 ?><option selected="selected">Select City :</option><?php
 while($row=$stmt->fetch(PDO::FETCH_ASSOC))
 {
  ?>
  <option value="<?php echo $row['city_id']; ?>"><?php echo $row['city_name']; ?></option>
  <?php
 }
}
?>