Combination JQuery and PHP - javascript

I'm making a project with the slides of text.
I have in the page a main div that contain the text of each slide.
I saved the content in a database.
I want do this operation:
When I click the arrow for view the next slide, PHP catch from database the content and save it in a variable.
Then with JQuery, I replace the maindiv's content with variable.
It is possible? If not, How can I do it?

Use a ajax request to simulate a post request, and parse the information with php. You will end up with someting like this:
<?php
if( isset( $_POST["slide"] ) {
// Database stuff
// Echo back
echo "Information that you need to get in jQuery";
}
?>
<script>
$("button.next_slide").click(function(){
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("some_element").innerHTML = ajax.responseText;
}
}
ajax.open("POST","this_page.php?slide=1&foo=bar&bar=foo",true);
ajax.send();
});
</script>
<button class="next_slide">Next slide</button>
<div id="some_element"></div>
Note: This could be done without jQuery, or with jQuery's $.ajax method. Read more here: http://api.jquery.com/jquery.ajax/

In my understanding, you want to load some data when user click on a particular button and then load it into a div we can achieve it via jQuery ajax and PHP.
HTML
<div class="main_div">
<ul id="list"><!-- Our content will load here --></ul>
Next
</div>
jQuery
jQuery(document).ready(function($){
$('.call_ajax').on('click', function(e){
e.preventDefault();
$.post('ajax.php', { get_slide: true }, function(response){
// We are telling jQuery to parse response as json because in ajax.php we have used json_encode function.
var data = jQuery.parseJSON(response);
$("#list").append('<li>' + data['slide'] + '</li>');
});
})
})
PHP ajax.php
if(isset($_POST['get_slide'])){
//Get slide from db and output it as json, but currently for example purpose we assume that we have a array.
$data['slide'] = 'Your slide text';
echo json_encode($data); die(); // We have used die because we don't won't our script to run any more.
}
I've not tested it, but it will work.

Related

How to get PHP array as responseText in ajax to pass it to certain div from ajax later

I have a general info form. When I click on submit, all values are got using javascript and send it to PHP function using ajax.
The PHP function validates the form and returns
EITHER form errors as an array
OR successful message.
I want to get the array generated by PHP on ajax side and pass it to the form to display the errors on respective form fields.
I have successfully generated the array of errors in PHP.
print_r($arrayname) shows all the values as an array.
But I don't want to show instead I want to pass it to ajax and retrieve the array in a div and do work on that array.
--------- AJAX ------
function general()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST','addGeneral',true);
var data = new FormData();
data.append('title',document.getElementById('title').value);
data.append('firstname',document.getElementById('firstname').value);
data.append('middlename',document.getElementById('middlename').value);
data.append('surname',document.getElementById('surname').value);
xmlHttp.send(data);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState==4)
{
var status = xmlHttp.responseText;
document.getElementById('responseG').style.display="block";
if(status=='true')
{
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else
{
document.getElementById('responseG').className="alert alert-danger";
document.getElementById('responseG').innerHTML=status;
}
}
}
}
---- PHP FUNCTION ---
public function addGeneral()
{
$status=array();
extract($_POST);
$this->form_validation->set_rules('title','Title','required',array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('firstname','First Name','required');
$this->form_validation->set_rules('middlename','Middle Name','required');
$this->form_validation->set_rules('surname','Surname','required');
if($this->form_validation->run()===FALSE)
{
$status=$this->form_validation->error_array();
}else
{
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
$this->Manage_employee_model->update_employee($data);
$status=array('true');
}
}
Once a PHP script finished running and the browser receives the end of the HTML response, it's over, you can't directly modify the output already sent with more PHP. What you can do it use AJAX to get the data and render it on the client side using JS, or render it on the server side and just inject the result with JS.
Client rendering
For this you just need your PHP script to return the data, then loop over it and append each item to your div in JS. It's a bit awkward to render things with native JS but this approach keeps the presentation in one place instead of having HTML code on your backend.
Server side
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
echo json_encode($data);
Client side
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4) {
var data = JSON.parse(xmlHttp.responseText);
document.getElementById('responseG').style.display="block";
if(data.status=='true') {
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else {
document.getElementById('responseG').className="alert alert-danger";
for(var i = 0; i < data.length; i++){
document.getElementById('responseG').innerHTML+= '<p>'+data[i]+'</p>;
}
}
}
}
Server rendering
Here we use PHP to generate the HTML string on the backend, send it back via AJAX and just append it to the div on the client side. The disadvantage here is mixing HTML templates with your backend code.
Server side
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
$html = '';
foreach ($data as $key => $item) {
$html += '<p>'.$item.'</p>';
}
echo json_encode(array('html' => $html));
Client side
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4) {
var data = JSON.parse(xmlHttp.responseText);
document.getElementById('responseG').style.display="block";
if(data.status=='true') {
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else {
document.getElementById('responseG').className="alert alert-danger";
document.getElementById('responseG').innerHTML = data.html;
}
}
}
In your php code after you have done all the checks and populated your response array just do a simple echo to return that data to ajax.
Example in php: echo json_encode($status);
The best place to put this code is under your if statement
Print error message on form
<?php
if(!empty(validation_errors())) {echo
validation_errors();}
?>

How do I redirect the user with PHP after using jQuery's preventDefault() on a form?

I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();

Ajax & Session Variables? Worksafe Filter (selective image hiding)

