XMLHTTP - Retrieving PHP, but can't perform JavaScript / jQuery - php

So first off, I'm new with jQuery and Ajax. I'm curious to learn more and decided to make a project for myself that is based on Ajax/PHP/jQuery/JavaScript and so on... I want to combine all languages. Now i ran into an problem wich is:
The code of my JavaScript, this call's the PHP file:
function fetchDatabase(method, value) {
document.getElementById("database_result").innerHTML = '<p class="loading">Laden...</p>';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("database_result").innerHTML = xmlhttp.responseText;
}
}
if (value != 'none') {
xmlhttp.open(method, 'php/fetch_browse.php?value=' + value);
} else {
xmlhttp.open(method, 'php/fetch_browse.php');
}
xmlhttp.send();
}
Now here is my PHP file, this fetches data out of my database:
<?php
include('database.php');
if (isset($_GET['value'])) {
$value = $mysqli->real_escape_string($_GET['value']);
$filequery = "SELECT * FROM files WHERE filelocation='".$value."'";
$folderquery = "SELECT * FROM folders WHERE folderlocation='".$value."'";
} else {
$filequery = "SELECT * FROM files";
$folderquery = "SELECT * FROM folders";
}
foreach ($mysqli->query($folderquery) as $row) {
echo '<a class="browseclick">';
echo '<div class="browse-item">';
echo '<img src="img/browse-item/folder.png">';
echo '<p title="' . $row['foldername'] . '">' . $row['foldername'] . '</p>';
echo '</div>';
echo '</a>';
}
foreach ($mysqli->query($filequery) as $row) {
echo '<a class="browseclick">';
echo '<div class="browse-item">';
echo '<img src="img/browse-item/' . $row['filetype'] . '.png">';
echo '<p title="' . $row['file'] . '">' . $row['file'] . '</p>';
echo '</div>';
echo '</a>';
}
mysqli_close($mysqli);
?>
As you can see, in my PHP code the <a>'s have a class: ".browseclick"
I want with jQuery if i click this i can execute a function.
So my jQuery code is:
$('.browseclick').click(function() {
var test = $(this).text() + ' - < This is a test';
console.log(test);
});
But it doesn't console.log() anything. not even the '< This is a test'.
So I tried to put script tags with an alert in the PHP file it self. Also this won't work.
Anyone an idea how i CAN execute javascript with content my ajax has fetched?
Thanks,

Related

I need to refactor this php function

I need to refactor this code, Im not a php developer so i dont understand the syntax thats apparent here, what i want is this button to activate the moment the page is loaded.
<?php
$h = '';
if ($newsermonstomove) {
foreach ($newsermonstomove as $vettel) {
$h .= "<div style=\"padding: 5px;\">";
$h .= "<button id=\"btn_" . $vettel->ID . "\" class=\"btn btn-primary btn-xs\" onclick=\"doMe(" . $vettel->ID . ");\" >s3</button><span style=\"padding-left:5px;\">Channel: " . $vettel->ChannelID . ", Sermon: " . $vettel->ID . " " . $vettel->SermonTitle . "</span> <div style=\"display:none;color:blue;\" id=\"msg_" . $vettel->ID . "\"></div><br/>";
$h .= "</div>";
}
} else {
$h = "<h3>No new sermons.</h3>";
}
echo $h;
?>
From what i understand, the onclick has an escape in it onclick=\"doMe(" . $vettel->ID . ");\" In HTML i know that with a button if you do onclick=doMe its a reference to a function, which i feel like is the same thing thats happening here with the escape keys in it. its making a reference to the function doMe, but i want the function to fire automatically when the page loads.
Ok, i was able to figure out the answer I needed using JQuery.
$("document").ready(function() {
setTimeout(function() {
$(".btn").trigger('click');
},10);
});
essentially what this function does is wait for the page to load then after 10 milliseconds it targets all buttons on the screen with the class name btn and triggers the click functionality of the button, thus firing off the button on the page load.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if (!empty($newsermonstomove)) {
$h = '';
foreach ($newsermonstomove as $vettel) {
$h .= '<div style="padding: 5px;">';
$h .= '<button data-id="' . $vettel->ID . '" class="btn-vettel btn btn-primary btn-xs">s3</button><span style="padding-left:5px;">Channel: ' . $vettel->ChannelID . ', Sermon: ' . $vettel->ID . ' ' . $vettel->SermonTitle . '</span> <div style="display:none;color:blue;" id="msg_'.$vettel->ID.'"></div><br/>';
$h .= '</div>';
}
} else {
$h = '<h3>No new sermons.</h3>';
}
echo $h;
?>
<script>
$(function() {
$('.bt-vettel').on('click', function(e) {
var id = $(this).data('id');
doMe(id);
});
});
<script>

