I'd like to do a sql query with ajax so I don't need to reload the page / load a new page.
So basicly I need to call a php page with ajax. And it would be great if there could be a way to reload a count of amount of rows in a table too.
Edit: to make it more clear, it should be able to do something along the lines of when you click the Like button on Facebook.
Thanks
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("your_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">here are your contents</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You don't want to query using ajax, you want to get new data using ajax, which is a fundamental difference.
You should just, using ajax, request a php page with perhaps some parameters, which in turn executes the query and returns the data in a format you can handle (most likely: json).
If you allow queries to be executed using ajax, how are you going to prevent a malicious user from sending drop table users, instead of select * from news where id = 123?
You won't do a sql query with ajax, what you need to do is call an external php page (one where your query is) in the background using ajax. Here is a link that explains how to do it with jquery: http://api.jquery.com/jQuery.ajax/
"Facebook Like" button in Agile Toolkit (PHP UI Library):
$likes = get_like_count();
$view = $this->add('View');
$button = $view->add('Button')->setLabel('Like');
$view->add('Text')->set($likes);
if($button->isClicked()){
increate_like_count();
$view->js()->reload()->execute();
}
p.s. no additional JS or HTML code needed.
function onClick(){
$.post(
"path/to/file", //Ajax file ajax_file.php
{ value : value ,insiId : insiId }, // parameters if you want send
//function that is called when server returns a value.
function(data){
if(data){
$("#row_"+data.id).show(); //display div rows
}
},"json"
);
}
<div id="myDiv">here are your contents</div>
<button type="button" onclick="onClick()">Change Content</button>
Here the ajax code that you can call to the server side php file and get the out put and do what you want
You are wrong, who says that he is submitting the whole query who is telling that he is not filtering? U can do all this easy with the jquery load function, you load a php file like that $('#BOX').load('urfile.php?param=...');.
Have fun,
i hope that was a little helpful for you, sry bcs of my bad english.
Possible solution: Ajax calls PHP scripts which make the query and return the new number
$.ajax({
async:true,
type:GET,
url:'<PHP_FILE>',
cache:false,
data:'<GET_PARAMETERS_SENT_TO_PHP_FILE>',
dataType:'json',
success: function(data){
$('<#HTML_TARGET>').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('<#HTML_TARGET>').html('<div class="ajax_error">'+errorThrown+'</div>');
}
});
Where
<PHP_FILE> is your php script which output must be encoded according to dataType. The available types (and the result passed as the first argument to your success callback) are: "xml", "html", "script", "json", "jsonp", "text".
<GET_PARAMETER_SENT_TO_PHP> is a comma separate list of value sent via GET (es. 'mode=ajax&mykey=myval')
<#HTML_TARGET> is the jquery selector
See jquery.ajax for more details.
For example:
<p>Votes:<span id="count_votes"></span></p>
<script type="text/javascript">
$.ajax({
async:true,
type:GET,
url:'votes.php',
cache:false,
dataType:'text',
data:'id=4'
success: function(data){
$('#count_votes').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('#count_votes').html(errorThrown);
}
});
</script>
If your looking for something like the facebook like btn. Then your PHP code should look something like this -
<?php
$topic_no = $_POST['topic'];
$topic_likes = update_Like_count($topic_no);
echo $topic_likes;
function update_Like_count($topic)
{
//update database by incrementing the likes by one and get new value
return $count;
}
?>
and the javascript/jquery ajax should be something like so -
<script>
$('#like-btn').click( function () {
$.post(
"like.php",
{ topic : value },
function(data)
{
if(data)
{
$("#like-btn span").append(data); //or append it to wherever you'd like to show it
}
else
{
echo "error";
}
},
"json"
);
});
</script>
Here is an example which uses a favorite jQuery plugin of mine, jQuery.tmpl(), and also the jQuery .text() function.
HTML and Javascript Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
<script id="UserTemplate" type="text/x-jquery-tmpl">
<li><b>Username: ${name}</b> Group ID: (${group_id})</li>
</script>
<button id="facebookBtn">Facebook Button</button>
<div id="UserCount"></div>
<ul id="userList"></ul>
<script>
function getData(group_id) {
$.ajax({
dataType: "json",
url: "test.php?group_id=" + group_id,
success: function( data ) {
var users = data.users;
/* Remove current set of movie template items */
$( "#userList" ).empty();
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#UserTemplate" ).tmpl( users )
.appendTo( "#userList" );
$( "#UserCount" ).text('Number of users: '+ data.count);
}
});
}
$( "#facebookBtn" ).click( function() {
getData("1");
});
</script>
</body>
</html>
PHP Code
<?php
//Perform a query using the data passed via ajax
$group_id = $_GET['group_id'];
$user_array = array(
array('name'=>'John','group_id'=>'1',),
array('name'=>'Bob','group_id'=>'1',),
array('name'=>'Dan','group_id'=>'1',),
);
$user_count = count($user_array);
echo json_encode(array('count'=>$user_count,'users'=>$user_array));
HTML:
//result div will display result
<div id="result"></div>
<input type="button" onclick="getcount();" value="Get Count"/>
JS:
//will make an ajax call to ustom_ajax.php
function getcount()
{
$.ajax({
type:"get",
url : "custom_ajax.php",
beforeSend: function() {
// add the spinner
$('<div></div>')
.attr('class', 'spinner')
.hide()
.appendTo("#result")
.fadeTo('slow', 0.6);
},
success : function (data) {
$("#result").html(data);
},
complete: function() {
// remove the spinner
$('.spinner').fadeOut('slow', function() {
$(this).remove();
});
}
});
}
custom_ajax.php:
//will perform server side function
//make a connection and then query
$query_txt = "SELECT count(*) FROM table ";
$result= mysql_query($query_txt) or die(mysql_error());
$total=mysql_num_rows($result) ;
$html= "Total result is $total";
echo $html; exit();
Related
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked
I have this submit button without a form..
<input type='submit' id='conx' name='X' value='TEST x'>
Now when the button is clicked i need to execute this code.
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
close($con);
How can i execute it in jquery and ajax?.
$("#conx").click(function(){
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
});
Thanks.
Post that to a PHP page with Ajax and execute those ther
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php");
});
Make sure yo have that PHP code in yourPHPPageWithMagicCode.php file.
If you want to show a response after the process is done, you can return something from your PHP page and let the callback of $.post handle it.
In your PHP page after your code,put an echo
echo "successfully finised";
Now change the jquery code to handle the callback
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php",function(repsonse){
alert(response);
});
});
Let's say your PHP file is called write.php. I believe you can do this:
$("#conx").click(function() {
$.ajax({
url: "/write.php"
});
});
All in one file.
test.php
<?php
if ($_POST['cmd'] === 'ajax') {
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
fclose($con);
exit;
}
?>
<!doctype html>
<head>
<meta charset="utf-8">
<title>meh</title>
</head>
<body>
<input type="submit" id="conx" name="X" value="TEST x">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
$("#conx").bind('click', function(){
$.post("test.php", { cmd: "ajax" } );
});
});
</script>
</body>
</html>
Add something like below inside your click function to call a PHP script:
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "URL/TO/PHP/SCRIPT",true);
xmlhttp.send();
You need a jquery ajax call between the click event block
$("#conx").click(function(){
$.ajax({
url: "phpfile.php",
type: "post",
//data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
alert(response);
}
});
});
put whatever code you want in the phpfile.php file.
You need to load the 'click event' on the document load i.e.:
$(document).ready(function($){
$("#conx").click(function(){ .....
one way is
$("#conx").click(function(){
$.post("PHPFILENAME.PHP",{
whatdo:otherstuff
},function(d){
// return d here
}
})
run your code in the php file.
You could call a javascript function from the button:
<input type='submit' onclick="myFunction()" id='conx' name='X' value='TEST x'>
and have a page load in your function:
function myFunction(){
var loadUrl = "magic.php";
var result = $("#result").load(loadUrl);
}
Then have magic.php run your method:
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
This is all untested pseudo-code...
I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.
I want to use $.post function of jquery to do a div refresh, only if the content returned in the json data from the php script is modified. I know that ajax calls with $.post are never cached. Please help me with $.post, or $.ajax if it is not possible with $.postor any other method with which this is possible.
Thanks
Why don't you cache the response of the call?
var cacheData;
$.post({.....
success: function(data){
if (data !== cacheData){
//data has changed (or it's the first call), save new cache data and update div
cacheData = data;
$('#yourdiv').html(data);
}else{
//do nothing, data hasan't changed
This is just an example, you should adapt it to suit your needs (and the structure of data returned)
var result;
$.post({
url: 'post.php'
data: {new:'data'}
success: function(r){
if (result && result != r){
//changed
}
result = r;
}
});
Your question isn't exactly clear, but how about something like this...
<script type="text/javascript">
$(document).ready(function(){
$("#refresh").click(function(){
info = "";
$.getJSON('<URL TO JSON SOURCE>', function(data){
if(info!=data){
info = data;
$("#content").html(data);
}
});
});
});
</script>
<div id="content"></div>
<input id="refresh" type="submit" value="Refresh" />
I think you should use .getJSON() like I used it there, it's compact, and offers all the functionality you need.
var div = $('my_div_selector');
function refreshDiv(data){
// refresh the div and populate it with some data passed as arg
div.data('content',data);
// do whatever you want here
}
function shouldRefreshDiv(callback){
// determines if the data from the php script is modified
// and executes a callback function if it is changed
$.post('my_php_script',function(data){
if(data != div.data('content'))
callback(data);
});
}
then you can call shouldRefreshDiv(refreshDiv) on an interval or you can attach it to an event-handler