I'm trying to get a jQuery script to update the content of an HTML paragraph tag variously according to whether or not a PHP if statement, which checks for data in a database, evaluates to true or not:
if ($num_rows > 0) { ?> // If results are returned from database...
<script>
$(document).ready(function() {
$('p.message').text('Some data'); // ... p should read 'Some data'
});
</script>
<?php else { // otherwise
<script>
$(document).ready(function() {
$('p.message').text('No data'); // ...p should read 'No data'
});
</script>
}
The contents of are intended to change dynamically without the need for a page refresh, but do not do so. Only after the page has been refreshed is the new value shown.
Any ideas as always much appreciated.
Use AJAX to get the content from PHP. You can have the success populate the data into your HTML.
What You are trying to do can be achived through Ajax. Belwo Is a simple Example
Jquery
setInterval(function(){UpdateMessage()},10000) // Will Eecute after 10 Seconds
function UpdateMessage()
{
$.ajax({
type:"POST",
url:"Script.php",
success: function(data)
{
$(".message").text(data);
}
});//END OF Second AJAX
}
HTML
<p class='message'></p>
Script.php
if ($num_rows > 0)
echo "SOME DATA";
else
echo "No Record";
above code will refresh Your Data every after 10 Seconds Without Refresh
did you try include jquery into that php file? like
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
Related
Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.
A PHP page opened in my browser.
I have an HTML file with a jQuery AJAX call in it. When I post the data using AJAX, the HTML page disappear and the PHP file open instead.
I want to see the HTML result in the PHP page that I initially opened instead of opening a new HTML page.
What I have to do in my phpfile?
Thanks for help.
My HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$.post( "result.php",{ name : $('#text').val() },
function( data ) {
$('#bigdiv').html(data);
// alert(data);
});
}); //event handler
}); //document.ready
</script>
And my PHP code:
<?php
$name="";
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
}
echo "name = $name";
?>
I'm going to go ahead and assume that your button is tied to a form, so that it submits the form, and thus reloading the page, when you press it. Try adding this to your JavaScript:
$("#button").click(function(e) {
e.preventDefault();
//rest of your code...
Is it possible using jQuery to literally refresh a div?
Nothing like submitting a form or anything like that.
I have a data stream which is updated else where and all I want to do is refresh the div and all its contents as if it were a page refresh. I can't link to that page to make a return that populates as the only output is just raw data.
The div itself contains all the data display processing. Nothing needs to be fetched as the data is already there.
you have to use setinterval with ajax function,
$(document).ready(function(){
setInterval(function(){ refreshDiv(); }, someInterval);
});
function refreshDiv(){
$.ajax({
url: "http://yourrequestpath",
.....
});
}
<div id="data"></div>
<script>
$('#div').load("loaddata.php", function() {
window.setInterval("loadData", 60000);
});
function loadData()
{
$('#div').load("loaddata.php");
}
</script>
i have a php page that redirects (if successful) to another php page like this:
header('Location: completed.php?message=Successful operation. Data inserted for user: ' . $login->get_username() . ' . See home page for infos.');
Now in completed.php i have a div that echoes the received message:
<div id="msg">
<?php echo $_GET['message']; ?>
</div>
I'm using the 'Toastmessage-plugin' : here.. , but i'm unable to display the $_GET in to the text of Toastmessage ..
I'm using this code :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="js/jquery.toastmessage.js" type="text/javascript"></script>
<link href="styles/jquery.toastmessage.css" rel="stylesheet" type="text/css" />
...
<script type="text/javascript">
function showStickyNoticeToast() {
$().toastmessage('showToast', {
text: $('#msg').val(),
sticky: true,
position: 'bottom-left',
type: 'notice',
closeText: '',
close: function () { console.log("toast is closed ..."); }
});
}
</script>
I've searched a lot , also for DOM Events and other events but i don't know what step take... maybe when the JQ function is loaded the div 'msg' has not yet received GET data ...? so how i update his value ?
The page i've read :
this and this.
I also tried with ajax but i'm less experienced in that language..
please help... :) Thanks
EDIT #charlietfl
Ajax : i've made a lot of tries... i can't find the code anymore!
Basically i call a php file with this code (take this as pseudocode):
<script type="text/javascript>
<!--
$('#choose').change(function(event) {
$.get('messages.php', { selected: $('#msg').val() },
function(data) {
$('#update').html(data); // other div wher store data
}
);
});
</script>
....
<?php
$alfa = isset($_GET['message']) ? $_GET['message'] : 'nothing';
echo $alfa;
?>
Try to pass the message with urlencode() like:
$msg = "Successful operation etc. etc.";
header("Location: completed.php?message="+urlencode($msg));
Got it: you use $("#msg").val() but DIV tags have not a "value".
Use $("#msg").text() (for plain-text)
or $("#msg").html()
to include also some HTML you may have in your code (pretty sure you need the first option).
Use .val() only with "valued" tags like <input> (works also with <textarea>).
See also: http://api.jquery.com/val/
Your issue is likely that you are trying to call the message plugin before the ajax completes since the first 'A' in ajax stands for asynchronous.
In order to allow for the time required for the ajax to complete you would need to call your message plugin within the success callback of ajax.
Add message argument to function
function showStickyNoticeToast( message ) {
$().toastmessage('showToast', {
text: message,
sticky: true,
position: 'bottom-left',
type: 'notice',
closeText: '',
close: function () { console.log("toast is closed ..."); }
});
}
$.post( url , dataToserver, function(data){
showStickyNoticeToast( $(data).text())
$('#update').html(data);
})
I have this code that is to fetch a particular item in the database after the user presses a button. If the item is found I would like to display a confirm message via javascript and I don't know how to show it.
After obtaining the item from the database
if(null!=mysqli_fetch_array($res)))
{
echo ""; // how can I call the javascript code here ?
}
and the following confirm box
<script type="text/javascript">
function onConfirm()
{
return confirm("Display this item ?");
}
</script>
Use jquery and ajax to get the value from the database:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
$.get("ajax.php", function(data){
if(data != "0"){
if(confirm("Display this item ?"))
{
//do something
}
}
});
ajax.php:
//other db code here
if(null!=mysqli_fetch_array($res)))
{
echo "1";
}
else{
echo "0";
}
There are number of ways you can solve this. A good way is to:
Send an ajax request to a page
The page does the mysql stuff and returns(echo in case of PHP) the message
On the callback function use simple way such as alert() to show the message.