Echo HTML from PHP to display in ajax request on webpage - javascript

I have a list of scientific publications displayed on a website and would like to load additional content as the user arrives at the end of a list of 10 publications, and presses a button to load another 10 publications.
I make an Ajax call to load the next 10 publications
I am trying to display html code that is echo-ed from php script but I cannot appear to display the html. In the console, I am getting '1' as a value for my HTML. I do not understand:
1. why I am getting the value of '1';
2. Also, is it good practice to echo HTML to be displayed via javascript?
JS (AJAX call):
var resp = xmlhttp.responseText;
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
var currentHTML = document.getElementById('showPubs').innerHTML;
if(response == '1'){
console.log('more publications available');
var currentHTML = document.getElementById('showPubs').innerHTML;
document.getElementById('showPubs').innerHTML += publicationList;
}else{
document.getElementById('showPubs').innerHTML += '<div id="noMorePub">No more publications</div>';
}
PHP:
$recentPublications .= '
<div id="pub'.$articleID.'" class="pub20">
<div class="divImg">'.$avatarPathHTML.'</div>
<div class="contentPub">
<div class="datepub">
<div class="fullName"><a class="sfullNme" href="2profile.php?username='.$articleUsername.'">'.$fullname.'</a></div>
<div class="date">'.$submitDate.'</div>
</div>
<div class="divLink">
'.$articleTitle.'
</div>
<div class="authorString">'.$author_string.'</div>
</div>
<hr class="pubSeparator">
</div>
';
echo $recentPublications.'|1';

