iam doing a page in php that if any new record is entered it will notify the users screen with the new record count. Following is the code i did for the same, but its not working fine. Can u pls suggest me as of what iam doing wrong...
alert.php
<?php
require("config.php");
$result = mysql_query("SELECT * FROM marketing_tend_corr");
$res = mysql_num_rows($result);
echo $res;
?>
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
define('BASEPATH', true);
require("config.php");
?>
<script>
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
if (count_cases != -1 && count_cases != response) echo $count_cases);
count_cases = response;
}
});
},1000);
</script>
The following line of code is not going to work in Javascript:
if (count_cases != -1 && count_cases != response) echo $count_cases);
This line of code contains php code (echo $count_cases) which is server side code.
I've changed the code a bit and replaced the number of records by returning a random value.
// alert.php
<?php
echo rand(1, 1000000);
//index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
$("body").html(response);
}
});
},1000);
</script>
</head>
<body>
</body>
</html>
You can check the index.php file in your browser to see the random numbers being returned. This random number should in your case become the result of your 'mysql_num_rows' function.
Related
I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.
I'm tryin to get a value in URL from php file via $.get(), here is the code:
PHP folder called 'jquery_con4.php':
echo (isset($_GET['req'])) ? 'found':'notfound';
JQuery called 'pass.js':
$.get('connection/jquery_con4.php', function(data){
alert(data);
});
the main folder called 'password_c.php' which include the javascript called 'pass.js' which has $.get but it shows me in note 'notfound', & if remove if echo, it shows be 'undefined index:req'
--- URL is: 'http://localhost/series/skyface/password_c.php?req=65yDq0zI39UcRSF'
Thanks!
http://localhost:8888/series/skyface/password_c.php?req=65yDq0zI39UcRSF
In order to pass the 'req' value from the URL querystring to the jquery_con4.php script, you need a JS function that will grab it for you and pass it into an ajax request.
Below is an example of how that might work.
/series/skyface/password_c.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="../../main.js"></script>
</body>
</html>
/main.js:
jQuery(document).ready(function($) {
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function success(data) {
console.log(data);
}
$.ajax({
url: '/connection/jquery_con4.php',
data: {req : getParameterByName('req')},
success: success
});
});
/connection/jquery_con4.php:
<?php echo(isset($_GET['req'])) ? 'found' : 'notfound'; ?>
I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.
Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>
For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.
I can send a query to mysql database with following code:
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
My questions is, Is there any way to send a query with just a click on some text.
Let's example: there are a text name Reply. I want if i click this Reply text then mysql database field value (field name: Reply, type: int) will be increase by 1.
Sorry I DON'T KNOW ABOUT JAVASCRIPT/AJAX:(
FINAL UPDATER CODE TO #DEVELOPER:
<html>
<head>
<title>Untitled Document</title>
</head>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
<body>
echo "<a href='#' id='mylink'>Reply</a>";
</body>
</html>
Php page:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
?>
You should have this link or button to be clicked wired to an ajax call using jQuery
http://api.jquery.com/jQuery.ajax/
It should call a php page, which contains the query you're looking to run. You can pass in arguments with the ajax call as well, so that your $message and $replyno are set properly before executing.
<script>
$("#mylink").click(function() {
$data = $("#myform").serialize();
$.ajax({
url: "postquery.php",
data: $data
}).done(function() {
$(this).addClass("done");
});
});
</script>
then your php page would look something like this:
<?php
...
$message = mysql_real_escape_string($_REQUEST['message']);
$replyno = mysql_real_escape_string($_REQUEST['replyno']);
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
....
?>
Excaping your incoming strings using "mysql_real_escape_string" is always important to prevent SQL Injection attacks on your database.
Your HTML should look something like this:
<html>
...
<input type="textarea"></input>
Reply
...
</html>
This will cause the previously stated jquery statement to trigger when "Reply" is clicked.
Here is with your updated code. I corrected the link ID and also removed the form serialization data since your test code does not appear to need it. I also added the reference to the jQuery library:
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
</head>
<body>
<a href='#' id='mylink'>Reply</a>
</body>
</html>
The problems you're likely seeing are because of your query, not the front end code. Try adding some debug code like this:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
if(!$sql)
{
echo mysql_error();
}
?>
Or try checking your servers error logs.
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
You have to use jquery and ajax like this:-
<script type="text/javascript">
$j(document).ready(function() {
$j('#reply').click(function(){
jQuery.ajax({
url: "test.php", //Your url detail
type: 'POST' ,
data: ,
success: function(response){
}
});
});
});
</script>
In the file "updat_post.php" write:
If(isset($_GET['visit_post']))
$pdo->query('update posts set counter = counter+1');
In your js/jquery file on document ready write:
$('#mybutton').click(function() {
$.post('update_post.php', {visit_post: true});
});
I would like to create a PHP page which accepts an arguement like so:
http://localhost/page.php?topic=Foo
and then pulls data from an SQL Database where topic=Foo but then automatically checks for new data every 10 seconds and refreshes a DIV tag using Ajax. I've tried and nothing works. Any help?
EDIT: here is the code I've used:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
ext = <?php $_GET[feedtitle] ?>
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + ext);
var refreshId = setInterval(function() {
$("#responsecontainer").load('response.php?ext=' + ext);
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
EDIT: I can do the SQL bit, it's just the getting the arguement to the response.php im having issues with.
EDIT: I have new code, but its still not working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function gup( name )
{ name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var feed = gup('f');
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + feed);
var refreshId = setInterval(function() { $("#responsecontainer").load('response.php? ext=' + feed); }, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
So, you need to
Get escaped URL parameter
,
output the jquery $.post function's result data and then you just need to know
How to refresh page with jQuery Ajax? and do an
AJAX Div Retrieval every 60 seconds?
I hope that helps :)