1

I have a problem with the variables, that I want to pass through ajax to php.

In an php file, I generate some divs with id and name attributes.

livesrc.php

echo "<div class=\"search-results\" id=\"" . $softwareArray['Sw_idn'] . "\" 
name=\"" . $softwareArray['SoftwareName'] . "\" 
onclick=\"addBasket(this.id, this.name)\" >
" . utf8_encode($softwareArray['SoftwareName']) . "</div>";

The relevent part is this:

onclick="addBasket(this.id, this.name)

Sorry for the escapes, in html the div looks like:

<div class="search-results" id="235" 
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this.id, this.name)">...</div>

This looks okay, but in the js "addBasket", the variable sw_name is not set. (undefinded)

The JS in the head section:

<script type="text/javascript">
  function addBasket(sw_id, sw_name) 
  {
    alert(sw_name);
    $.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data) 
  { 
      $("#basket").html(data);
    });
  }
</script>

The sw_id is set, but the sw_name is not working. Is the call in html with "this.name" correct?

2
  • 1
    Try $(this).attr("name") Commented Oct 14, 2013 at 15:49
  • Could you try $(this).attr('name') ? (if you're using jQuery? Commented Oct 14, 2013 at 15:50

2 Answers 2

5

it's because this.name did not exists if you want to access the attribute you have to call this.getAttribute('name') id are particular and can be access directly.

Personally I will give juste this to the function and extract id and name in the function

 onclick="addBasket(this)";




<script type="text/javascript">
  function addBasket(el) 
  {
    var 
    sw_id = el.id,
    sw_name = $(el).attr('name');

    alert(sw_name);
    $.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data) 
  { 
      $("#basket").html(data);
    });
  }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

what does it mean that "el" in this term sw_id = el.id, sw_name = $(el).attr('name');
0

You could pass the whole element into your js:

<div class="search-results" id="235" 
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this)">...</div>

Then grab what you want in your function

function addBasket(sw) {
    alert( sw.id + ' ' + sw.getAttribute( 'name' ) );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.