I guess better idea is not use this dirty hack
echo $recentPublications.'|1';
and
var respArray = resp.split('|');
var response = respArray[1];
var publicationList = respArray[0];
if(response == '1'){
You can just check length of response. if length of response is equal 0 bytes then other publications are not available.

The good practice is to separate concerns. Therefore, in your example, server-side script should only provide data to be displayed (ex. JSON via), and frontend should make AJAX call to specific endpoint.

Related

How do I use a global session element in html script?

I want the script to read the global element, detect if its value equals 1 and if so, display a load of text but for some reason it doesn't seem to work.
var z = sessionStorage["system"]
if (z == 1) {
document.getElementById("titlesystem").innerHTML = "Your System";
document.getElementById("bodysystem").innerHTML = "Amazing!
}
<h2 id="titlesystem"></h2>
<p id="bodysystem"></p>
If I understand it right, you want to read some value stored in session (in php stored in $_SESSION) as a client from javascript.
First: session is server-side thing, clients don't know that they are in session.
But there is a way, how to send value.
This is what came to my mind:
<h2 id="titlesystem"></h2>
<p id="bodysystem"></p>
<input type="hidden" value=<?php echo $_SESSION["value"]?> id="mySessionValue">
<script>
var sessionValue = document.getElementById("mySessionValue").value;
if (sessionValue == 1)
{
document.getElementById("titlesystem").innerHTML = "Your System";
document.getElementById("bodysystem").innerHTML = "Amazing!"
}
</script>

Dynamically send javascript value via form

I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript

AJAX data returned is not correct

I have this posts.php where it uses a unique id to view different contents. For example: posts.php?id=1 will display all data on my table which has an id of 1, id = 2 for 2 and so on...
This id is held on a php var $post_id on each page and in order to send this php variable on my jquery/javascript, I used:
<div id = "dummy_disp" style = "display: none;">
<?php echo htmlspecialchars($post_id); ?>
</div>
<div id = "real_commentsno"></div>
( I know, not the best way to do it but it works)
It connects to my js:
var commentid = document.getElementById("dummy_disp");
var commentidreal = commentid.textContent;
$.ajax ({
type:"GET",
url:"php/post_comments.php",
data:'comid='+commentidreal,
success: function(data){
$("#real_commentsno").html(data);
}
});
I have this post_comments.php where it has:
$cc_g_postid = htmlentities($_GET['comid']);
$cc_postid = mysqli_real_escape_string($con,$cc_g_postid);
$cc_sql = "SELECT * FROM comments WHERE postuniqueid = '$cc_postid' ";
$cc_result = mysqli_query($con,$cc_sql);
$cc_count = mysqli_num_rows($cc_result);
echo $cc_count;
When I try to view the post_comments.php alongside with the attached url var: ?comid=1 the page displays 2 which is correct since post id=1 on my table has only 2 comments. But when I go to my posts.php the ajax displays 0, not 2. I tried looking at the console, there were no errors.
Is there anything I missed or misdo? Also, post_comments.php is on located on mypage/php/post_comments.php whereas posts.php is located on mypage/posts.php ( i dunno if this is necessary info but maybe the url is jamming it or something? )
The problem is that the DIV has newlines and spaces around the ID number. You need to remove all this whitespace.
var commentidreal = commentid.textContent.trim();

How to auto refresh a division with some PHP content within it

I googled abit and found a script, to reload a division.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
setInterval("$('#downshow').load('message.php');", 5000);
</script>
here downshow is my division where contents need to be refreshed. its like chat app, and messages between me and my friend needs to continoulsy reload.
My division downshow is something like below...
$getmessages= mysql_query("SELECT * FROM pvt_messages WHERE (user_from='$active_username' && user_to='$username') || (user_from='$username' && user_to='$active_username') ORDER BY id ASC ") or die(mysql_error());
while ($row = mysql_fetch_assoc($getmessages ))
{
$body = $row['msg_body'];
$date_send = $row['date'];
$opened = $row['opened'];
$whosent= $row['user_from'];
$whoreceived= $row['user_to'];
$seen=$row['opened'];
/////////////////////////////////////////////////////
$get_user_info = mysql_query("SELECT * FROM users WHERE (username='$whosent')");
////////////////////////////////////////////////////
$get_info = mysql_fetch_assoc($get_user_info);
$profilepic_info = $get_info['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./images/default_pic.jpg";
}
else
{
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
echo "
<div style='float: left;padding-top:5px; padding-left:20px;'>
<img src='$profilepic_info' height='50' width='40'>
</div>
<div style='margin-left:50px;padding-top:5px;'>
<a href='$whosent' style='color:black'> $whosent</a> $body
</div></br>
<div style=' margin-left:30px;'>
<font size='2px'>sent on: $date_send</font>
<br />
</div>
<hr />
";
}
I would have kept the content of this division in some other page i.e. message.php and then include it just as
<div id='downshow' style='bottom:0px;'class='see_message'>
<?php include("message.php"); ?>
</div>
But if i do this, there will be lots of problem like, session_start() issues, variable $active_username ll be obtained easily by $active_username=$_SESSION['username'] bt couldnt obtain varibale $username in message.php.
so instead of including the division content as "message.php". i want that code to be in main php file itself.
so want to as instead of
setInterval("$('#downshow').load('message.php');", 5000);
how can i use
setInterval("$('#downshow').load('????????????');", 5000);
load the division itself?????????????
Thankyou in advance :)
Try this..
setInterval(function(){ $('#downshow').load('message.php');
}, 5000);
This is not the best way to do this
You should look at AJAX and create a template for the HTML.
This way you can send information to the server (such as requesting items since a particular time, or from a particular 'room') and only send back the important data (send it back as JSON) and populate your template.
This will reduce traffic and load on your server and will reduce latency in your application as you are only sending back the important data - not the HTML to go with it!
Additionally use classes for each of the items instead of inline styles as it will make your code easier to maintain.

How to dynamically show error messages through PHP

I am creating a PHP login script. So far I have only worked on the registration.
My question is, how can I handle validation in PHP without refreshing the page? I want to output the feedback that the user has entered information wrongly, but I don't want to refresh the page. This is because I am using AJAX, so I want it to output on the page.
Is this possible?
See here, if you "sign up" without filling in any of the boxes it shows you some error messages. The problem is that it reloads the page as it does it. Is there a way to not reload the page and still show this data?
http://marmiteontoast.co.uk/fyp/login-register/test/index.php
This is an example of the if statement for just the username. This is repeated with all the other fields too:
if(isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
if(strlen($username) > 3){
// passed
if(strlen($username) < 31){
// passed
} else {
$_SESSION['status']['register']['error'][] = 'The Username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 4 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The Username is not entered.';
}
Once it passes all the validation it does:
header('Location:index.php');
And the errors are output on the index page by:
<?php
if(isset($_SESSION['status']['register']['error'])){
?>
<div class="alert alert-error">
<p><strong>There's a problem!</strong><br /><br />
<?php
foreach($_SESSION['status']['register']['error'] as $error){
// Outputs list of all errors, breaks to new line
echo $error . '<br />';
}
?>
</p>
1. Is it possible to output these dynamically with PHP?
2. Could I do the validation on the front end, then just pass it to the PHP to pass to the database?
2a. How would I handle running a username exists check if I do it front end?
This is something I actually just made the other day!
I have a file called "register.js", a file called "register_process.php" and some html.
How my server is set up:
html_docs (www):
ajax:
register_process.php
js:
register.js
jquery-1.6.2.js
register.html
so within my register.html, my code looks like such:
<script type="text/javascript" src="js/md5.js"></script> <!-- this is in my head -->
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<!-- everything else is in my body -->
<div id="error_message" style="display: none;">
</div>
<div id="register_div">
<input type="text" name="username" id="username"><br>
<input type="password" name="password" id="password"><br>
<input type="submit" name="submitbutton" id="reg_button" value="Register" onclick="AttemptRegisterAjax(); return false;"><br>
</div>
This calls the function inside of my register.js file. That functions looks like such:
function AttemptAjaxRegister(){
var url = "ajax/register_process.php?";
url += "time=" + (new Date().getTime()) + "&un=";
var username_ele = document.getElementById("reg_username");
var password_ele = document.getElementById("reg_password");
var error_ele = document.getElementById("error_message");
var username = username_ele.value;
var password = password_ele.value;
if((username.length >=4) && (password.length >= 4)){
url += encodeURIComponent(username) + "&pw=" + encodeURIComponent(password);
console.log(url);
$.get(url, function(data, status, xhr){
data = data.trim();
if(data != "true"){
error_ele.innerText = data;
error_ele.style = "display: block;";
}else{
window.location = "/profile.php";
}
});
}else{
error_ele.innerText = "Please make sure your password and username are both 4 characters long";
error_ele.style = "display: block;";
}
}
now, inside of your php, you'll want to set everything up just like how you had it to register, but you'll want to actually just call die($YourErrorMessage); or if the registration was successful, die("true");
Not directly, you will need to use another tool for that, most likely Javascript.
Yes but that would be a terible practice. the best way to validate on both.
2a. I believe you would need to use a database.
thsi tutorials might help you out.
Easy jQuery Ajax PHP Contact Form
How to create a Sign Up form registration with PHP and MySQL

Categories

Resources