Remove unknown text appearing on page

I have used a widget called addthisevent to allow users to add a class booking to their calendar. It is all working as indented but when I echo the link to the page I get a random ‘1’ next to the button. As you can see here -- http://oi60.tinypic.com/10fu8ac.jpg --
==add_event.php==
<?php
//Call session variables
$start_time = $_SESSION['class_time_start'];
$end_time = $_SESSION['class_time_end'];
$date = $_SESSION['class_date'];
$class_name = $_SESSION['class_name'];
$client_F_name = $_SESSION['firstname'];
$client_L_name = $_SESSION['lastname'];
$client_email = $_SESSION['email'];
//echo addthisevent script
echo '<script type="text/javascript" src="https://addthisevent.com/libs/ate-latest.min.js"></script>';
//echo addthisevent with the variables in place, ready to be converted using the JS function
echo '<a href="http://example.com/link-to-your-event" title="Add to Calendar" class=" addthisevent" id="addthisevent">'
, 'Add to Calendar'
, '<span class="_start">' . $date . ' ' . $start_time . '</span>'
, '<span class="_end">' . $date . ' ' . $end_time . '</span>'
, '<span class="_zonecode">36</span>'
, '<span class="_summary">' . $class_name . ' Class</span>'
, '<span class="_description">Your ' . $class_name . ' class with ****</span>'
, '<span class="_location">*****</span>'
, '<span class="_organizer">*****</span>'
, '<span class="_organizer_email">******</span>'
, '<span class="_facebook_event">*****</span>'
, '<span class="_all_day_event">false</span>'
, '<span class="_date_format">YYYY/MM/DD</span>'
, '</a>';
?>
Let me know if you need more code as I understand this is a weird issue I'm having.
I really can't work out what is causing it. I know it is definitely coming from the php above. If there is a way to fix this issue or just to simply remove the '1' after the page has loaded as a workaround that would be great
Thanks
The page link is http://217.37.5.115/content/temppage.php
you will need to select the dropdown boxes for it to appear
In short:
I use this function below to run a php script when the value of one of the dropdown boxes changes
===temppage.php (main page)===
<script>
function class_space_Update(str) {
if (str == "") {
document.getElementById("class_spaces").innerHTML = "";
return;
} else {
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("class_spaces").innerHTML = xmlhttp.responseText;
addthisevent.refresh();
}
}
xmlhttp.open("GET", "../includes/get/class_spaces.php?id=" + str, true);
xmlhttp.send();
}
}
</script>
===class_spaces.php===
<?php
//Set session variables
//Session 'class_time_start'
$_SESSION['class_time_start'] = $start_time;
//Session 'class_time_end'
$_SESSION['class_time_end'] = $end_time;
//Session 'class_date'
$_SESSION['class_date'] = $date;
//Session 'space_left'
$_SESSION['space_left'] = $space_left;
//Include add_event.php
echo include_once ($_SERVER["DOCUMENT_ROOT"] . "/includes/add_event.php");
//Close MySQLi connection
mysqli_close($mysqli);
?>
This isn't all of that file as it isn't really necessary.
If I comment out the echo include_once add_event.php part then the '1' does not appear.
Quick solution I can offer for you is:
<?php
//Call session variables
$start_time = (isset($_SESSION['class_time_start']))?$_SESSION['class_time_start']:'';
$end_time = (isset($_SESSION['class_time_end']))?$_SESSION['class_time_end']:'';
$date = (isset($_SESSION['class_date']))?$_SESSION['class_date']:'';
$class_name = (isset($_SESSION['class_name']))?$_SESSION['class_name']:'';
$client_F_name = (isset($_SESSION['firstname']))?$_SESSION['firstname']:'';
$client_L_name = (isset($_SESSION['lastname']))?$_SESSION['lastname']:'';
$client_email = (isset($_SESSION['email']))?$_SESSION['email']:'';
//echo addthisevent script
ob_start();
echo '<script type="text/javascript" src="https://addthisevent.com/libs/ate-latest.min.js"></script>';
//echo addthisevent with the variables in place, ready to be converted using the JS function
echo '<a href="http://example.com/link-to-your-event" title="Add to Calendar" class=" addthisevent" id="addthisevent">'
, 'Add to Calendar'
, '<span class="_start">' . $date . ' ' . $start_time . '</span>'
, '<span class="_end">' . $date . ' ' . $end_time . '</span>'
, '<span class="_zonecode">36</span>'
, '<span class="_summary">' . $class_name . ' Class</span>'
, '<span class="_description">Your ' . $class_name . ' class with ****</span>'
, '<span class="_location">*****</span>'
, '<span class="_organizer">*****</span>'
, '<span class="_organizer_email">******</span>'
, '<span class="_facebook_event">*****</span>'
, '<span class="_all_day_event">false</span>'
, '<span class="_date_format">YYYY/MM/DD</span>'
, '</a>';
exit();

