Carrying a PHP variable to Ajax


I am trying to get Ajax to load a form which is created in PHP and assigned a variable $copen.  

In Ajax how do I go about placing the variable in the URL part of Ajax to open and retrieve the JSON data.  

The code in my Ajax script:



```
        $.ajax({
             async: false,
             url: 'queryme3x.php',
             type: 'get',
             dataType: "json",
             success: function(data) {
               $.each(data, function(i, val){

                val.timestamp = Date.parse(val.date);

                // save the years so we can create year markers
                var year = new Date(val.timestamp).getFullYear();
                if (years.indexOf(year) < 0)
                    years[years.length] = year;

                // combine data & templqate
                var html = postTemplate(val);

                $('#timeline').append(html);

```

And the code in my PHP script:



```
<?php
require("dbenter.php");
$checks = $_POST['check1'];
if (isset($checks) && !empty($checks)){
foreach ($_POST['check1'] as $tst1) {
    $tst1 = implode("' OR Category ='", $checks);
}
$checks1 = "'".$tst1."'";
}

$sql = "SELECT * FROM tstline WHERE Category =$checks1";
$result = mysql_query($sql);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
    $row = array();
    $row['date'] = $r['date'];
    $row['Year'] = $r['Year'];
    $row['Category'] = $r['Category'];
    $row['Subcategory'] = $r['Subcategory'];
    $row['Location'] = $r['Location'];
    $row['Shortdescription'] = $r['Shortdescription'];
    $row['Fulldescription'] = $r['Fulldescription'];
    array_push($rows,$row);
}
$fdate = date('mdy');
$fp = $checks1.$fdate.".json";
$stripout = array("'","OR","="," ","Category");

$nfname = str_replace($stripout,"",$fp);
echo $nfname;
$tst2 = $checks;
if (file_exists($nfname)) {
    $copen = $nfname;
    return true;
}
else {
    $copen = fopen($nfname,'w+');
    fwrite($copen, json_encode($rows));
}
echo json_encode($rows);
?>

```

As you can see its the value of $copen that I want to carry into the Ajax URL section.  

Any help would be appreciated :)
Try this... Save the value to an input element of type "hidden" from your PHP code. The information wont be visible but it will be accessible client side. Then client side, grab the value using jQuery assign it to a variable then work with that variable in your Ajax routine.
JavaScript *itself* has nothing built in for handling query string parameters. 


Code running in a (modern) browser you can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (which is part of the APIs provided by browsers to JS):





```
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
```









For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/ungap/url-search-params) or the code from the original version of this answer that predates `URL`:


You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.


Then you can parse it with this:





```
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key]  "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key]  "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
```




You can get the query string from the URL of the current page with:



```
var query = window.location.search.substring(1);
var qs = parse_query_string(query);

``` First you need to clear the call in the database. `$mysqli->query`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

sent request before parameter binding, etc.


Replace as follows:



```
$stmt = $mysqli->prepare('SELECT reply\_id FROM replies WHERE reply\_topic = ? ORDER BY reply\_date ASC');
$stmt->bind_param('i',$param)
$stmt->execute();

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

 `$mysqli->prepare`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

returns a new object for which you want to bind values ​​and execute them. It avoids [SQL injection](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=) !


None of this is discounted. `mysqli_`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

is exactly what you should be using.



  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

Since all you need is an array of results, you can use the following code to do this - no custom functions are required.



```
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
        $set[] = $row['reply\_id'];
}

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

For each row, `while`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

each field is stored in an array with the column name as the key. Thus, `$row['reply_id']`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

contains the value of a column `reply_id`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

in the database. Above, I have stored this value in a named array `$set`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

and when it iterates over the next row of the result, it also stores the next value for that array.


You can manipulate the result before or after saving it to a new array as you see fit.


Hope it helps. 1) Usage `yii`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

and `php yii`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

exactly the same. If you look at the file `yii`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

, you'll see it in the first line `#!/usr/bin/env php`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

. This is called the "shebang" syntax and instructs your shell to automatically execute the `yii`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

script using binary code `php`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

. See: [https://en.wikipedia.org/wiki/Shebang\_%28Unix%29](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=)


2) The difference here is flexibility. If you use the syntax `Schema::TYPE_PK`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

, Yii will automatically detect the exact column type based on your database database. For example, it `Schema::TYPE_PK`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

translates to `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

in MySQL, but if you use Postgres as your database, it will translate to `serial NOT NULL PRIMARY KEY`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

. [1]



  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

In practice, it is unlikely which method you are using because you are probably not going to switch to a different type of database halfway through your project, and therefore there is no need for your migration scripts to be database agnostic. Based on your preference, you can choose the syntax `Schema`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

for added flexibility, or for a hard-coded syntax to make your hyphenation definitions more readable for future readers.


[1] See [https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php#L21](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=) and [https://github.com/yiisoft/yii2/blob/master/framework /db/mysql/QueryBuilder.php#L24](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=) Hello Dmytro,


You will need to bind to the Custom Command, create arguments for the command execution, specify parameter values that will be used to execute the command in the Scheduled Task and then pass the arguments to the Arguments property of the action. Here is the code that will do the trick:



```
# Define actions and conditions for the task

$commandID = "{a7264a61-b77d-4386-a138-ec2557c5b3ba}" # Command ID
$commandDN = "CN=MyCommand,CN=Custom Commands,CN=Configuration Objects,CN=Adaxes Configuration,CN=Adaxes" # Command DN

