I have an index.php page where there are 2 kinds of queries first is location and secondly the search query. I am using ajax on location query
html structure :
<ul class="dropdown">
<li>City</li>
<li>North</li>
<li>South</li>
</ul>
<form action="" method="post">
<input type="text" name="search" id="search">
</input value="submit" type="submit"/>
</form>
<div id="content_from_AJAX">
<ul id="li_start">
</ul>
</div>
The ajax.js code :
$(document).ready(function(e) {
function getLoc(param){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("li_start").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getresult.php"+param,false);
xmlhttp.send();
}
//handle anchor clicks
$("ul#location li a").click(function(){
var loc = $(this).attr("href");
getLoc(loc);
return false;
});
});
the getresult.php code :
require ('connect_to_mysql.php');
if(isset($_GET['loc']) && empty($_GET['loc'])===false){
$loc = mysql_real_escape_string($_GET['loc']);
$query = "SELECT * FROM TB_name WHERE loc=";
}
else{
$query = "SELECT * FROM TB_name";
}
$query_run = mysql_query($query);
$count = mysql_num_rows($query_run);
if($count<1){
echo 'no result found';
}
else{
while($result == mysql_fetch_assoc($query_run)){
echo "ALL results";
}
// Here is what I want to be able o access on index.php
return $_GET['loc']
}
I want the $_GET to be accessed on index.php so I can use it to filter result on search queries on the form above ie:
"SELECT * FROM `TB_name` WHERE `keyword` LIKE '$keyword' AND `loc`='".$_GET['loc']."'"
//I need to do this on index.php not on getresult.php
And also I want the AJAX.js to send queries on getresult.php if a user clicks on the loc links if the $_POST['search'] isset.
Please help really need this project and I am starting to be so depressed X_X.. Thank you any help is appreciated alot :)
change this
xmlhttp.open("GET","getresult.php"+param,false);
to
xmlhttp.open("GET","getresult.php?loc="+param,false);
^^^^ // forgot ?loc=
then use $_GET["loc"] in your getresult.php page.
Why have you put your function in document.ready() ?
If it would be me then i would have done like this
function getLoc(param){
$.get('getresult.php',{loc:param},function(data){
//Do some stuff with data
});
}
Your code needs some rethinking. You have a dropdown with href links in it and a form that submits information (which it shouldn't if you want ajax results).
And why is your getresults.php doing a database query and then returning the GET variable back. That makes no sense, because the database query is now pointless as its results are not used for anything.
What I think you want is onClick event listeners on the dropdown, and then have an Ajax request fire on each change, the getresults.php file then does a MySQL search and returns the results of the search (not $_GET['loc'] as index.php already knows this value).
Also, use mysqli* or PDO for your database queries, the mysql* set of functions are now deprecated and prone to sql injection.
Related
I want to display the contents of the php file and I tried to include the php file in ajax but it doesn't work.
solution 1 doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
solution 2 still doesn't work
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'<script type='text/javascript' src='wotd.php'></script>";
Here's the code for ajax if there's no input it will display the word of the day
function showMeaning(word)
{
if(word.length == 0)
{
document.getElementById("txtMeaning").innerHTML = "<center><img src='images/img_layout/exploro_logo.png'><?php include 'word.php' ?></center>";
//the word of the day must be displayed here but it doesn't work
return false;
}
else{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url = "get_word.php"
url = url + "?word=" + word
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
here's my php code for generating the word of the day
<?php
$con=mysql_connect("localhost","root","");
mysql_set_charset("UTF8", $con);
if(!$con)
{
die("Could not connect." .mysql_error());
}
mysql_select_db("dictionary_ajax", $con);
$query = "SELECT eng_word" .
" FROM english".
" ORDER BY RAND(DAY(NOW())) LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows==0)
{
echo "No Results Found. Please try again";
}
while($row=mysql_fetch_array($result))
{
echo "<center><div class='wotd'>Word of the day:</div><div class='word'>".$row['eng_word']."</div></center>";
}
mysql_close($con);
?>
A better approach would be to call the php file via an AJAX request and then append the response to the relevant DOM element.
Overview of AJAX using vanilla Javascript:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Docs on JQuery Post and Get short cuts.
https://api.jquery.com/jquery.get/
http://api.jquery.com/jquery.post/
There are examples of what you are trying to do in the JQuery .get docs
Using jQuery, you could you use one of their ajax calls to load your html from include.php.
<div id="content"></div>
<script>
$(document).ready(function() {
$("#content").load("/yourpath/include.php");
});
</script>
or, without using jQuery, you may try this,
<div id ="content"></div>
<script>
function loadphpfile() {
var x = document.getElementById("content");
x.innerHTML = '<?php include_once "include.php";?>';
}
loadphpfile();
</script>
Try isolating the html+js files and API call yout .php file
app |-- www/index.html
|-- www/js/main.js
|-- www/api/word.php
Create html for view and include your javascript file and the jQuery library.
Get your data from the php file and return a json file
Call the *.php api file url using $.ajax Read more
Update DOM from the ajax data object
Hope that helps
You should make an AJAX call to get HTML from your server, then put the response to a DOM element with JavaScript.
So, in your case this may look like:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//Adds the response to the DOM element with ID wordOfTheDay
document.getElementById("wordOfTheDay").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "word.php", true);
xhttp.send();
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
With a popular framework like jQuery, this may look like this:
<center>
<img src="images/img_layout/exploro_logo.png">
<div id="wordOfTheDay"></div>
</center>
<script type="text/javascript">
/**
* Gets a word of the day
*/
function getWordOfTheDay() {
//Makes AJAX call
$.get("word.php", function (response) {
$('#wordOfTheDay').html(response);
});
}
//Invoke the function to get the word of the day
getWordOfTheDay();
</script>
More examples of using AJAX here - http://www.w3schools.com/ajax/ajax_examples.asp
More info about jQuery get method - https://api.jquery.com/jquery.get/
Also there are very good explanations of AJAX on stackoverflow here - How does AJAX work?
I am trying to pass some parameters vars and variables from one page x to another page y
My parameterized portion looks like:
x?path=1&edu=4&cert=
How can I pass these values easily to another page using php?
Note: often times cert var has no value.
For example:
I have a file x.php that is generating a url like: xx.xxx.xxx.xxx/p?path=1&edu=4&cert= . I need to then use this url in y.php - how can I do this?
Note: I am unable to use a framework for this application
Thanks
When receiving the parameters in page x, save them in variables and add them in the link to the page y. There are better ways but they depend on exactly what you want to do.
Simple example below.
x.php?path=1&edu=4&cert=
<?php
$path=$_GET['path'];
$edu=$_GET['edu'];
$cert=$_GET['cert'];
$params = "?path=".$path."&edu=".$edu."&cert=".$cert;
?>
Link to page Y with params obtained from page X
The result will be y.php?path=1&edu=4&cert=
It doesn't matter if you don't have a value in cert, it will pass as cert=
try use header location
$path=$_GET['path'];
$edu=$_GET['edu'];
if(!isset($_GET['cert'])) header("Location: y.php?edu={$edu}&path={$path}");
else $cert = $_GET['cert'];
I'm not to understand what you want but try this :
x.php
<?php
$url = 'http:localhost/test.php?path=1&edu=4&cert=';//generated url
parse_str(parse_url($url)['query']);//get parameter on url
include("y.php");
y.php
<?php
//!\ you must secure this value /!\
var_dump($path);
var_dump($edu);
var_dump($cert);
Are u submitting any form???If you are going from x.php to y.php through some event like button click then you can do an ajax call and easily can receive the parameters in the other page.
like <input name="" type="button" onclick="showHint($x);" value="click on me!" id="start" />//wher $x=1 your value
<div id="txtHint"></div>
You can write function as
<script>
function showHint(path) {
if (path.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "y.php?p=" + path, true);
xmlhttp.send();
}
}
</script>`
Now in y.php you can catch the param as
$path= $_REQUEST["p"];
Like this you can pass the params from one php page to another.
I don't know whether you want this kind of thing or something else.
Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!
You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>
HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();
(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>
To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript
I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}
On my website I give users an option to subscribe to blog authors. Right now it is a php process and requires page refresh each time user clicks "SUBSCRIBE" or "UNSUBSCRIBE" button. I was thinking that it is a time to make this process sort of AJAX based, so when users click "SUBSCRIBE" or "UNSUBSCRIBE" buttons there would be no page refresh, but their subscription arrays would be updated. therefore buttons will change respectively e.g. if user clicks "SUBSCRIBE" button it will change to "UNSUBSCRIBE" and backwards.
The problem is that I never used AJAX before and I can't find useful information to achieve this specific task, because there is a lot of it.
So could anyone suggest how to make this process sort of AJAX, so no page refresh takes place? If possible jQuery based solution would be great.
HTML & PHP for Buttons
//SUBSCRIBE Button
<?php if (($isLogedIN) && ($canSubscribe) && (!$isBlogOwner)) { ?>
<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="subscribe" value="Subscribe"/>
</form>
<?php } ?>
//UNSUBSCRIBE Button
<?php if (($isLogedIn) && ($canUnSubscribe) && (!$isBlogOwner)) { ?>
<form id ="unsubscribeform" name="unsubscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="unsubscribe" value="Unsubscribe" />
</form>
<?php } ?>
PHP to update database records
//Subscribe
if (isset $_POST['subscribe'])){
//First Update Visitors Subscription Array
if($subscription_array != ""){
$subscription_array = "$subscription_array,$blogauthid";
} else {
$subscription_array = "$blogauthid";}
$updateSubscription_array = mysql_query("UPDATE members SET subs='$subscription_array' WHERE id='$reader'") or die (mysql_error());
//Then Update blog writers subscribers array
$subArray7 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT1");
while($subrow7=mysql_fetch_array($subArray7)) {subscription_array7 = $subrow7["subscribers"];}
if ($subscription_array7 !="") {
$subscription_array7 = "$subscription_array7,$reader";
} else {
$updateSubscription_array7 = mysql_query("UPDATE members SET subscribers='$subscription_array' WHERE id='$blogauthid'") or die (mysql_error());
header("location: blog.php?id=$blogid");exit();
//Unsubscribe
if (isset($_POST['unsubscribe'])){
//First Update visitors subscription array
foreach ($subscription_array2 as $key => $value) {
if ($value == $blogauthid)
unset($subscription_array2[$key]);
}
}
$newSubArray = implode(",", $subscription_array2);
$updateSubscription_array = mysql_query("UPDATE members SET subs='$newSubArray' WHERE id='$reader'") or die (mysql_error());
//Than update blog writers subscription array
$subArray9 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT 1");
while($subrow9=mysql_fetch_array($subArray9)) {subscriber_array9 = $subrow9["subscribers"];}
$subscriber_array9b = explode(",", $subscriber_array9);
foreach ($subscribe_array9b as $key9 => $value9) {
if ($value9 == $reader) {
unset($subscriber_array9b[$key9]);
}
}
$newSubArray9 = implode(",", $subscriber_array9b);
$updateblogSubsArray = mysql_query("UPDATE members SET subscribers='$newSubArray9' WHERE id='$blogauthid'") or die (mysql_error());
header ("location: blog.php?id=$blogid");exit();
Basically you want to have a JavaScript function like this:
function subscribe(id)
{
if (window.XMLHttpRequest)
{// code for real browsers
xmlhttp=new XMLHttpRequest();
}
else
{// code for abominations
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.status==200 && xmlhttp.readyState==4)
{
document.getElementById("subscribeStatus").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","blog.php?id="+id,true);
xmlhttp.send();
}
Call it and pass it the variable (id) you want with a button like this on the frontend.
<input type="button" name="click" value="Subscribe" onmousedown="subscribe(document.getElementById('id').value);">
Embed the user's ID as a hidden form field with id = "id" (or whatever).
Then on the PHP side (blog.php) just handle it with $_GET instead of $_POST. And duplicate it for unsubscribe or find a way to work it together using a switch (or if) statement.
Hope that helps.
This could be optimized a little, but it's functionality is more clear at each step and it should work. This is Jquery $.post, as requested.
You only need one form element:
<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="subscribe" value="Subscribe"/>
</form>
At the bottom of your document, just before the closing body tag, link the jquery library, followed by the script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#subscribeform input:submit').click(function() {
// $.post is the jquery shorthand method for $.ajax - it always uses POST
$.post(
// url
'blog.php?id=<?=$id?>',
// serialized form data to POST
$('#subscribeform').serialize(),
// success callback toggles form value
function(data) {
if ($('#subscribeform input:submit').val() == 'Subscribe') {
$('#subscribeform input:submit').
attr('name','Unsubscribe').val('Unsubscribe');
}
else {
$('#subscribeform input:submit').
attr('name','Subscribe').val('Subscribe');
}
}
);
});
});
So i have a simple question, but i cant find the answer to it.
I have a form in which a user types something into the textfield and clicks the submit button with the value "Add". There will be list to the right and every time the user clicks add, there will be element added to the list on the right with a fade in animation.
I'm using php to make it so that every time the user clicks add, it queries the databse and finds what the user is looking for. And if it isnt in the database, then insert it into the database.
I'm using javascript/jquery to have the fade in animation when the user clicks "Add".
I know how to do these things individually, but when i click the Add button (the submit button), the entire page refreshes, php works fine, but there was no animation.
I try using preventDefault() on jquery, and the animation works fine, but the php code didnt register? How would i make it so that the php and javascript dont cut each other off? Does this have anything to do with ajax? Thanks
You need to use the jquery Ajax functions. These are especially made so that you can call php scripts without page refresh.
Click Here for the official documentation on Ajax post functions, and how to use them.
Here is an example that I came up with. Hopefully that can be helpful to you.
Content of index.php
This is where your form is and where added items will be displayed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Page Title</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
jQuery(function($) {
// Declare DOM elements for quick access
var itemsList = $('#items-list'),
searchInput = $('#search-input');
// click event handler for the 'Add' button
$('#add-btn').click(function(e) {
// Prevent the form from being sent
e.preventDefault();
var searchValue = searchInput.val();
// Send the AJAX request with the search parameter
$.post('search.php', {
search: searchValue
},
function(data, textStatus) {
// data is returned as a json object
if (data.found) {
// Create a new hidden element into the list
// and make it fade in
$('<p class="item">'+searchValue+'</p>').hide()
.appendTo(itemsList)
.fadeIn();
}
}, 'json'
});
});
});
//-->
</script>
</head>
<body>
<form action="index.php" method="post" id="search-form">
<div>
<input type="text" name="search" id="search-input">
<input type="submit" id="add-btn" value="Add">
<div id="items-list"></div>
</div>
</form>
</body>
</html>
Content of search.php
<?php
// AJAX Request?
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Prepare the reponse
$response = array('found' => FALSE);
// Check that the search parameter was provided
$search = filter_input(INPUT_POST, 'search', FILTER_SANITIZE_STRING);
if (!empty($search)) {
// Note: We'll assume a connection to a MySQL database
// with the following constant already declared
$mysqli = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Make sure that the connection was successful
if (!$mysqli->connect_error) {
$query = "SELECT id, keyword FROM search_table WHERE keyword = ?";
// Check if the search keyword already exists
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $search);
$stmt->execute();
// Create a new entry if not found
if (0 == $stmt->num_rows()) {
$query = "INSERT INTO search_table(keyword) VALUES(?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $search);
$response['found'] = $stmt->execute();
}
else {
$response['found'] = TRUE;
}
}
}
echo json_encode($response);
}
This is not tested so let me know if you encounter any issues.
Cheers,