How can I post data through a form with ajax and get it working? [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 9 years ago.
I have a piece of ajax script that is trying to post a form for me. Currently without ajax the form will post properly and it will send the data. What I want is an ajax post so it does not refresh the page and it posts the data too. There are multiple forms on one page.
My js script looks like this:
function post_form(action)
{
var token = $('.forms').attr('id');
var itemId = $('.forms').find('input.id').val();
var instaUrl = 'https://api.instagram.com/v1/media/'+itemId+'/likes?access_token='+token+'';
console.log(token);
console.log(itemId);
console.log(instaUrl);
var dataString = token;
$.ajax({
type: "POST",
url: instaUrl,
data: dataString,
crossDomain: true,
dataType: 'jsonp',
beforeSend: function()
{
$("#loading").fadeIn("slow");
if ( action == "like" )
{
$("#open"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else if ( action == "unlike" )
{
$("#close"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else {}
},
success: function(response)
{
if ( action == "like" )
{
$("#close"+comment_id).show();
}
else if ( action == "unlike" )
{
$("#open"+comment_id).show();
}
else {}
$("#loading").fadeOut("slow");
}
});
event.preventDefault();
}
$(document).ready(function() {
$('button.like').each(function() {
$(this).on('click', function(){
post_form();
});
});
});
Now in my markup I have a form that has an id in a hidden input value. The form once posted looks for the id and uses a case switcher with a like ans unlike switch. It uses the instagram php library to connect and get the data for the images as you will be able to see:
try {
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
$liked_media = $current_user->getLikedMedia();
/* echo 'https://api.instagram.com/v1/media/'. $item->getId() .'/likes?access_token='.$token.''; */
if ( isset( $_POST['action'] ) ) {
echo '<br/>FORM IS SUBMITTED, INSPECT WHAT WAS SENT';
print_r($_POST);
$id = $_POST['id'];
switch( strtolower( $_POST['action'] ) ) {
case 'like':
$current_user->addLike( $id );
break;
case 'unlike':
$current_user->deleteLike( $id );
break;
}
}
} catch ( Exception $e ) {
// yes there is an error
$error = $e->getMessage();
}
// view rendering stuff
// display the error
if ( $error != '' )
{
echo "<h2>Error: ".$error."</h2>";
}
echo '<section id="images">';
foreach ( $media as $item ) {
echo '<article class="instagram-image">';
// define the form and set the action to POST to send the data to this script
echo '<form id="'. $token .'" class="forms" action="'; echo URL::current(); echo '" method="post">';
$id = $item->getId();
echo '<a title="' . $item->getCaption() .'" class="fancybox" href="' . $item->link . '"><img alt="' . $item->getCaption() .'" src="' . $item->images->standard_resolution->url . '" /></a>';
echo '<div class="formSubmit-feedback"></div>';
//echo '<img src="/public/img/377.gif" alt="loader"/>';
if ( $current_user->likes($item) ){
echo '<button class="ajax instabtn unlike icon-heart" type="submit" name="action" value="Unlike"></button>';
} else {
echo '<button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button>';
}
echo '<input class="id" type="hidden" name="id" value="'; echo $id; echo '">';
echo '<p>'; echo $item->likes->count; echo '</p>';
//echo '<p>'.$item->getId().'</p>';
//echo '<p>By: <em>' . $item->user->username . '</em> </p>';
//echo '<p>Date: ' . date('d M Y h:i:s', $item->created_time) . '</p>';
//echo '<p>$item->comments->count . ' comment(s). ' . $item->likes->count . ' likes. ';
echo '</form>';
echo '</article>';
}
echo '</section>';
The form works I know that for sure but I really need to know how I can get this to post to the right place and do the switch so it likes/unlikes the image.
Does anyone know a way around this at all?
Thanks
So the database changes happen properly but the page doesn't reflect the change properly?
I'm not sure if the ajax success has action in its scope...try echoing the action in the php script and using the ajax response var to control the images.

how to set pagination on a lot of data rows after selection a option from the dropdown list with onchange event in php

I have a php page on which has a ajax function makerequest(serverPage, objID) , it works fine it has three links they also works fine my content comes on that page in the <div id=pageId>. in this page the third page has a dropdown list populated by mysql with on change event. in this page a lot of rows on every option so I have to decide that the data show on multiple page by php pagination class,it also works fine, but when I click on next page all the data lost due to reload the page and get the default value in the dropdown list.
Some of code content is here:
<div id="menu">
<!-- <a href="?id=AllIndiaengineringCollege" What part we want to link to onClick="makerequest('page.php?id=AllIndiaengineringCollege', 'content'); return false;" For AJAX - Load page into the div>AllIndiaengineringCollege</a>-->
<a href="?id=AllIndiaengineringCollege" onClick="makerequest('id=AllIndiaengineringCollege', 'content'); return false;" style="text-decoration:none;color: #3E5AAB" >All India Engineering College</a>
Deemed Universities
State Engineering College
</div>
</font></div>
<div id='content'style="text-align:left;width:897px; height:auto; background-color:#99CCFF;padding:1px">
<?PHP
if (isset($_GET['id'])) {
$pageId = $_GET['id'];
if ($pageId == 'AllIndiaengineringCollege') {
include("/pagination/index.php");
}
if ($pageId == 'Deemed') {
include("/pagination/state.php");
}
if ($pageId == 'state') {
include("/pagination/state.php");
}
}
?>
</div>
it works fine
my third page is
<?php
$result = mysql_query("SELECT Id,state FROM state");
echo "<select name=State id='Id' class='select' onchange='showUser(this.value)'>";
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
echo "</select>";
?>
</div>
<div id="state"><b><center>xxxxxxxx.</center></b>
showUser function is like here
function showUser(str) {
if (str == "") {
document.getElementById("state").innerHTML = "";
return;
}
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("state").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "pagination/statelist.php?state=" + str, false);
xmlhttp.send();
}
And the pagination code is like here:
<?php
include('db.php');
include('function.php');
$q = $_GET["state"];
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 2;
$statement = "college where State= '" . $q . "'";
$url = "BTech.php?id=state&State=" . $q . "&";
$startpoint = ($page * $limit) - $limit;
?>
I think if you corrected this, it would be fine
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
as something like this,
while ($nt = mysql_fetch_array($result)) {
echo "<option value=\"{$nt['Id']}\"".(($State===$nt['Id'])?'selected="selected"':"") .">{$nt['state']}</option>";
}
You can't evaluate conditions that way, nested echo wont work either.
Look at this previous SO question

jquery add to array then submit and pass data not working

My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']

Categories