ajax query on secondary page - javascript

Background
I've read through several posts and tutorials here on AJAX, and I've gotten it to work great - on one page, but I'm still new to utilizing AJAX so I hit a rough spot that I can't understand how to fix.
I have my main page, ajaxtest.php which contains a drop-down with this code:
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?></select></a>
which pulls this function:
<script>
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Sending the selection from the database off to my second page, getuser.php.
The user then sees the rest of the initial page populated with the results of getuser.php, which contains the bulk of my code and the HTML tables populated with the SQL info.
This is working fine.
Issue
My issue stems from the fact that once (and pardon my lack of technical jargon,) getuser.php is populated into the <div> that is inside of ajaxtest.php, I can't utilize any other JavaScript or AJAX functions or the entire page just refreshes as if I were to reload ajaxtest.php again from scratch and it puts me back to the initial blank screen with the dropdown menu.
On getuser.php, within the <form> that surrounds the entire table, there is a submit button:
<form action="" method="POST" onsubmit="test()">
and
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
and this is supposed to link to my JavaScript test() function that simply reads:
function test() {
alert("yo");
}
but when I click the button, the entire page refreshes instead of executing this function. Why is this?
If I manually go to localhost/getuser.php?q=John%20Doe instead of "having this page load inside of my ajaxtest.php <div>" and click the button, it works just fine and I get the JavaScript alert to pop up. What am I doing wrong here?

Try editing the function test() to return false
function test() {alert("yo"); return false}
and change the line
<form action="" method="POST" onsubmit="test()">
into
<form action="" method="POST" onsubmit="return test()">
Now it shouldn't refresh the page. Function used in onsubmit needs to return true or false.

Related

why does my browser reloads when using ajax?

i created an ajax function that when clicked by a user it adds a messages to his favorites tab. i want it to work similar to a twitter like button so when a user clicks the favorite button it does not reload the page. i created everything correctly and even the ajax function calls the php file and inserts everything into the database, its just that it still reloads the page after the clicking.
my ajax code:
<script>
function GetXmlHttpObject() {
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
r eturn xmlHttp;
}
function ajaxfav(){
var xmlHttp=GetXmlHttpObject();
var url="favorite.php?message="+document.msgidform.fav_message.value;
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
alert("Message is favorited");
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
</script>
my php code:
$user_id = $_SESSION['active_user_id'];
extract($_POST);
extract($_GET);
if(isset($_GET['message']))
{
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result-bindValue(1,$user_id);
$result-bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery-execute();
}
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
my html code:
<form name="msgidform" method="post">
<input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
</form>
<a class="msg-icon" href="" onclick="ajaxfav();"><img
src="images/linedfav.png" id='img'></img></a>
why does my browser still reloads even though i am using ajax?
It's is because you're using <a> tag, even in you don't provide a href attribute it will redirect you, in your case to homepage that's why you have the reload effect. A way to solve it would be to create a fake anchor tag by using <span>tag that would have the styles of <a> tag and attaching your ajax function to the <span> tag

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} 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("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

Submit issues with form that interact with an API

I have a form that interacts with an API, I used a simple auto submit:
<script type="text/javascript">
window.setTimeout(function(){
document.getElementById('formSubmit').submit();
},1000*20);
</script>
and it worked great in the testing environment. We moved into a new environment and the setup of the hardware was slightly different, realized that didn't work and altered it. Now my auto submit isn't working. The API developers suggested I use watchdog instead so I applied a code according from #Drakes and modified it to interact with my application. This also did not work. I am a noob with Watchdog, and most things in the development world, did I skip a set up with watchdog that wasn't referenced in the previous question?
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
setInterval(function(){ watchdog(); }, 20000);
I think you haven't posted the field values [Fields of the form]. The AJAX code you have used is checking if some value got changed or not every 20 second. But as much as I can understand you wanted to submit your form every 20 second. In that case the AJAX post code need some editing. May be the following thing can solve your problem. Here I am assuming your form having two fields and hence two values are getting submitted. If you have more then you have to modify it as per your requirement.
EDITED MY TESTCODE (This is tested)
The html code along with the AJAX script is as follows -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function watchdog(value1,value2) {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// write any code as this block will be executed only after form succesfully submitted.
document.getElementById("showresponse").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);// You can use this responseText as per your wish
}
}
xmlhttp.open("POST","process.php?value1="+value1+"&value2="+value2,true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
window.setInterval(function(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
// thus store all required field values in variables ,
//here as instance I am assuming the form has two fields , hence posting two values
watchdog(value1,value2);
}, 20000);
function submitIt(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
watchdog(value1,value2);
}
</script>
</head>
<body>
<form id="formSubmit">
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<button type="button" onclick="submitIt();">Submit</button>
</form>
<div id="showresponse"></div>
</body>
</html>
The php code of process.php will be as follows -->
<?php
if(isset($_REQUEST['value1']) && isset($_REQUEST['value1']))
{
$value1 = $_REQUEST['value1'];
$value2 = $_REQUEST['value2'];
echo "Values are respectively : " .$value1." and ".$value2;
}
else
{
echo "Data not found";
}
?>
While testing the above code sample dont forget to keep both html and process.php files in same folder and then test it. The above shown "Run Code snippet" button will not show you any effect of the php code as it only runs html and javascript. So to test it properly you should keep it on some server - local or online .

php javascript code to call php function from javascript

Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.

Applying AJAX to rating system

So I've create this rating system that sends number 1-5 to a textfile, depening on which star the user clicked on.
At the same page we have a counter who counts number of votes, and the total amount of all votes.
The progress works fine, but I want to enchance it some.
Here is my code:
<form name="Star" id="Star">
<div id="rating-area" class="shadow">
<img src="star-icon.png" id="thumb1" data-value="1" />
<img src="star-icon.png" id="thumb2" data-value="2" />
<img src="star-icon.png" id="thumb3" data-value="3" />
<img src="star-icon.png" id="thumb4" data-value="4" />
<img src="star-icon.png" id="thumb5" data-value="5" />
</div>
</form>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ Star : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes in file: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Total: " . $sum;
?>
Im kind of new to this php, but is it possible to do an AJAX request so that we don't have to reload the page to get the updated count numbers?
What I need help with is to create an AJAX call so when the user onclick a star, the page will call for data from the textfile without realoading the whole page.
I think I posted all the necassary information, if not, please tell me and I will edit and try to give you the information.
Firstly I would rather store this information in database than a text file but the concept is the same.
1.) Create a new PHP that reads the text file and gets the new 'Count' of votes or 'Score' whatever information you want to send back. For simple usage I would just echo this value.
2.) Add some more Javascript to go fetch this value after we have added the users count.
The example below gives a good overview of the concept (From W3Schools - http://www.w3schools.com/php/php_ajax_database.asp). This example would take and then replace the return value into the webpage with the css 'ID' of 'txtHint'. This specfic example also gets the entire page and loads it into this ID, this will be fine if you are only echo'ing the vale to your browser.
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
This should help you out, if you struggle getting it to work post back your code and can debug on from that.

Categories

Resources