This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
i have a the following url
http://www.test.com/index.html?num1=123&num2=321
Now i want to grab the values of num1 and num2 using javascript
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
alert(QueryString.num1);
I feel like reaching the get parameters with javascript is kind of mixing up the roles of PHP and javascript so i prefer to do it this way. You can get the URL with window.href and parse but this is better form
Somewhere in PHP body:
echo '<input type="hidden" id="num1_arg" value=" . $_GET['num1'] . '/>';
echo '<input type="hidden" id="num2_arg" value=" . $_GET['num2'] . '/>';
Javascript (ill use jquery, but it can be done without)
n1 = $('#num1_arg').val();
n2 = $('#num2_arg').val();
Try using this simple function:
var parseQueryString = function() {
var queryString = window.location.search.substring(1);
var pairs = queryString.split("&");
var params = {};
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split("=");
var key = parts[0];
var value = parts[1];
params[key] = value;
}
return params;
};
If num1 and num2 are always in the same order, you can use regular expressions:
var url = ...
var pattern = /num1=(\d*)&num2=(\d*)/
var match = pattern.exec(url)
var num1 = match[1]
var num2 = match[2]
Related
Here I am getting the counter value using javascript.
I want to insert those counter value into my database.
How can I do it? Please suggest me.
<script language="JavaScript">
var counter = 1;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
please read W3school ajax tutorial and click on try it yourself button I am sure that you will easily get that :)
I am trying to pass values from a multiple select listbox through Ajax to PHP. I saw some examples in Jquery and JSON, however I am trying to accomplish this just in plain old javascript (Ajax). Here is what I have so far (simplified):
Ajax:
function chooseMultiEmps(str)
{
var mEmpList2 = document.getElementById('mEmpList'); //values from the multi listbox
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myPage.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&mEmpList=" + mEmpList; //query string should have multiple values
xmlhttp.send(queryString);
}
I can run an alert(mEmpList) and get each value in individual message boxes, however when I retrieve and echo the $_POST['mEmpList'], I get only the first value. Also, when I alert(queryString), I get only one value.
I think I need to create a comma delimited array, and then pass that through the query string. From there, I can use the PHP implode/explode feature to separate the values. Any assistance would be greatly appreciated.
here:
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
you are redefining your mEmpList over and over again, that means only the last value is send
You could do:
var mEmpList = '';
for (var i = 0; i < mEmpList2.options.length; i++) { //loop through the values
mEmpList = mEmpList +','+ mEmpList2.options[i].value; //create a variable to pass in string
}
Also your queryString is not ok, no need for &
var queryString = "mEmpList=" + mEmpList;
That way at the end you will have all values delimite by comma ,
In PHP you can use explode to loop each value:
<?php
$string = explode(',' $_GET['mEmpList']);
for($i=1; $i<count($string); $i++){
echo $string[$i]."<br />";
}
?>
Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help
I am creating an URL like this:
www.mysite.com/xyz.php/0:100003044058740-1:100000657838131-2:100001676304188-3:1075440919-4:100002474721536-5:100003033556875-6:1257699872-7:1257699872-8:100000501703505-9:100000297352382
from this function in my .php file
function finish(){
var allInputs = $(".gift_user",$("#scrollWrapper"));
var param = ""; //:
for(i=0;i < allInputs.length;i++){
var inEl = $(allInputs[i]);
var id = inEl.attr("id");
var val = inEl.val();
var arr = id.split("_")
var giftId = arr[2];
var userId = $.trim(inEl.val());
if(userId != ""){
if(param != ""){
param = param + "-" ;
}
param = param + giftId + ":" + userId ;
}
}
var url = "https://mysite.com/abc.php" + param ;
$('#finishButtonContainer').hide();
$('#processing').show();
window.location= url;
}
I want to get the value after xyz.php in my file abc.php where it take me to into an array. How can I do that?
Either manipulate the $_SERVER['REQUEST_URI'] value or pass the the value after xyz.php as a queryString
example:
www.mysite.com/xyz.php?0:100003044058740-1:100000657838131-2:100001676304188-3:1075440919-4:100002474721536-5:100003033556875-6:1257699872-7:1257699872-8:100000501703505-9:100000297352382
www.mywebsite.com/?foo=bar
How can I get the value of foo into a Javascript variable?
You don't even need PHP for that. Basically, you can parse window.location.href to get the value of a GET URL parameter into a JavaScript variable.
There is plenty of code online, you can use for example this:
function getUrlParameter( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
To get the value of foo, just call getUrlParameter("foo") in your JavaScript code.
You can parse the window.location.search string for query variables.
https://developer.mozilla.org/en/DOM/window.location
For example
var query = window.location.search.substring(1);
var pairs = query.split('&');
var _get = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
_get[pair[0]] = pair[1];
}
I did some googling and here is a link for you http://www.zrinity.com/developers/code_samples/code.cfm/CodeID/59/JavaScript/Get_Query_String_variables_in_JavaScript
You can try this
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
EDIT
The above will parse the URL and give you the parameters as an associative array. You can also try
function getURLVars(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
In this if you want the value of foo, call this with getUrlVars('foo')