what is wrong in this code? - php

I have to use this piece of code to save some values in table when page loads. The function to search values is in php. I have to use those values in script. I am trying this way but its not working.
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
var msg_top = new array();
msg_top = "<"+"?php echo searchResults('windows');"+"?"+">";
var url = "msg2_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
alert('POST');
} else {
alert(request.status); //
}
}
}
request.send("msg_top=" + encodeURIComponent(msg_top).replace(/%20/g, '+'));
});
</script>

if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}}
Should probably be something like:
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
If you pay proper attention to your indentation, you'll notice you never end the anonymous function you create at:
request.onreadystatechange = function(){

Related

how to load php action page instead of php file in javascript?

<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
}
</script>
Code is working 100% but my problem is in script in place of getuser.php i want to use action for example "action=records" . what should i change

ajax search with input field

I am trying to create a ajax function to just reload a <div> and not the entire page.
What is working:
-during writing in the input field the div is reloaded after every character correctly.
What is not working:
-when the input field is complete empty again, it is not showing the whole entries I have in the database.
this is what I have in the php file where the div is:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
} }
this is what I have in the search.php
<?php
include 'test/database.php';
$pdo = Database::connect();
if($_GET['game'] == "") {
$sql="SELECT * FROM games WHERE active=1";
echo "<script type='text/javascript'>alert('Should be empty')</script>";
} else {
$q = $_GET['game'];
$sql="SELECT * FROM games WHERE gamenamelong LIKE '%".$q."%'";
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
$gameResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rowCount1 = count($gameResults);
Is anybody able to help me?
Thank you!
since we don't know how your form looks like, and what calls the function showGames how, I can only give a vague answer. But your main problem/misstake should be solved with that:
In your function showGames you never hit the ajax if the search string is empty, so you can't get back all results.
So I suggest to change that function like so:
function showGames(str) {
if (str == "") {
document.getElementById("searchgame").innerHTML = "";
//remove that: return;
}
// remove the 'else { '
// now you allways hit the ajax
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("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","searchgame.php?game="+str,true);
xmlhttp.send();
// remove closing bracket of if-else: '}'
}

Make an error to pop-up without refresh

I have this php code, which basically checks if the e-mail is correct and if it is, it saves the e-mail in a *.txt file (I'm using it for a subscribe form), if it's not it pop-ups an error div, but it pops it up with refreshing the whole web page, and when it's in the bottom you have to scroll to actually see the error.
<?php
if ( isset($_POST['submit']) ) {
if( isset($_POST['inputEmail']) ) {
$email = trim($_POST['inputEmail']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<div class='wrong'>This e-mail is invalid.</div>";
}
else {
$data = $email . "\n";
$ret = file_put_contents('emailAddresses.txt', $data, FILE_APPEND | LOCK_EX);
if ( $ret !== FALSE ) {
header('Location: thanks.html');
exit;
}
}
}
}
?>
What you want to do is send your request with AJAX using javascript or jQuery.
With JavaScript:
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
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 ) {
if(xmlhttp.status == 200){
//Request worked, Do something
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
With jQuery:
$.ajax({
url: "test.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});

AJAX/Jquery/PHP - Load page dependant on anchor/hash tag

I have the following code which works great:-
$('.ajax a').click(function() {
getpageajax(this.href);
return false;
});
function getpageajax(getpage) {
if(getpage == "") {
//SET ERROR?
document.getElementById("main").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("main").innerHTML = xmlhttp.responseText;
}
}
var urlarray = getpage.split('/');
location.hash = urlarray[urlarray.length-1];
xmlhttp.open("GET", "includes/AJAXgetpage.php?getpage=" + getpage, true);
xmlhttp.send();
};
Only problem is that I have no idea how to get then read the anchor links I create (e.g. #contact-us) to create bookmarkable pages.
I tried to do a solution based around the following but it seems less than ideal
<script>
var query = location.href.split('#');
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
To get the hash, other than your initial example, you can use window.location.hash
// example url - http://www.mysite.com/blog/post#comments
var hash = window.location.hash; // = "#comments"
You can use replace to get rid of the leading # if required.

Simple PHP, AJAX request

Right now I'm struggling to get this simple PHP AJAX request to work.
<html>
<head>
<script type="text/javascript">
function getSuggestions(type){
if(type == "")
{
document.getElementById("entries").innerHTML="test"
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("entries").innerHTML=xmlHttp.response;
}
}
xmlHttp.open("GET","getData.php?status="+type,true);
xmlHttp.send();
}
</script>
</head>
<body>
<div id="A" onclick='getSuggestions("A")'>Click for A</div>
<div id="P" onclick='getSuggestions("P")'>Click for P</div>
<div id="R" onclick='getSuggestions("R")'>Click for R</div>
<div id="entries"></div>
</body>
</html>
Below is getData.php
<?php
$status = $_GET["status"];
echo $status;
?>
Everytime I click on any of the tags I get "undefined" in the "entries" tag. Could anybody explain why it's undefined?
use xmlHttp.responseText
This is how I handle AJAX. Essentially an example of akellehe's answer
function getSuggestions(type){
if(type == "") {
document.getElementById("entries").innerHTML="test"
return;
}
var r = getXmlObject();
var url= "getData.php?status="+type;
if (r.readyState == 4 || r.readyState == 0) {
r.open("POST", url, true);
r.onreadystatechange = function (){
if (r.readyState == 4) {
document.getElementById("entries").innerHTML= r.responseText;
}
};
r.send(null);
}
}
////////////////////////////////////
function getXmlObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.');
}
}

Categories