how to automatically submit form using which uses ajax and asp? - php

I want to get details from one site. That web page is having 3 different select box:
1) Choose Branch
2) Choose Semester
3) Choose Exam Year and then click on show button. This site is using AJAX to show table(output).
I tried with HTML dom parser but don't know the parameters to be passed with that. How to automize such thing which works(submit) with AJAX?
My code is:
<?php
include('simple_html_dom.php');
$html = file_get_html("http://www.abc.com/Engineering-Degree/ExamPapers/ExamPapers.aspx");
foreach($html->find('select[id=Branch]') as $branchSelect)
{
echo $branchSelect;
foreach($html->find('select[id=Semester]') as $semSelect)
{
echo $semSelect;
foreach($html->find('select[id=Exam]') as $examSelect)
{
echo $examSelect;
echo "<input type='submit' value='Show' id='BranchSemesterExamBtn'/>";
}
}
}
?>

Those selects are using get method to retrieve data maybe. Goto you browser console(F12) and change those select options. You may get the links there.

Related

PHP Populate Dropdown From Database and then Update on Button Click

I'm having trouble populating a dropdown list from a database and then updating the selected item on a button click. What I'm trying to have is that when you pick Option B in the dropdown, it'll update that option on the click of a submit button.
I can get the dropdown box to populate fine, but when clicking the button it won't update correctly. I'm learning as I go, any pointers would be appreciated.
<form id='filter' name='filter' method='post' action=''>
<?php
$getIssuedVouchers2 = "SELECT * FROM vouchercodes WHERE status = 'Active'";
$issuedVouchersResult2 = mysql_query($getIssuedVouchers);
?>
<select>
<?php
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
echo "<option name='updatestatus'>" . $ivSelectRow['vouchId'] . "</option>";
}
?>
</select>
<INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit" />
<?php
if(isset($_POST['Submit'])) { //if the submit button is clicked
$updatingQuery = "UPDATE vouchercodes SET status='Expired' WHERE vouchId = '".$ivSelectRow['vouchId']."' ";
mysql_query($updatingQuery) or die("Cannot update");//update or error
}
?>
</form>
PHP is a server side language. It runs once when you request the page, and after it is done it serves the page to you. It does not run until you do another page request, which PHP can't do because that's a client side action.
What you are looking for is Javascript and Ajax. They are client side languages. I'd recommend using Jquery for this, it's pretty easy to use once you get the hang of it. It makes it a lot less awful than standard javascript.
If you aren't wanting to avoid a page reload (submit -> handler -> page reload), I can cook up an answer for you for that. Maybe.
Update from your comment:
You want to set the "selected" attribute, which makes that option selected on page load, correct? e.g. pick the second item in the dropdown instead of the first.
You need to use the selected attribute on your option tag. That makes it selected.
Here's an example I use on one of my sites.
<select data-wavenum='<?=$i;?>' id="enemy<?=$i;?>" name="enemy<?=$i;?>" class="enemylist">
<option value="assaulttrooper" <?=($enemy == 'assaulttrooper') ? "selected" : ""?>>Assault Trooper</option>
This prints out something like:
<option value="assaulttrooper" selected>Assault Trooper</option>
In this case, $enemy is my item that makes me print selected out which makes that option be selected.
In your case, this is what it would be. It's kind of ugly. I think I fixed some of your code, but without the DB backend I can't test.
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
$selected = false;
if (isset($_POST['Submit'])) {
$selected = ($_POST['vouchId'] == $ivSelectRow['vouchId']);
}
echo "<option name=".$ivSelectRow['vouchId']." ".($selected) ? "selected" : "".">" . $ivSelectRow['vouchId'] . "</option>";
}
Please be aware that I could change the option name or send a POST that would cause you to expire a value, or delete your entire table as your data is not sanitized.

Pass data from php mysql to pop up on same page

I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery

Approved method to navigate between pages on same website

I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.

change the value of session variable

