Couple questions:
1) I'm trying to have a new random value updated each time a button is pressed. When the button is clicked, a value is generated once... but is not random. So I'm not sure if the function is being called again on click because a new value isn't generated.
2) Can I include the php code within the same file as the jquery when using a server call such as $.get() and call it as a function within that same file?
The reason is, I don't want to have to keep creating new php script files, and would rather throw the code in the same file as the calling jquery.
Meaning...
Instead of $.get("../scripts/NameGenerator2.php",
I do this: $.get("a php function within this same file",
JQuery:
<?php
if ($imgid == 1) {
?>
<button onclick="generate()">Generate</button>
<button id="generateButton">Generate</button>
<script type="text/javascript">
$(document).ready(function() {
$("#generateButton").click(function(e) {
//alert("called");
$.get("../scripts/NameGenerator2.php",
function(returned_data) {
$("#generated").html(returned_data);
}
).error(function(jqXHR, status, error) {
console.log("error in $.get")
});
});
});
</script>
<?php } ?>
<br /><span id="generated"></span><br />
PHP:
<?php
$adj = array("Happy", "Great", "Mandarin", "New", "Golden", "Ming's");
$noun = array("Dragon", "Sea", "Wok", "Fortune", "Rice", "Empire");
$place = array("Garden", "China", "Village", "Palace", "Kitchen", "Mountain");
$x = rand(0, count($adj)-1);
$y = rand(0, count($noun)-1);
$z = rand(0, count($place)-1);
echo '<p>' . $adj[$x] . " " . $noun[$y] . " " . $place[$z] . '</p>';
?>
Any thoughts? Thanks!
Updated: Only error I seem to be getting is "Object Expected" in my "myJquery.js" file, which is not the file I'm working in, and doesn't seem connected.
When I add in document ready to my function, the button onclick() call seems to break.
You can call a .php-file with jQuery. But the file should be reachable with your browser and should return qualified data.
With .get() you can define the expected data-type. It can be xml, json, script, or html.
If you want to use json (my favourite) the use the php-function json_encode to generate the output.
If you want to use the same file, create a GET-Parameter e.g. ?ajax=1. With your AJAX-request you call the file and append the GET-Parameter. And in your .php-File you can then switch between an normal call and an ajax call which returns an other output.
<?php
if (!empty($_GET) && !empty($_GET['ajax']) && $_GET['ajax'] == 1) {
// header("Content-type: application/json");
// $data = array(some_data);
// echo json_encode($data);
echo 'AJAX-call-output';
} else {
?>
<!-- [...] -->
<script type="text/javascript">
function generate() {
$.get("../scripts/NameGenerator2.php",
{ ajax: 1 }, // GET-Parameter
function(returned_data) {
//alert("test");
$("#generated").html(returned_data);
}
//, "json"
);
}
</script>
<!-- [...] -->
<?php
}
?>
You cannot get a PHP function but you can load the page and get a specific div -
$('#generated').load('../scripts/NameGenerator2.php #pagePart');
You echo out PHP with the proper id's in place, for instance -
echo '<p id="pagePart">' . $adj[$x] . " " . $noun[$x] . " " . $place[$x] . '</p>';
Without using any inline JavaScript this is what your jQuery code might look like -
<button id="generate">Generate</button>
$(document).ready(function() {
$('#generate').click(function(e){
e.preventDefault();
$('#generated').load('../scripts/NameGenerator2.php #pagePart');
});
});
Based on your update you need to move all of your jQuery functions into the document ready function.
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?
Hello I want to execute bb() function on button click.
I tried following code but it did not work.
echo "<div class ='i2' id=".$x.">";
echo "<button type='button' style='display: none;' id='i' name='delete' onclick='document.body.removeChild(this.parentNode)'>";
echo"</button>";
echo "</div>";
<?php
function bb()
{
echo "hello";
}
if (isset($_GET['delete'])) {
bb();
}
?>
Your button is HTML and your function is PHP. They look like together because they are in the same file, but they are not together. PHP exists only on the server. HTML only works on the client (browser). When you see the button on your browser, the PHP is gone, you only have HTML.
To make a HTML button to call a PHP function, you will have to move your function to a PHP file, then make your button to call it with Ajax. Example:
bb1.html : contains button that uses Ajax to call PHP function.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'bb2.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">Click here</button> <!-- BUTTON CALL PHP FUNCTION -->
</body>
</html>
bb2.php : contains function that returns "hello".
<?php
function bb()
{
echo "hello"; // VALUE RETURNED.
}
bb();
?>
Create two text files with the given names, copy-paste this codes, open your browser and run "localhost/bb1.html".
This is how a button calls a PHP function : Ajax does all the magic.
How is possible to check if div is clicked and then return information?
function kat(){
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
echo "</div>";
}
echo "<div class='mygtukas-js' onclick='kat();'>";
echo "</div>";
But actually it's wrong because my mygtukas-js has a drop down menu.
I need to generate a code which let me to press a button and then menu would be generated. Maybe someone knows?
EDIT: This div <div class='mygtukas-js'></div> (has to start and end before) <div class='turinys'> STARTS.
Some fresh ideas? :?
EDIT2:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>
<script>
$(document).ready(function(){
$('#mygtukas-js').click(function() {
$("#turinys").load('b.php');
});
});
</script>
and b.php
<?php
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
?>
But no information generated :(
Create your PHP file which I guess would also include HTML.
Create a "click" JQuery function and make sure to send the POST to the specific PHP file / Controller which should handle the request. In case you want to just get the above file directly then point to it.
It should be like:
$(document).ready(function(){
$('#send').click(function() {
$("#menu").load('URL_TO_YOUR_PHP');
});
});
Thanks to AJAX the "#menu" should be displayed and will contain whatever the PHP file sends back.
HTH.
U can use jQuery to check if a div is clicked. Like this:
$('.turinys').click(function(e) {
$(this).html("Add any html to the div");
});
Use to different php file. Lets call A.php and B.php. A.php contain the menu code.
A.php
<?php
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'>
<a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a>
</div>";
}
echo "</div>";
?>
B.php
<script>
function kat(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "A.php", false);
xhr.send(null);
// You can also check response status if you need.
var serverResponse = xhr.responseText;
document.getElementById('menu').innerHTML = serverResponse;
}
</script>
<?php
echo "<div class='mygtukas-js' onclick='kat();' id='menu'>";
echo "</div>";
?>
This is my code below for page.php file.
<?php session_start(); ?>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<script type="text/javascript" src="js/new-landing.js"></script>
<script type="text/javascript">
var ans1 = "home";
function aa(){
$.post("ajax.php", { "ans": "test" }, function(data){
alert("Posted");
}, "html");
};
</script>
<a href="#" id="q1" onClick="javascript:aa();" >click</a>
and this is where i want to see if my data is posted.
<?php
session_start();
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
when i click the anchor tag. the alert box is shown. but when i refresh the ajax.php page. it shows an error..Notice: Undefined index: ans in ajax.php on line 3
and the print of session is also empty.
Array(
[demo] =>
)
but when i refresh the ajax.php page. it shows an error
It sounds like you want to set the session variable when a value is posted, and get the session variable otherwise:
<?php
session_start();
if (isset($_POST['ans'])) {
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
}
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
$.post and $.get are just shorthand versions of the more structured $.ajax(), so I prefer using the latter. The additional structure keeps me straight.
Since you are using jQuery anyway, I would re-structure your code like this:
$('#q1').click(function() {
var test = "Hello there";
$.ajax(function() {
type: "POST",
url: 'ajax.php',
data: 'ans=' +test+ '&anothervarname=' + anothervarvalue,
success: function(recd_data) {
alert('Rec'd from PHP: ' + recd_data );
}
});
});
Note that the data: line is for example purposes and does not match with your code -- just showing you how to pass variables over to the PHP side.
Of course, the above includes removing the inline javascript -- never a good idea -- from your anchor tag HTML, thus:
<a href="#" id="q1" >click</a>
Also, on the PHP side, you can verify that things are working by adding a test at the top. Matching with the data: line in the example AJAX code, it would look like this:
ajax.php
<?php
$a = $_POST['ans'];
$b = $_POST['anothervarname'];
$response = '<h1>Received at PHP side:</h1>';
$response .= 'Variable [ans] has value: ' . $a . '<br>';
$response .= 'Variable [anothervarname] has value: ' . $b . '<br>';
echo $response;
Important: Note the use of echo, not return, to send values back to the AJAX script.
Also note that you must deal with the stuff returned from PHP in the AJAX success: function ONLY. If you need access to that data outside of the success: function, then you can stick the data into a hidden <input type="hidden" id="myHiddenInput"> element, like this:
success: function(recd_data) {
$('#myHiddenInput').html(recd_data);
}
Here are some additional examples of simple AJAX constructions:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
i give another codes for example
this is my some3.php code:(First file)
:
<head>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var who = $('input#who').val();
var why = $('input#why').val();
$('#geting').load('file2.php',{who:who,why:why},function(applyData){
if ( applyData == 'YEY . Ye have hi' ){
alert('OKKK data is ok ');
} else{
alert('Nooo We dont have requested output');
}
});
});
});
</script>
</head>
<body>
<p> click </p>
<input type="text" id="who">
<br>
<input type="text" id="why">
<div id="geting" align="center">
</div>
</body>
i this my file2.php:
<?php
echo "1";
echo "2";
if($_REQUEST['who'] == "hi"){
$myVariable = "YEY . Ye have hi";
echo $myVariable;
} else{
$myVariable = "The out put is not Hi";
echo $myVariable;
}
?>
its not work why? becuse we have echo "1" and echo "2"
i want jquery just check $myVariable data not whole php callback ! i think i must use json but i dont know how
Well, assuming that you want to read the value with JQuery off the page you are posting to, you could do this, since you are echo'ing the value out in that page by doing the following: echo $myVariable;
Now this is how I generally read a value off another page with JQuery which is by using JQuery's get() method.
$.get("thepagetoretrievefrom.php", function(retrievedvalue) {
alert("Here's the data you requested: " + retrievedvalue);
if (retrievedvalue == 1) {
//print out something here
alert("The retrieved value was 1.");
}
});
And that should retrieve the value from the PHP page. "thepagetoretrievefrom.php" is the page where you want to retrieve the information from. function(retrievedvalue) just indicates that whatever output you're requesting from the page via JQuery will be put into retrievedvalue. Then, using JQuery, you may decide whether you want to do a new call to another page depending on what the "retrievedvalue" was.
This, however is not the best method to achieve this, since this will print whatever may be in that page, but if you are requesting one specific value from that page, then it shouldn't be an issue.