I'm trying to create a form that is capable of generating multiple urls, depending on the input by the user. The created url has a json extension. A php file is used to get the contents of that url. This php file has to have the same contents as the inputted url has. This php file is used as input for a javascript/jquery file.
In this file I'm trying to convert the json code to an html table. This is done by an http_request. The table has to be outputted in a div on the html page. However my code doesn't work due to errors I can't find. I've already looked at simular questions at stackoverflow and google, but could find the fix that made my code working.
I'm applying this code to spotify lists. This is the code I already have:
html:
<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
<select id="country" name="country">
<option value="GB">UK</option>
<option value="US">USA</option>
</select>
<select id="interval" name="interval">
<option value="daily">Daglijst</option>
<option value="weekly">Weeklijst</option>
</select>
<select id="chart" name="chart">
<option value="most_streamed">Meest gestreamd</option>
<option value="most_viral">Meest gedeeld</option>
</select>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>
spotify.js:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.open("GET", "spotifylist.php", true);
http_request.send();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.artist_name and jsonObj.track_name.
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=jsonObj.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
}
}
}
$("#spotifyform").submit(function(){
loadJSON();
return false;
});
spotifylist.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$chart = $_POST['chart'];
$country = $_POST['country'];
$interval = $_POST['interval'];
}
$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>
What currently goes wrong is that the php file is loaded when I press the submit button. This file contains the right json information. However this json isn't converted to a html table.
I would really appreciate it, if anybody could help me fix this problem
If you want the spotifylist div to load in the data when you press submit, you have to prevent the page from redirecting.
Make the form action:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>
And if possible, your input values (if you have any within the form tags):
"<?php echo $_POST['value']?>"
If you can, place your HTML code within a PHP file which executes everything from spotifylist.php.
There are a couple of problems in my guess.
You send your Form to the spotifylist.php which grabs an file and sends something back to the html. Probably JSON but where did you handle that data?
Maybe some Javascript which does something with that "string" that your php sends back?
And your loadJSON sends (whenever) a GET Request to the same php but without parameters or something.
So your php run into an error because there obviously no POST variables set, so your variables inside your if condition will never set ergo your data which comes back again?!? with errors
You should first get clear which technique you want to use.
It seems to me as you would take a little of both.
There are multiple ways to get information from an external server:
httprequest - not recommend, because of bad user experience.
file_get_contents - usually easy, but in this case it requires a lot of data handling. Php works server-side and javascript works client-side. It requires a lot more work to let these two work together.
$.ajax - in this case the best solution, because it doesn't require any php and $.ajax is able to directly parse the json data. Because the data is requested from an external site, you have to change the datatype to jsonp and perform a callback function.
It is very easy to transfer the data from the form to javascript:
// Automatically call this function when the page loads.
window.onload = function loadJSON()
{
// The HTML input of the form that is the input of this javascript document
var country2 = document.getElementById("country");
var chart2 = document.getElementById("chart");
var interval2 = document.getElementById("interval");
Build the url with the selected parameters on submit:
// Call the function when the form is submitted
$("#spotifyform").submit(function(e)
{
e.preventDefault(); // to prevent the page from reloading
// Save the choice of the <select> country in a variable named country2
var country = country2.options[country2.selectedIndex].value;
var chart = chart2.options[chart2.selectedIndex].value;
var interval = interval2.options[interval2.selectedIndex].value;
var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
Then get the right data and parse it directly with the json native parser.
// Get the data from the site and save this into the variable 'json'
$.ajax
({
'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
'dataType': 'jsonp', // Cross site request via jsonp
'error': function(xhr, status, error){ alert(error.message); },
'success': jsonParser // call function
}); // $.ajax
}); // $("#spotifyform").submit(function(e)
} // window.onload = function loadJSON()
Then do with the data whatever you want. You don't need to do an httprequest and you don't have to parse the data anymore.
function jsonParser(json)
{
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=json.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
} // function jsonParser(json)
Related
My code works fine when I run the php script without ajax as a GET request. I get prompted to download the rendered pdf and all is well. However, I need to use ajax because I need to send more info from an html page to the php script than can be handled in a GET request.
What do I need to put into my ajax to make this work?
Thanks
js
function makePDF()
{
var x;
if(window.event) // IE8 and earlier
{
x=event.keyCode;
}
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
keychar=String.fromCharCode(x);
alert(keychar);
if (keychar == 'p' || keychar == 'P')
{
var charSheetHTML = characterSheet.innerHTML;
$.ajax({
url: 'pdf.php',
data: {'charactersheet': charSheetHTML,},
type: 'post',
success: function (data) {**WHAT_DO_I_PUT_HERE??**},
error: function (data) { alert("error\n" + data.toString()); }
});
}
}
pdf.php
<?php
include_once( "bxcharacter/PDFChar.php.inc" );
PDFChar();
?>
PDFChar.hph.inc
<?php
require_once('./tcpdf/tcpdf.php');
function PDFChar(){
$pdf = new TCPDF();
$pdf->AddPage('P');
$pdf->writeHTML($_POST['charactersheet']);
$pdf->Output("character.pdf", 'D');
}
?>
This is not an ajax solution, but you can send your data with this way and if no error occurs, your page will not change.
Create a form element with inputs hidden which contains your data you want to send:
example format:
<form id="myForm" method="GET" action="pdf.php">
<input type="hidden" name="data1" type="hidden" value="your JSON.stringify() data">
</form>
js code (call these where your ajax request is):
var myForm = '<form id="myForm" method="GET" action="pdf.php">';
myForm += '<input type="hidden" name="data1" type="hidden" value="JSON.stringify() data">';
myForm += '</form>';
$("body").append(myForm); // temporarily appending
$("#myData-form").submit(); // submitting form with data
$("#myData-form").remove(); // remove form after submit
And as you said, force download will force file to download and page will remain same. However, if an error occurs, your page will change of course.
I don't know whether this is an effective way or not but in my case, this does the trick.
Old question, but I was trying to do something similar with Laravel PDF extension, and stumbled across this question. I did successfully do this asynchronously with the help of a nice blog post
https://nehalist.io/downloading-files-from-post-requests/
https://github.com/nehalist/download-post-requests
The using the form method, like the previous answer works fine too, but maybe this will help anyone else trying to achieve this with AJAX. The author's XMLHttpRequest method worked great for me!
The code that worked for me (almost verbatim from the blog post) ->
document.getElementById('exportpdf').addEventListener('click', function () {
var request = new XMLHttpRequest();
request.open('POST', '/your/post/endpoint/here', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
if(request.status === 200) {
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
I tried to get it to work with jQuery AJAX but failed, so I went with XMLHttpRequest. With jQuery, The download would work, but the content was always empty. I tried to do something like in this post -
https://keyangxiang.com/2017/09/01/HTML5-XHR-download-binary-content-as-Blob/
$.ajax does not support either arraybuffer or blob as its dataType. Thus we need write a beforeSend handler:
//setup ajax
$.ajaxSetup({
beforeSend:function(jqXHR,settings){
if (settings.dataType === 'binary'){
settings.xhr().responseType='arraybuffer';
settings.processData=false;
}
}
})
//use ajax now
$.ajax({
url:url,
dataType:"binary",
success:function(data){
console.log(data); //ArrayBuffer
console.log(new Blob([data])) // Blob
}
})
But never got it to work. Maybe someone smarter can figure out the jQuery method :)
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
I was wondering, what'd be the best way to store a shopping cart?
I thought about storing products ID's in localstorage/sessionstorage and then use AJAX to retrieve the products from the server.
The only problem is that I don't know how to pass the items from the localstorage to PHP...
I'm guessing it's probably not possible directly, and I thought about a form though I have no idea how to implent it...
The idea is that when a user clicks "Add to cart" the item id and quantity is added to the localstorage, and when a user views his cart, the item details (image, name, price...) are being retreived from the database.
I'm probably going to use this tutorial
http://verido.dk/index.php/ressourcer/artikler/loading-and-saving-data-dynamically-using-php-jquery-and-mysql/
I could as well give up on local storage and go with sessions and database but I'd really like to give users that dynamic web experience.
Another possible way I just came up with is to use URLs like file.php?prodid=......, although URLs like this may get way too long.
Thanks in advance!
'You must remember that Server-Side (PHP) code is read before it converts the code to browser-side code. JavaScript is manipulated browser-side...
So one-dimensionally, you cannot pass JavaScript to PHP.
However...
With Ajax and in your case I suggest JSON you can send JavaScript data to a PHP page and bring the response back to your JavaScript methods. I think this will suit your needs. I can provide a simple example if you want.
//--example below:
JavaScript:
//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {
responseDiv.innerHTML = '';
var myAjax;
try {
// Modern Browsers-->
myAjax =new XMLHttpRequest();
} catch (e) {
// antique ie browsers-->
try {
myAjax =new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
myAjax =new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
document.getElementById('processDiv').innerHTML="";
alert("Your browser malfunctioned! Please try again. Consider installing a modern browser if the problem persists.");
return false;
}
}
}
myAjax.onreadystatechange = function() {
if (myAjax.readyState == 4) {
var ajaxResponse = myAjax.responseText;
responseDiv.innerHTML = ajaxResponse;
processDiv.innerHTML = "";
//NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
//POST PROCESSING----->
// IE: alert('I am finished processing now!');
// or call another function:
// anotherFunction();
} else {
processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
}
}
myAjax.open("GET", queryString, true);
myAjax.send(null);
}
function sendStorage() {
var helloVar = 'Hello, I am passed to PHP #1';
var worldVar = 'I am the second value passed to PHP!';
var processId = 'process_div';
var resultId = 'result_div';
var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;
processAjax(queryString, processId, resultId);
}
Now for some HTML:
<div id="content">
<div id="process_div"> This is where processing will occur </div>
<div id="result_div"> This is where my response will display </div>
</div>
Now for a process.php (NOTE: FOR SECURITY, I STRONGLY SUGGEST YOU DON'T REVEAL A SERVER-SIDE PROCESSING PAGE IN YOUR JAVASCRIPT)
<?php
//init
$hello = '';
$world = '';
$errors = 0;
//set
//Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
(isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
(isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;
//process
if($errors > 0) {
echo 'Errors Detected! Missing querystring get data!';
} else {
echo '<p>Hello received: ' . $hello . '</p>';
echo '<p>World received: ' . $world . '</p>';
//now we can process $hello and $world server side!
}
?>
Important: you should really look into learning some JSON and $_POST requests as they are more secure, faster and you can easily manipulate returned data. I suggest looking at a library like jquery for simplified examples.
I have not tested this code, but it should work.. Let me know if you have questions or this does not answer your question.
Glad to help!
Use AJAX to send data to the server (GET or POST) and store these values in a session variable or cookie on the server
You can use your local/session storage data and populate some hidden inputs, then submit the respective form in an ajax request. To make things cleaner you can use one hidden input and set it's value into a JSON object created from your storage data.
No, javascript runs on the client, php runs on the server.
I have
index.php
<select id="year_list" name="year_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
<select id="event_list" name="event_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
.
.
.
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
?>
myscripts.js
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
// call PHP function (but I don't know how): checkYearandEvent(year, event);
}
My question is how do I call the PHP function every time the user changes the value of any of the select element.
You need to use ajax. There is a basic example:
myscripts.js
function AjaxCaller(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function callPage(url, div){
ajax=AjaxCaller();
ajax.open("GET", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
div.innerHTML = ajax.responseText;
}
}
}
ajax.send(null);
}
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
callPage('file.php?year='+year+'&'+'event=+'+event,document.getElementById(targetId));
}
file.php
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
echo checkYearandEvent($_GET['year'], $_GET['event']);
?>
You won't be able to do this in the way you might be expeting to. PHP is executed on the server, before the browser receives the HTML. On the other hand, JavaScript runs in the browser and has no knowledge of the PHP (or any other server side language) used to create the HTML.
To "call" a php function, you have to issue a request back to the server (often referred to as AJAX). For example, you could have a checkYear.php script which checks the event and returns some HTML indicating whether the check succeeded. When the HTML fragment gets back to the JavaScript, you inject it into the page.
Hope this helps!
JavaScript is a client side language, PHP is a server side language. Therefore you can't call PHP functions directly from JavaScript code. However, what you can do is post an AJAX request (it calls a PHP file behind the scenes) and use that to run your PHP code and return any data you require back to the JavaScript.
Basically, you are mixing server-side (PHP) and client-side (JS) scripting.
It is however possible - thanks eg. to AJAX. Because you was not specific about what do you exactly need to be done after the select box changes, I can only point you to some resources and propose following:
learn and start using jQuery (jquery.com) - it will help you get started and maintain cross-browser compatibility,
learn how to make AJAX requests (eg. in the function you just were firing when onchange event was fired) - eg. using .post() jQuery function,
learn how to return data from PHP (eg. using json_encode() in PHP, but raw HTML is also ok) and use it in JS,
There may be many ways to do this. The one I prefer, is using MooTools Request object.
For example, you have a script called ajaxCallable.php, which receives thru $_REQUEST variables some parameters, then you do (in the Javascript side):
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
var myRequest = new Request({method: 'get', url: 'ajaxCallable.php'});
myRequest.send('yearVar=' + year + '&eventVar=' + event);
}
then, your ajaxCallable.php will be able to access the variables: $_REQUEST['yearVar'] and $_REQUEST['eventVar'].
I was working on a project this week and came up with an easy way to call a php script from an onclick(). It goes like this.
I define an onclick() call in this case on a div called "sidebarItem"…
<a><div class="sidebarItem" onclick="populate('#content', 'help', 'open')">Click me for new content</div></a>
Then I made a simple little JS function that loads an external file into the target container…
function populate($container, $page, $item){
$($container).load('cyclorama/includes/populate.php?$page='+$page+'&$item='+$item);}
Then I write a small php file that gets the $page and $item, queries the database and returns the new content.
<?php
$page = $_GET['$page'];
$item = $_GET['$item'];
$getContentQuery = "SELECT content FROM myTable WHERE page='".$page."' AND item='".$item."'";
$content = mysql_query($getContentQuery, $db);
$myContent = mysql_fetch_assoc($content);
echo $myContent['content'];?>
The php script echoes the new content and it's loaded into the container. I think there are a lot of places this could serve. I'd be interested in finding out if there are any obvious reasons NOT to do this. It doesn't use AJAX just javascript and php but it's fast and relatively easy.
Here is my code. You have to kindly look does it suffer from 'same origin policy' in this shape. The domain for HTML is (http://127.0.0.1/jqload.html) & php file (http://127.0.0.1/conn_sql.php). This is json format : [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]
I actually want to append json data that I receive in HTYML with user input & I am suffering in that. If I use eval for parsing, it works fine to point its put here. But if I use JSON.parse to parse, the whole code stops working & this error message is issued '"IMPORTANT: Remove this line from json2.js before deployment". I put my code for some other question on stackoverflow forum & I was told that my code suffer from 'same origin policy' that causes the problems in appending JSON data. So can you kindly see does my code suffer from this policy? Though I have doubts it suffers from that policy as I learn that it restricts if files reside on different domains, here both files reside next to each other.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>
You're on the right track, but here: $.each(jsonData, function (i, j) { ... } you are actually looping through each character of the jsonData string, and not the json object. Just change jsonData to json inside the $.each(), and it should work fine (regardless of whether you're using eval or JSON.parse, but I recommend the latter).
Edited: Since you are using jQuery.getJSON(), you don't need to use eval or JSON.parse - jQuery does it for you. So inside your callback function, just set json = jsonData .
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>