js
function SearchInList(_id,_url,_place){
this.id = _id;
this.url = _url;
this.place = _place; /*How to get this value */
};
SearchInList.prototype.FindMe = function (_str){
this.str = _str;
if (this.str == "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var place = this.place;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lista-ind").innerHTML = this.responseText; /*in this place */
}
};
xmlhttp.open("GET",this.url+"?id="+this.id,true);
xmlhttp.send();
} 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("lista-ind").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",this.url+"?id="+this.id+"&hint="+this.str,true);
xmlhttp.send();
}
};
in HTML I have
<input type="text" placeholder="Search" id="search-ind" ></div>
<div id="lista-ind" class="lista"></div>
<script>
var id = <?php echo $_GET['id']; ?>;
var url = "showresults.php";
var place = "lista-ind";
var searchInd = new SearchInList(id, url);
var searchboxInd = document.getElementById("search-ind");
window.onload = searchboxInd.addEventListener("keyup", function(){
searchInd.FindMe(searchboxInd.value,place);
console.log(searchboxInd.value);
}, false);
window.onload = searchInd.FindMe("",place);
</script>
and when i have in function in onreadystatechange " document.getElementById("lista-ind")" it is working, but when I change to
document.getElementById(this.place) it is not.
how to pass this variable into that function?
this is how i made searching in lists.
thanks.
M.
If place is a global variable, outside the function, you not need this; just the variable name.
document.getElementById(place)
You're instantiating SearchInList without a place and FindMe does not take place as a parameter, so there is no way to get place to use in the object.
The easiest solution would be to add place as a parameter to FindMe
SearchInList.prototype.FindMe = function (_str, _place){
this.str = _str;
this.place = _place;
...
Related
This is my code. i don't know what's wrong with my code but the readyState always return 1 and the status always return 0. can anyone please help me?
function Registered() {
console.log("masuk function");
var xmlhttp;
var randomNum = Math.floor((Math.random() * 100) + 1);
const proxyurl = "https://cors-anywhere.herokuapp.com/";
var url = "http://127.0.0.1:8080/webchatBack/webchat/getQueueCount?t="+randomNum;
var xmlDoc;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
console.log("masuk xml");
xmlhttp = new XMLHttpRequest();
} else if(window.ActiveXObject){// code for IE6, IE5
console.log("masuk active");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
console.log("masuk function lagi");
console.log(xmlhttp.readyState);
console.log(xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("masuk if");
xmlDoc = xmlhttp.responseXML;
var result = xmlDoc.getElementsByTagName("Result");
result = result[0].childNodes[0].nodeValue;
console.log(result);
document.getElementById("agentLoginData").innerHTML = result;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=\"utf-8\"");
xmlhttp.send('');
}
I have a button which increments a variable value, and I use this variable to load specific content. My problem is that after the page has loaded, I have to click 3 times for the first content load:
1st time I click: I get an undefined result because no ID is loaded
2nd time: the input field value from before I reload the page disappears
3rd time: the first content finally loads
Once the first content has loaded everything works fine. From what I understood it is because the variable isn't initalized at page loading. So I added an onload event but it doesn't work at all.
the script :
var Pokemon_ID = 1
function changePokemon(Pokemon_ID) {
function resetID() {
document.getElementById("id-input").innerHTML = Pokemon_ID;
}
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_ID, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
I also tried to declare my variable inside the changePokemon() function, but only the first id was loading I couldn't change the value of Pokemon_ID.
I tried to use const and let but both of them also didn't work
You use the same name Pokemon_ID for the global variable and the parameter to the changePokemon() function. The parameter is a local variable, so assignments to it don't affect the global variable. Give it a different name.
You need to take resetID() out of the changePokemon() function. It needs tobe in the global scope so it can be accessed from onclick.
To change an input, you need to assign to .value, not .innerHTML.
DIVs don't have a load event. You need to put onload="resetID()" in the <body> tag, or write:
window.onload = resetID;
in the Javascript.
var Pokemon_ID = 1
function resetID() {
document.getElementById("id-input").value = Pokemon_ID;
}
function changePokemon(Pokemon_val) {
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_val, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
Here is my JavaScript with Ajax code:
Actually i am using this for dynamically adding option in any number of select in which this function is called.
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
document.impForm.vm.options.add(createOption);
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}
I am using ondblclick="loadabc(this)" for calling it. I want to access this vm object for creating options in select. How can I do so?
The solution is to use the param vm instead of referencing it as document.impForm.vm:
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
vm.options.add(createOption); // <-- Here!
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}
In jquery I can do this
myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
alert(data);
});
How can I do the same thing using plain javascript ? I want to send an array to my php script using POST method. I have found so many examples but all of them are jquery related.
Thanks in advance.
You will have to use XMLHttpRequest and serialize the array yourself:
function ajax(myArray) {
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 whatever it is you want to do
}
}
//Serialize the data
var queryString = "";
for(var i = 0; i < myArray.length; i++) {
queryString += "myArray=" + myArray[i];
//Append an & except after the last element
if(i < myArray.length - 1) {
queryString += "&";
}
}
xmlHTTP.open("POST", "www.myurl.com", true);
xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHTTP.send(queryString);
}
Mess around with this.
JS
var myarray = Array("test","boom","monkey");
send("test.php", myarray);
function send(url, data)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("data= " +data);
}
PHP
<?php
$array = explode(',', $_POST["data"]);
for($i=0,$l=count($array); $i<$l; $i++)
{
echo $array[$i].'<br>';
}
?>
Something like this:
post is either POST or GET.
params are only used in POST otherwise include what you need in the url for GET.
success and error are both string names of the functions, not the functions themselves, which is why you need executeFunctionByName, thanks to Jason Bunting:
How to execute a JavaScript function when I have its name as a string
getRemoteData = function (url, post,params, success, error){
var http = false;
if (navigator.appName === "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
http.open(post, url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {var resp; if (http.readyState === 4 && http.status == 200) { resp=http.responseText; executeFunctionByName(success, window, resp); }else if(http.status == 400){resp=http.responseText; executeFunctionByName(error, window, resp);}};
http.send(params);
return false;
};
function executeFunctionByName(functionName, context, args) {
args = Array.prototype.slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
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 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","jsArrayPhp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("test[]=Henry&test[]=Ford");
}
Take attention here:
test[]=Henry&test[]=Ford"
Where test is the name of array you'll use in php.
In php
<?php
print_r($_POST['test']);
?>
It'd produce: Array ( [0] => Henry [1] => Ford )
I have an AJAX function which loads content from a file and displays in the file that called it.
But the script that was called I want to loop an array which is actually set in the script that called it... this is main script that calls the file:
function call_file(file, div_id) {
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 && xmlhttp.status == 200) {
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
var global = new Array();
global[0] = 1;
global[1] = 2;
call_script('html.html', 'main');
html.html is the file that is called which has this:
<script>
i = 0;
for(var id in global) {
alert(i + ' = ' + id);
i++;
}
</script>
Is this at all possible?
One way is to extract the script and eval it yourself. For example:
//....
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
var str = xmlhttp.responseText;
var reg = /<script>([^>]*)<\/script>/img;
while(reg.test(str))eval(RegExp.$1);
//...