# Create action set
$actionsAndConditions = $task.ConditionedActions.Create()
$actionsAndConditions.ConditionsLogicalOperation = "ADM_LOGICALOPERATION_AND"
$actionsAndConditions.SetInfo()

# Create execute Custom Command action
$action = $actionsAndConditions.Actions.CreateEx("adm-CustomCommandAction")
$action.ExecutionOptions = "ADM_ACTIONEXECUTIONOPTIONS_SYNC"

# Get action
$removeAction = $action.GetAction()

# Bind to Custom Command
$customCommand = $Context.BindToObjectByDN($commandDN)

# Specify command arguments
$arguments = $customCommand.CreateArguments()
$arguments.SetParameterValue("MyParameter", "MyValue") # Parameter value

# Configure the action
$removeAction.CustomCommandId = $commandID
$removeAction.Arguments = $arguments

# Save action
$action.SetAction($removeAction)
$action.SetInfo()
```

In the script, the $commandDN variable specifies the distinguished name (DN) of the Custom Command. For information on how to get the DN of a directory object, see <http://adaxes.com/sdk/?HowDoI.GetDnOfObject.html>.


For details, have a look at the following SDK article: <http://adaxes.com/sdk/?IAdmCustomCommandAction2.html>. Let's say in your `settings.py` file you have:



```
SITE_URL='www.mydomain.tld/somewhere/'
SITE_NAME='My site'

```

**If you need that in just one or two views:**



```
from django.shortcuts import render_to_response
from django.conf import settings

def my_view(request, ...):
    response_dict = {
        'site_name': settings.SITE_NAME,
        'site_url': settings.SITE_URL,
    }
    ...
    return render_to_response('my_template_dir/my_template.html', response_dict)

```

**If you need to access these across a lot of apps and/or views, you can write a context processor to save code:**


James has a tutorial on this 
[online](http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/).


Some useful information on the when and if of context processors is available on this very site 
[here](https://stackoverflow.com/questions/831301/when-is-it-appropriate-to-use-django-context-processors).


Inside your `my_context_processors.py` file you would:



```
from django.conf import settings

def some_context_processor(request):
    my_dict = {
        'site_url': settings.SITE_URL,
        'site_name': settings.SITE_NAME,
    }

    return my_dict

```

Back in your `settings.py`, activate it by doing:



```
TEMPLATE_CONTEXT_PROCESSORS = (
    ...

    # yours
    'my_context_processors.some_context_processor',
)

```

In your `views.py`, make a view use it like so:



```
from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view(request, ...):  
    response_dict = RequestContext(request)
    ...
    # you can still still add variables that specific only to this view
    response_dict['some_var_only_in_this_view'] = 42
    ...
    return render_to_response('my_template_dir/my_template.html', response_dict)

``` The problem is the response from the server, not your JavaScript. I ran the following code in the console on your page:



```
$.getJSON('data.json', function(data) { 
    console.log(data); 
});

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

The result looks like this:



  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

 ![enter image description here](https://fooobar.com//img/b0b4666ec951695a00da8c82eb85e737.jpg)


As you can see, there is only one property in the returned object ( `mesta`
  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

, an array with three elements).


You can confirm this by [visiting the file directly`data.json`
  




 (adsbygoogle = window.adsbygoogle || []).push({});](https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=) . Okay well if those query parameters really do represent arbitrary text a visitor enters into fields, then personally I would push them to separate Adobe Analytics variables instead of concatenate them, because there's no guarantee on how many characters they will be or what characters will be entered. 

I'm not sure I understand what you mean... is your site just using different query parameters for search terms, depending on the page or search widget used? So e.g. maybe you do a search and it pops k=[search term] but on search results page you do another search and it instead pops query=[new search term] ?  If so, then it sounds to me like you shouldn't concat them, but instead just look for either one and push to the variable.  

Or is it that a visitor can go to your site and search for something that results in both of those parameters showing up in the URL at the same time, with different values? 

I think I need clarification about how your site actually works vs. these two parameters. 




[View solution in original post](/t5/dynamic-tag-management-questions/internal-search-term-tracking/m-p/278167#M1141) hi chris, 
if you use relations api, you may set properties field in your query. in this field you should set the names of the properties which values must be retrieved from the server. the argument should be a string in the following format: "propertyname1, propertyname2, , , propertynamen" , wher… [@rbarriuso](/u/rbarriuso), to set script response from an async operation use the method below…

event.setresponse(content, statuscode, contenttype)

so in your case it will be like …

myapi.authentication

.login("mylogin", "mypassword")

.then(function(result) {

console.log("auth correct: ", result);

var c… You could achieve this with a simple `for` loop:



```
var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/).


[JS Perf](https://jsperf.com/) comparison of both mine and [Sime Vidas' answer](https://jsperf.com/comparison-of-loops), run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.







**Edited** in response to comment from OP:



> 
> [How] do [I] apply this to more than one element?
> 
> 
> 



```
function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/1/).


And, finally (after quite a delay...), an approach extending the prototype of the `HTMLSelectElement` in order to chain the `populate()` function, as a method, to the DOM node:



```
HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/148/).


References:


* [`node.appendChild()`](https://developer.mozilla.org/en/DOM/node.appendChild).
* [`document.getElementById()`](https://developer.mozilla.org/en/DOM/document.getElementById).
* [`element.innerHTML`](https://developer.mozilla.org/en/DOM/element.innerHTML).