getElementById.value and getElementById.value? - javascript

I have a problem regarding this two values from my textboxes (text, text2), seems like text2 only show its value, is there any way I can get rid of these things. Any help would be so much appreciated.
parameters = ('text=' + document.getElementById('text').value) && ('text2=' + document.getElementById('text2').value;
xmlhttp.open('POST', 'try.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);

parameters = ('text=' + document.getElementById('text').value) && ('text2=' + document.getElementById('text2').value;
This line is wrong. && does not mean "concatenate": it means "logical and". Basically, it means "return false if either side of the operator is falsy, otherwise, return the right-hand-side". So this will always return 'text2=' + document.getElementById('text2').value, because this is the right-hand-side of the && operator.
You need to concatenate them, for which the operator, as you use quite correctly otherwise, is +.
parameters = 'text=' + document.getElementById('text').value + '&' + 'text2=' + document.getElementById('text2').value;
Note that you should probably also use encodeURIComponent to make sure you're making valid HTTP requests:
parameters = 'text=' + encodeURIComponent(document.getElementById('text').value) + '&' + 'text2=' + encodeURIComponent(document.getElementById('text2').value);

Don't use && to concatenate strings, use +. There are also unbalanced brackets and you are missing the "&" to separate your parameters in the URL string.
parameters = 'text=' + document.getElementById('text').value + '&text2=' + document.getElementById('text2').value;

Related

Javascript .indexof 'typeError' error despite forcing string conversion

JS drives me insane with issues like this. I have the following code which creates a string (composed of session data and date information) to be written to an array, as such:
var _writes = String(req.session.subscriber + ":" + req.session.postal + "[" + req.session.id + "]=" + _onYear + "-" + _onMonth + "-" + _onDay + "-" + _onHour + "-" + _onMinute);
_users.push(_writes);
Later, I wish to perform an 'indexof' command on the string of the array, as such:
for (_cycle = 0; _cycle < _users.length; ++_cycle) {
_seeks = String(_users[_cycle]);
_score = _seeks.indexof("="); //ERROR THROWN HERE
//do other stuff here...
} //for loop
My error is "TypeError: _seeks.indexof is not a function"...? I thought by converting everything to a string I should be able to perform the 'indexof' command. Can somebody please advise what the issue is here? I thank you in advance.
Probably not a js issue. You are using "indexof" instead of "indexOf" (Uppercase O). Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
It should be:
_seeks.indexOf("=");
Don't give up, it will make sense soon :)

replace segment of a URL with regex

I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.
Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know
URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]
I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/

First character of a string fusionning with a %

So i'm sending a String with javascript to a php page :
if(cp.value!=''){
s+=cp.name +" LIKE '%"+ cp.value +"%'";
console.log(s);
if(sec.value!=''){
s+=" AND "+sec.name+" LIKE '%"+ sec.value +"%'";
console.log(s);
}
}
else{
if(sec.value!=''){disappear
s+=sec.name+" LIKE '%"+ sec.value +"%'";
}
}
console.log(s);
if(s.length!=0){
var connect = new XMLHttpRequest();
connect.onreadystatechange=function(){
if (connect.readyState==4 && connect.status==200){
var resu=connect.responseText;
console.log(resu);
var tab=document.getElementById("main_tab");
tab.innerHTML=resu;
}
};
connect.open("POST","../../Controller/stage.php",false);
connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
connect.send("s="+s);
}
}
The string sent is for exemple :
CP_Stage LIKE '%90%' AND secteur_stage LIKE '%ait%'
But when i print the request in the php page i have something like :
SELECT * FROM Stage WHERE CP_Stage LIKE '�%' AND secteur_stage LIKE '%ait%';
i have no idea why my first number disappear with the first %.
If anyone have an idea it would be awesome, thanks !
The percent-sign is a special charcter. Any special characters like %,&,? etc need to be encoded. Your "%90" is converted to an Ascii-Value. You have to encode these values with encodeURIComponent.
s += cp.name + " LIKE '" + encodeURIComponent("%" + cp.value + "%") + "'";
Note that encodeURIComponent does not escape the ' character. If your cp.value has an ' you have to replace it with its encoding value: %27.
By the way.. its a bad idea to send mySQL-queries from client-side - thats a major security flaw. Send only the values and build your queries on server-side.

pass toString(number) in innerHTML

This is my first post, I am "new" to javascript but experienced in actionscript. I'm having an issue that should not be one, can't get my head around it.
In the code below all I want to do is pass a integer variable (stackID) as an img id attribute inside innerHTML. It must be some detail I just don't know but I have searched for hours on google to no avail. Help would be greatly aprreciated. Whatever I do, it seems I can only pass <img id="string">, which of course is not what I want. Can't pass <img id=numVariable>, or <img id=String(numVariable)>, there must surely be a way to do this ?
Thanks folks !
Here is the line of code :
div.innerHTML='<img src="img/xbut.png" id=String(stackID) onclick="close(this.id)">';
You're trying to pass it in the string.
What you want to do is:
div.innerHTML='<img src="img/xbut.png" id="' + String(stackID) + '" onclick="close(' + this.id + ')">';
Oh and since you're already making a string, you don't need the String() convert, you can just id="' + stackID + '"
Javascript is loosely typed and will automatically convert (to the best of its abilities) anything you want to interpolate in a string:
var num = 1;
"sup" + num; // => "sup1"
It's cool, but be careful though, it can lead to some weird surprises:
var obj = {};
"sup" + obj.missingKey; // => "supundefined"
In that case, obj.missingKey === undefined, and String(undefined) === "undefined", so "sup" + obj.missingKey becomes in fact "sup" + "undefined"
javascript has not string interpolation. Concatenate stackId like:
div.innerHTML='<img src="img/xbut.png" id="' + stackID + '" onclick="close(this.id)">';
Use '+' to join chunks like this:
div.innerHTML='<img src="img/xbut.png" id="' + String(stackID) + '" onclick="close(' + this.id + ')">';
Try this, you make the variable is dynamic:
var x = 0;
x = x +1;
div.innerHTML='<img src="img/xbut.png" id="name_' + x + '" onclick="close(this.id)">';

javascript - function with dot notation using concatenation and array value

<script src="modernizr-1.7.min.js"></script>
var modernizr_fields = new Array("canvas","video","webgl");
for (i=0; i < modernizr_fields.length; i++) {
document.writeln(modernizr_fields[i] + " ");
if (Modernizr + "." + modernizr_fields[i])
document.writeln("true");
else
document.writeln("false");
document.writeln("<br>");
}
I know the problem is with this line: "if (Modernizr + "." + modernizr_fields[i])" as it is always evaluating to "true"
Please help with my syntax.
You need:
if (Modernizr[modernizr_fields[i]]) {
...
}
The format obj.field only works with literal field names, if field is instead a variable you have you use obj[field]

Categories

Resources