I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.
I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.
UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.
Image Index Page:
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'] {
$_SESSION['Worksafe_Mode'] = 1;
}
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
Toggle Worksafe Mode
</button>
<script>
$('#Worksafe_Button').click(function() {
$.post("worksafe_mode_toggle.php")
.done(function(data) {
window.location.href = window.location.href;
});
});
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');
while($row = mysqli_fetch_assoc($image)) {
if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
echo 'If you are over 18, toggle Worksafe Mode to view this image';
}
else {
echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
}
}
?>
worksafe_mode_script:
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 1) {
$_SESSION['Worksafe_Mode'] = 0;
}
else {
$_SESSION['Worksafe_Mode'] = 1;
}
}
I think ajax is a good approach in your case.
I might do something like display a page of SFW images as the default, along with the toggle button.
When they click the button it triggers an ajax request to the back-end that sets/un-sets the session value in toggleWorksafe.php. Finally it triggers a page refresh.
During the page refresh the PHP code checks whether the session variable is set and shows either the filtered or unfiltered set of images, and changes the button's text to match.
To implement:
Include jQuery in the <head> section (jQuery simplifies the ajax call):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'])) {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
<button id="workSafe" type="button" name="Worksafe_Toggle_Button">
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo 'Hide NSFW images';
}
else {
echo 'Include NSFW images';
}
?>
</button>
<!-- display safe images by default -->
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo '<br/><br/>Showing NSFW images';
}
else {
echo '<br/><br/>Showing safe images only';
}
?>
<!-- any other page content here -->
<script>
$('#workSafe').click(function() {
// ajax request to page toggling session value
$.post("/toggleWorksafe.php")
.done(function(data) {
window.location.href = window.location.href; // trigger a page refresh
});
});
</script>
</body>
</html>
toggleWorksafe.php:
<?php
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 'yes') {
$_SESSION['Worksafe_Mode'] = 'no';
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
there are a couple of ways to do this and it related to how you hide or load you images.
1. simple method
if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:
var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false
function loadImage(nsfw){
if (nsfw){
$.get('nsfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
} else {
$.get('sfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
}
}
and in you button click event:
nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
2. another simple method, but not as simple as the #1
you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.
note: this method still uses cookie
for example the returned list is like this:
[
{"url": "some-image-1.jpg", "nsfw": "true"},
{"url": "some-image-2.jpg", "nsfw": "false"},
{"url": "some-image-3.jpg", "nsfw": "true"},
{"url": "some-image-4.jpg", "nsfw": "false"},
{"url": "some-image-5.jpg", "nsfw": "false"},
{"url": "some-image-6.jpg", "nsfw": "true"}
]
then you just render it when the conditions are met.
function renderImage(nsfw){
$.get('image-list-url', function(resp){
list.forEach(function(val, key){
if (nsfw || !val.nsfw){
$('#container').append('<img src="' + val.url + '/>');
}
});
});
}
and many other methods that are too long to explain, such as using Angular, React, or Vue
still uses cookie for between reloads or backs, and does not regard user's age.
as for the session based approach, you only need that if you need to verify your users age
that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use #KScandrett 's answer
Confirm form resubmission happens because you do not perform a redirect after a successful form submission.
Take a look at this wiki page to see how to do it right. https://en.wikipedia.org/wiki/Post/Redirect/Get

Passing Javascript variable to php on the same page

I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});

How to update a php variable in a HTML document without refreshing the whole page?

I have a webpage that echoes out a list of files(pdfs) that i have uploaded in a MYSQL database. When i upload a new file, i would like to automatically update this list to include the new file that i have uploaded without having to refresh the entire webpage.
This is my HTML code that displays the updated list through the variable $mypdf_list :
<div id="listwrapper_hook">
<div id="dynamic_listwrapper"><hr>
<!--DYNAMIC PDF LIST CONTENT GOES HERE-->
<?php echo $mypdf_list; ?>
</div>
</div>
I have tried the to swap out the 'dynamic_listwrapper' div and then replace it with a new one through javascript in the hope that the displayed 'mypdf_list' variable is refreshed. But this has not worked.
MY javascript code:
//UPDATE 'Recently Uploaded Files'
var wrapper_hook = document.getElementById('listwrapper_hook');
var list_wrap = document.getElementById('dynamic_listwrapper');
wrapper_hook.removeChild(list_wrap);
//Add child again to update the '$mypdf_list'
wrapper_hook.appendChild(list_wrap);
Thanks for all the advice everyone. Ajax call was the way. Here is my solution (which works) in javascript:
// GET REFRESHED '$mypdf_list'
// AJAX CALL
var formdata = new FormData();
formdata.append("update",'refresh');
// create XMLHttpREquest object
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
// HANDLE RESPONSE HERE
document.getElementById('dynamic_listwrapper').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getMypdf_list.php");
xmlhttp.send(formdata);
}
Use ajax for it.
The code will look slightly like this:
setInterval(function () {
var url_to_fetch_pdfs = "www.yourdomain.com/fetch_pdfs.php";
$.ajax({
type: "POST",
url: url_to_fetch_pdfs,
cache: false,
success: function(result){
$("#dynamic_listwrapper").html("<hr>"+result);
}
});
}, 60000); // 1 Minute
In your PHP file you will fetch all the pdf downloads, the result in the ajax variable will be the echo in your PHP fetch file.
Ajax Documentation

Categories