I have created a website in which when user logs in he specifies the year i.e. 2013-2014, or 2014-2015, and so on...Now, I am storing this value of year in a session variable which I am using it through out the site. Now, if user wants to change the year he will have to sign out and then log in with different year. I have created a dropdown menu on home page which will show all the years from database. I want to change the value of the session variable by selecting a year from home page without signing out.
Here is the code:
session_start();
if(!isset($_SESSION["myusername"])){
header("location:login.php");
}
$year = $_SESSION["year"];
Here is the code for dropdown menu:
$query = "SELECT * FROM year";
$result = mysql_query($query);
echo "<select class='innerinputstyle' id='year' name='year'><option value='$year'>$year</option>";
while($note=mysql_fetch_array($result)){
echo "<option value=$note[year]>$note[year]</option>";
}
echo "</select>";
Can anyone please tell me how to change the value of $year from home page?
I think you have plenty of choices to achieve this, and the AJAX one is one of them , but everything depends on how you want to implement the user interface. You can think to create a little form with the drop down and submit the year, you can do this via a submit button or via javascript and as for the AJAX example the solution is always the same:
$_SESSION['year']=$_GET['year'];
At the end depend all on the user interface, if you want it invisible to the user, without refreshing the page, use AJAX, otherwise just submit your input
Change
echo "<select class='innerinputstyle' id='year' name='year'>"
into
echo "<select class='innerinputstyle' id='year' name='year' onChange='doIt()'>"
and here is the ajax function
function doIt(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
}
var new_year = document.getElementById('year').value;
xmlhttp.open("GET","change_year.php?year="+new_year,true);
xmlhttp.send()
return false;
}
on change_year.php you can easily change
$_SESSION['year']=$_GET['year'];
Warning: Untested code. Used to sketch the idea.

How to get the second value in a dropdown box based on the selected one in the first dropdown box

I have written the following code in PHP to generate two dropdown boxes on the same page.
The first dropdown box gets value from a MySQL table. This dropdpwn box contains some UserIDs. The second dropdown box contains some dates which should be based on the UserID that is selected in the first dropdown box. I have filled the 2nd dropdown box with all the dates in the MySQL table, but, it should be filtered by the UserID which is selected on the first dropdown box.
Just to inform, with these two values from these two dropdown boxes in this PHP page, I have posted them by pressing the submit button to another PHP page to process some other work.
I would appreciate if you can help me to fill the second dropbox only based on the UserID selected on the first dropbox. Here is the code I have written to display and fill those dropdown boxes. Can you please inform me, what part of the code I should modify and I would appreciate if you can show me the modification code as well. I am a newbie in PHP, that's why I am asking for code level help.
My code:
<html>
<head>
<title>
Search Alert DB
</title>
<body>
<br />
<?php>
$con = mysql_connect("localhost","root","root"); // (host, user,pwd)
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
echo "<p> Search Alert database </p>";
echo "<br />";
$result = mysql_query("SELECT distinct(UserID) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$options="";
echo "<form action='Search_AlertDB_process.php' method='POST'>\n";
//echo "Please choose a user: ";
echo "Please choose a user: <select name = userid>";
echo "<option>-Select-";
while ($row = mysql_fetch_array($result))
{
$userid=$row["UserID"];
$options ="<option value = \"$userid\">$userid </option>";
echo "$options";
}
echo "</select>";
echo "<br />";
echo "<br />";
$dayresult = mysql_query("SELECT distinct(Occurred_date) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$dayoptions="";
echo "Please pick a date:<select name = day>";
echo "<option>-Select-";
while ($row=mysql_fetch_array($dayresult)) {
$day=$row["Occurred_date"];
$dayoptions ="<option value = \"$day\">$day </option>";
echo "$dayoptions";
//$options.="<OPTION VALUE=\"$id\">".$day;
}
echo "</select>";
echo "<br />";
mysql_close($con);
?>
<br />
<input type="submit" name="Submit" value="Search" /> <br /> <br />
</form>
</body>
</html>
You'll need 3 things
Initial page with select fields
The first select field is pre-populated with user ids
The second field contains no options and is disabled
A separate endpoint/page that takes a user id as a parameter to return relevant dates
It should probably return JSON/XML (or something similar), or you could return the dates pre-rendered in <option /> tags (shouldn't really do this, but it would be quicker to hack this together)
Javascript callback triggered when an option in the first dropdown is selected. The callback should send an AJAX request to the separate endpoint and populate the second dropdown with the result.
It would have probably been easier for me to write it all out for you than [try] to explain it, but that's not really the point. Just trying to set this all up (all be it; relatively simple) will teach you a whole load of things about Javascript, AJAX and web services.
If you choose to return JSON/XML from your web service (the separate endpoint/page), and hopefully you will, you might also start to see the benefit of separating logic from presentation, which will make the world of difference to both your understanding and delivery of code.
Well, we wont write the code for you. Otherwise you are going to be newbie for all your life :)
What you need here is called AJAX. The easiest way to implement it is probably jQuery ajax function. If you don't know jQuery - learn the basics, it shouldn't take more than an hour or so. It's worth it :)

Categories