Send javascript function parameters onChange - javascript

Okay, I've been struggling with this for a few hours now. I'm using ajax to update a div in my site with a php code however, i'm trying to send parameters in the function from the external javascript file to update the correct link(there are multiple drop down boxes)
for example: this is my select box
<script type='text/javascript' src='ajax.js'></script>//include ajax file
<select onchange='MakeRequest(raceupdate);
this.options[this.selectedIndex].value;'> //so no use of a button is needed to auto link to anchor tag
<option>Deathmateched</option>
<?php
dmList()
?>
</select>
Then next my external ajax function MakeRequest().
function MakeRequest(value)
{
var linkInfo = "teleport.php?call=" + value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
So as you can see I'm trying to pass a sting of text into this function, but I seem to be failing somewhere.

You probably want to setup your tag to pass "this". I don't see where your raceupdate variable is declared, unless it's global... in which case you should show us what you're doing with that variable.
<select onchange='MakeRequest(this);'>
<option>Deathmateched</option>
<?php
dmList();
?>
If you did it that way, you'd have to change this function as such:
function MakeRequest(element)
{
var linkInfo = "teleport.php?call=" + element.value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
And what are you trying to do here?
this.options[this.selectedIndex].value;
In your comments, it looks like you're saying you want to jump to an anchor tag? If so, then you would want to do something like
var anchorTag = document.getElementID("YOUR_ANCHOR_TAG_ID");
anchorTag.focus();

Related

How actual parameter can be passed here?

JS function can't be called with passed parameters
I've passed actual parameters from php file to divs with onclick event, it is rendered right on the page, function itself is present, but parameters aren't passed to function call
Formal argument stays like in function definition, it isn't substituted by what was passed to onclick events
http://localhost:8000/sknt1.php?reqStr
Code itself looks like this:
for ($i=0; $i<count($json_a["tarifs"]) ; $i++) {
echo "<div onclick='fun(".$i.")' class='column' style='font-size:20px; width:100%'>
On the page it looks like this (0 through 4):
<div onclick="fun(0)" class="column" style="font-size:20px; width:100%">
<div onclick="fun(1)" class="column" style="font-size:20px; width:100%">
And so on.
fun() is an AJAX call function, it is written to page one time, I cannot embed it in php for loop:
<script type='text/javascript'>
function fun(reqStr) {
var xmlhttp = null;
function AjaxRequest(url){
if(xmlhttp != null){
if(xmlhttp.abort)
xmlhttp.abort();
xmlhttp = null;
};
if(window.XMLHttpRequest) // good browsers
xmlhttp=new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
if(xmlhttp == null)
return null;
xmlhttp.open('GET',url,false);
xmlhttp.send(null);
if(xmlhttp.status >= 200 && xmlhttp.status < 300)// 2xx is good enough
return xmlhttp.responseText;
else
return null;
}
window.history.replaceState({}, '',`/sknt1.php?reqStr`);
var url = '/sknt1.php?reqStr';
var contents = AjaxRequest(url);
if(contents){
document.documentElement.innerHTML = contents;}
}
</script>
I want this Ajax call to substitute variable passed in and replace url for smth. like http://localhost:8000/sknt1.php?0, there's additional php file, it will render new page after manipulating the history, please help
Just make a variable inside the for loop as $iStr = ' " '.$i.' " ' and pass the new variable.
It was a noob question. Obviously I should have concatenated arguments[0], not pass it directly.
Not this /sknt1.php?reqStr, but this /sknt1.php?+reqStr

what causes the URL to change upon form submissions

I often seen websites with a search function and when they search for something, the web page often changes the url to something along the lines of
search.php?q="searchquery"& etc , i have a search page on my site and i use ajax to submit a form that has a search input and sends to a php page which searches through my database and returns data to a specific div on the original page via echo.
function getdata() {
var str = document.getElementById("searcb");
document.getElementById("demo").innerHTML = "You are searching for: " + str.value;
document.getElementById("searchresults").style.display="block";
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("searchresults").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str.value, true);
xmlhttp.send();
return false;
}
}
HTML
<form onsubmit="return getdata()">
<input type="search" id="searcb" name="searchBar"></br></br>
</form>
My question is what am i doing differently that causes my url to remain the same compared to a common search engine
In general the url change because a post that reload the page is performed. Your url will not change because you call make an ajax call that will not reload your corrent page .

Find event on cell click Javascript

I have a Calender Control, which is populated with events on Page_Load. When a user clicks on a cell I want to find the events in that cell and then populate a Text Area with the information.
I can get the Click Event to happen when they click on a cell but I don't know how to get the event and display in a Text Area in Javascript.
<DayPilot:DayPilotMonth CssClassPrefix="bsimplexcalender"
OnCommand="calender_control_Command"
ContextMenuID="menu"
EventRightClickHandling="ContextMenu"
EventRightClickJavaScript="select(e)"
BubbleID="DayPilotBubble1"
ClientObjectName="dpm"
runat="server"
ID="calender_control"
Theme="bsimplexcalender"
HeightSpec="Auto" Height="0"
MinCellHeight="63"
DataStartField="start"
DataEndField="end"
DataTextField="name"
DataValueField="id"
OnBeforeEventRender="calender_control_BeforeEventRender"
TimeRangeSelectedHandling="JavaScript"
TimeRangeSelectedJavaScript="''THIS IS THE CLICK EVENT I NEED TO FIND EVENT AND DISPLAY HERE" />
This code might help :
For JavaScript :
function loadCalendarEvent(day) { //call this function when table cell is clicked
//in var day pass the day clicked
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//just received the answer from server so do something with it here
}
}
var url; //link to php file
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "text/json"); //change Content-Type to what you need
xmlhttp.send(day);
}
For PHP :
<?php
$ClientData = file_get_contents('php://input'); //day variable is stored here
//query database for event and save it to some variable
echo $thatVariable;
?>
If you want me to explain more, leave a comment...

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Call Perl function in HTML using AJAX

im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:
function getOption(){
var selectmenu=document.getElementById("Select1")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
var s = chosenoption.text;
openFile("C:\PerlTest\test.txt");
}
}
}
EX. not working trying to pass parameter:
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Im attempting to pass the paremeter in that way because of this example:
http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201
Can anyone help??
Thanks a lot.
After the sugestion of Kinopiko, that makes sense, i have the following:
HTML-
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
var container = XMLHttp.responseText.split("\n");
if (container.length>0){
for ( i=0; i< container.length-1;i++){
document.getElementById("TxtArea").innerHTML += container[i] + " ";
}
}
}
else{
document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Perl script:
#!c:/Perl/bin/perl
use strict;
use CGI qw/param/;
use URI::Escape;
print "Content-type: text/html\n\n";
my $file = param ('file');
$file = uri_unescape ($file);
open (MYFILE, $file);
while (<MYFILE>) {
chomp;
print "$_\n";
}
close (MYFILE);
Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.
Maybe im using the encodeURI wrong??
Thanks.
First of all you need to add a question mark:
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true);
Also you need to percent-encode "name" using encodeURI.
On the Perl end, you can use a module like CGI to get the value of the file:
use CGI qw/param/;
my $file = param ('file');
Then
use URI::Escape;
$file = uri_unescape ($file);
open (MYFILE, $file);
should be
open (MYFILE, $file) or die "Cannot open file $file: $!\n";

Categories

Resources