I am currently developing a system which user can only view the name with the start character.
Below is the example :
When I click on the "A" link, the below table will show the name which start from "A" and will not shows the rest of the records.
I am trying to use href to pass operation to my php but it is not flexible to do so. Therefore, I looking for javascript to help me go through this. What I want to do is the page will not refresh and will direct change the content when I click on the A~Z link.
This is my HTML code :
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
This is my php page which execute data from table :
$rsa = array();
$sqladded = false;
$appliedfilter = array();
if($_REQUEST['op'] = ''){
$record = 'A';
}
else{
$record = $_REQUEST['op'];
}
$stmt = $getuser->getuser($record);
if ($rs = $db->Execute($stmt))
{
$arrResult = array();
while($rsa = $rs->FetchRow())
{
array_push($arrResult, array(
"name" => $rsa['name'],
"mobile_no" => $rsa['mobile_no'],
"email" => $rsa['email'],
"address" => $rsa['address'],
"current_professional" => $rsa['current_professional'],
"others" => $rsa['others']
));
}
$tpl->display("alumni-listing.html");
}
And this is my SQL statement :
function getuser($record)
{
global $db;
$arrResult = array();
$stmt = "SELECT * FROM "._CONST_TBL_ALUMNI." WHERE name LIKE ".$record."%";
if($rs = $db->Execute($stmt))
{
$arrResult = $rs->GetArray();
}
return $arrResult;
}
Hope someone can help me.
Thanks in advanced.
Anyhow you have to use the calls to the PHP page.
If not then you can make a the 1st call load all data (A-Z) and then display the connects with just a click. But then your 1st call would be big and it will take time to load if data is greater.
You can use Ajax calls.
Structure your HTML as this way.
<li><a href="#" class='ajaxCaller>A</a></li>
<li><a href="#" class='ajaxCaller>B</a></li>
<li><a href="#" class='ajaxCaller>C</a></li>
<li><a href="#" class='ajaxCaller>D</a></li>
<li><a href="#" class='ajaxCaller>E</a></li>
<li><a href="#" class='ajaxCaller>F</a></li>
The Ajax calls should be
$('a.ajaxCaller').click(function(event){
event.preventDefault();
var x=$(this).text();
$.ajax({
url: "alumni-listing.php",
data: {op:x}
}).done(function() {
// You can have your code to set the returned page, to the specific div.
});
});
I have made lots of project like the one you ask. Learning to use jQuery a javascript framework would be the best solution to solve the task. jQuery made ajax process very simple using jQuery.post().
So the way I see it, your problem boils down to dynamically querying the database on a Dom-event (i.e, through javascript) and not navigating to a different page. Which is lucky, because AJAX was developed pretty much for this - smaller 'refreshes'.
Use JS to trigger a php request, and parse the return
Check out jQuery's Post. I am sure it can be accomplished without, so please edit the question if jQuery is a no-no. If you change your php page to just echo a JSON of the result, and call if from JS, you can parse the JSON and display it in the html page.
HTML
<li><a class="listing-filter" href="alumni-listing.php?op=a">A</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=b">B</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=c">C</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=d">D</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=e">E</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=f">F</a></li>
Javascript
$('.listing-filter').click(function (e) {
var $filter = $(e.currenttarget),
filterValue = $filter.html();
RefreshPageWithData(filterValue);
});
function RefreshPageWithData( filterBy ) {
var data = {
op: filterBy,
};
$.post(pathname-on-server.php, data, function (response) {
//Parse the response
var results = JSON.parse(response);
//Construct the DOM
var newHtml;
//Append it to existing element
$('#container').html(newHtml);
});
Please note that anything you echo in the php page is the response passed back to the JS callback. So, a simple idea might be to echo json_encode($arrResult). I suggest having one index.php that serves the file as you do above, and another that does similar tasks but echoes the retrieved data. This avoids a double-server request for the homepage.
Related
i have a file main.js where every step pass selected variable to php page, i need pass some variable to another one php page.
this is piece of code of main.js, i tryed to get 'optionsContent' variable and put in a index.php page in a 'div id="rip" with 'document.getElementById("rip").innerHTML = optionsContent;' but tryed to pass this variable with 'href' in new.php page and not work
if( selectedOptions.length == 0 ) {
optionsContent = '<li><p style="color:#FF0000">Nessuna Riparazione Selezionata</p></li>';
} else {
selectedOptions.each(function(){
optionsContent +='<li><p>RIPARAZIONE '+$(this).find('.searchText1').text()+'</p>'+' - '+'<p style="color:#0012ff">' +$(this).find('.price').text()+'</p></li>';
//optionsContent +='<li><p>'+$(this).find('p').text()+'</p></li>';
//document.getElementById("new").innerHTML = optionsContent;
document.getElementById("rip").innerHTML = optionsContent;
});
}
self.summary.find('.summary-accessories').children('li').remove().end().append($(optionsContent));
}
});
index.php page
<div id="rip">** HERE GET 'optionsContent' VAR CORRECTLY **</div>
<li class="next nav-item">
<ul>
<li class="visible">Modello</li>
<li>Colore</li>
<li>Riparazione</li>
<li>Sommario</li>
<li class="buy">Prenota</li>
</ul>
</li>
in new.php page
<?php
$riparation = $_GET['riparation'];
?>
<input name="riparation"><?php echo $riparation; ?></input>
but doesnt work
any help?
You can use cookies or data storage API for saving data between pages.
index.html:
<?php
// set the cookies:
setcookie("riparation", "myDataFromApp");
// Render the page:
echo "<h1>This works!</h1>"
?>
Another page (jQuery cookie plugin required):
var riparation = $.cookie("riparation"); // riparation = "myDataFromApp"
I'm using Jquery mobile, and I want to create a clickable view list in my panel. to look something like this...
<li><a href='#' onclick='getmoviepic_mobile(this) ;' > MovieTitle"</a>
</li>
MovieTitle is obtained from my MYSQL database array using json_encode($x) so when the user clicks on the title the function getmoviepic_mobile(this) is triggered.
My question is how to set up my javascript with json data to populate my html
page.
My HTML
<div data-role="panel" id="Panelcategory" >
<ul data-role="listview" data-inset="true" id="MovieTitle">
<li></li>
</ul>
</div >
PHP getcatagories2_mobile.php
<?php
include("includes/connection.php");
$q=$_POST['input'];
$resultActor = mysqli_query($con,"SELECT id,title,
plot,catagory,release_date,rated FROM ".TBL_DATA." WHERE catagory LIKE
'%".$q."%' ORDER BY title ");
while($rowMovie = mysqli_fetch_array($resultActor)) {
$x[]=$rowMovie['title'];
}
$jsonarray=json_encode($x);
echo $jsonarray;
?>
Javascript
function getcatagories(catagory){
var catagoryValue = $(catagory).text();
$.getJSON( "getcatagories2_mobile.php", {input:catagoryValue},
function(json) { this is the part I am stuck on
}
not sure even if my HTML is set up correctly maybe don't need the "li".
thanks guys
I would iterate through the JSON and add attributes by key. For example, you could query the list and add each value.
$("#MovieTitle").append("<li>" + json["category"] + "</li>")
And do so for each key-value pair you want to include.
I'm moving a php / js / ajax script to wordpress
I encountered something that i've never seen before, I understand what it does, but i'm trying to figure out how to make this work for wordpress.
the code:
<a id="a" class="tab block sel {content:'cont_1', ajaxContent:'php/templates.php',ajaxData:'type=pistols'}">Pistols</a>
<a id="b" class="tab block {content:'cont_2', ajaxContent:'php/templates.php',ajaxData:'type=rifles'}">Rifles</a>
<a id="c" class="tab block {content:'cont_3', ajaxContent:'php/templates.php',ajaxData:'type=shotguns'}">Shotguns</a>
<a id="d" class="tab block {content:'cont_4', ajaxContent:'php/templates.php',ajaxData:'type=cameras'}" >Cameras</a>
<a id="e" class="tab block {content:'cont_4', ajaxContent:'php/templates.php',ajaxData:'type=audios'}" >Audio</a>
Templates PHP:
if(isset($_POST['type'])) {
//The div for the manufacturer tabs, uniquely identified by the $_POST['type']
echo "<ul id=\"".$_POST['type']."\" class=\"shadetabs\" style=\"position:relative; top:-12px; width:905px;\">";
if ($_POST['type'] === 'pistols') {
$manufacturers = .. and so on
From what i can understand, we are calling Templates.php and passing $_POST['type']. When this is compoleted, the script replaces the content of a <div id="cont_1"
in wordpress, i can't call random php files, since ajax will not work. I need to turn this into a function and hook it to wordpress.
Does anyone know how this type of code works?
As alternative, I'm planning to do the following, but I would prefer to keep it similar to the original code and this will need lots of extra lines of code.
var tab = jQuery("#a").type;
jQuery.ajax({
url: custom_designer.ajax_url,
type: 'post',
data: {
action: 'php_template_function'
type: tab
},
success: function (response) {
document.getElementById('caseclub_response').innerHTML = response;
document.getElementById("buy_case_foam_added").submit();
}
});
Does anyone know how this type of code works?
It looks like there is some JavaScript that extracts the object string from the class attribute, then fetches the HTML from template.php and writes it somewhere.
For example:
function fetchList(element) {
var settings = element.className.match(/\{.+\}/);
settings = eval('(' + settings[0] + ')') // eww
fetch(settings.ajaxContent, {
method: 'post',
body: settings.ajaxData
}).then((response) => {
// Error handling...
response.text().then(() => {
// Now writes the HTML somewhere...
});
});
}
If you want to copy what they did, see if you can find the original code using the Inspector.
I got couple of li elements and using them as a links to welcome.php. In welcome.php I need to know which one was clicked.
<ul>
<li><a href='welcome.php'>sport</a></li>
<li><a href='welcome.php'>relax</a></li>
<li><a href='welcome.php'>gym</a></li>
</ul>
I can't use jquery. Is there any other way to do this?
The simplest way to do this might be to append a query parameter to your links:
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
you can incorporate the value in the links and get them with PHP like this
<a href="welcome.php?x=sport">
Where x is the variable you're going to get by using this in your php:
$x = $_GET["x"];
You'd need to do the same with all other links. but you only need to get the value once ofcourse
I was a little bit too late with posting this, but I think mine might have a better explaination so I'm keeping it
You can use $_GET for post value of li
I prepare an example for you
index.php
<form action="welcome.php" method="post">
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</form>
welcome.php
$var = $_GET["var"];
echo $var;
I have prepare one solution for you using simple html and Javascript :
<html>
<body>
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</body>
<script>
var el = document.getElementById('sport');
el.onclick = showMsg1;
var el = document.getElementById('relax');
el.onclick = showMsg2;
var el = document.getElementById('gym');
el.onclick = showMsg3;
function showMsg1() {
//alert('Sport Clicked!');
//Do what ever you want after click of "sport"
window.location = "welcome.php?type=sport";
return false;
}
function showMsg2() {
//alert('relax Clicked!');
//Do what ever you want after click of "relax"
window.location = "welcome.php?type=relax";
return false;
}
function showMsg3() {
//alert('Gym Clicked!');
//Do what ever you want after click of "Gym"
window.location = "welcome.php?type=gym";
return false;
}
</script>
I am sure this will helpful to you. Thank you :)
I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.
There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).
Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.
Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});