0

I have two types of links in my webpage:

<div id="mybookings">
<a name="type1ID" href="4007" class="booking-deleteDraft">Delete Me</a>
<a name="type2ID" href="9001" class="booking-deleteDraft">Delete Me</a>
</div>

I am writing an ajax submit and need to include the correct data in the POST. How do I ask JQuery to do the following:

    $("#mybookings").on('click', '.booking-deleteDraft', function (e) {
    e.preventDefault();
     data: {
             Type1ID: $(this).attr("href").val() // This gets the value of the href, but it should only get it where the name attribute is "type1"
             Type2ID:  $(this).attr("href").val() // This gets the value of the href, but it should only get it where the name attribute is "type2"
           },
.....

How do I get the the correct values into the Type1ID and Type2ID parameters?

volume one
  • 6,800
  • 13
  • 67
  • 146
  • 1
    Use the [attribute selector](http://api.jquery.com/attribute-equals-selector/). Something like `$("[name='type1ID']").attr("href").val()`. – Matt Burland Jan 27 '14 at 14:09
  • 1
    possible duplicate of [jquery selector: anchor elements by name](http://stackoverflow.com/questions/8948758/jquery-selector-anchor-elements-by-name) – Liam Jan 27 '14 at 14:09
  • Are you only ever going to have these two types? – crush Jan 27 '14 at 14:11
  • 1
    @crush maybe not... I guess I could end up with more types. Damn I didn't think it through. – volume one Jan 27 '14 at 14:16

4 Answers4

5

With this css selector a[name="type1"] and a[name="type2"]

data: {
     Type1ID: $('a[name="type1"]').attr("href") // This gets the value of the href, but it should only get it where the name attribute is "type1"
     Type2ID:  $('a[name="type2"]').attr("href") // This gets the value of the href, but it should only get it where the name attribute is "type2"
   },
gpopoteur
  • 1,509
  • 10
  • 18
  • Don't I need the $(this) selector before the 'a[name="type1"]' part? – volume one Jan 27 '14 at 14:15
  • 1
    No you don't, because you want the value inside the object referred in the CSS Selector. – gpopoteur Jan 27 '14 at 14:17
  • What is `this` in your context? Is it the form? – crush Jan 27 '14 at 14:18
  • Its the link itself... I added it to my OP. My link has a class. – volume one Jan 27 '14 at 14:20
  • Is your intent to submit the form to a different `action` based on the `href` of the link that is clicked? – crush Jan 27 '14 at 14:22
  • No, they get submitted to the same action. the action page is the same... it accepts Type1ID and Type2ID and then does whatever is necessary depending on which one is present. They both can't be present at the same time, obviously. – volume one Jan 27 '14 at 14:29
1
$('a[name="type1"]').prop('href');
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
  • @Liam: `prop` works perfectly fine here. JQuery copies attributes into properties. – Matt Burland Jan 27 '14 at 14:11
  • @Liam prop will find it too. – Popnoodles Jan 27 '14 at 14:12
  • I thought this was frowned upon if it was a attribute, [but it turns out I'm wrong](http://stackoverflow.com/questions/5874652/prop-vs-attr) – Liam Jan 27 '14 at 14:14
  • 1
    **Prop is actually much slower [in this use case](http://jsperf.com/prop-vs-attr-for-href).** – crush Jan 27 '14 at 14:17
  • 1
    `.attr()` and `.prop()` is not the same. `attr == HTMLELement.getAttribute('href')` which return the attribute itself (in this case `type1ID `) while `prop == HTMLElement.href` which return the entire url (in this case something like `https://www.mySite.com/type1ID `). In this case, prop will not work. – Karl-André Gagnon Jan 27 '14 at 14:28
1

You have a click event handler that is bound with jQuery that probably looks something like this:

$('a.booking-deleteDraft').on('click', function(e) {
    //Do stuff here.
});

I'd suggest doing the following:

$('a.booking-deleteDraft').on('click', function(e) {
    var $this = $(this),
        type = $this.attr('name'),
        href = $this.attr('href'),
        data = {};

    data[type] = href;

    //Append any additional data to the data object here.

    //You could use $.post or $.get here too.
    $.ajax({
        //Your ajax options.
        data: data //Send the data object here.
    });
});

Now, any of your booking-deleteDraft links will automatically be handled.

EDIT If you need the key to be type1ID instead of type1, then just append 'ID':

data[type + 'ID'] = href; 

WARNING

If you are using this value directly in your database query, you need to sanitize it server-side. The value here could easily be manipulated, allowing an abusive user to specify virtually any field of your database table, and its value. It could also open you up to SQL-injection if you are not using prepared statements.

Compare the values you receive server-side against a list of valid values.

Community
  • 1
  • 1
crush
  • 16,713
  • 9
  • 59
  • 100
  • On the server side it goes like this: `if Type1ID exists then { delete from table where type1ID = #url.type1id# and table.ownerID = session.userID }` – volume one Jan 27 '14 at 14:51
  • @volumeone Well, that's one way to do it. Make sure you are using prepared statements, or sanitize the input of `href` or you'd be open to SQL-injection still. For example, a user sends `'; DROP table --` or `' OR '1' = '1' --` as the `href`. – crush Jan 27 '14 at 14:55
  • can you specify key names using variables? this is not working: `name = $(this).attr('name'); bookingid = $(this).attr('href'); .... data: { name:bookingid }` If I do this, then in the POST it is sending "name: 4007" for example. when it should send "type1id:4007" for example – volume one Jan 27 '14 at 15:07
  • You have to do it like I did above. Make a variable named data (or whatever you want) that is a JS object `{}`. Then, give it the variable key name with the `[]` accessor: `data[name] = bookingid`. Then pass your data object variable to the data property of your ajax call: `data: data`. If you named your `data` variable `myData` you'd do: `myData[name] = bookingid;` and `data: myData`. – crush Jan 27 '14 at 15:10
-1

In case you have delete links based on entries in database or anything like that.. You can try this:

$("#mybookings").on('click', '.booking-deleteDraft', function (e) { 
       e.preventDefault(); 
       data: {
            $(this).attr("name"): $(this).attr("href");
         });
Liam
  • 27,717
  • 28
  • 128
  • 190
  • I like this so it means I'm not restricted to just Type1ID and Type2ID – volume one Jan 27 '14 at 14:31
  • @volumeone, are you sure this is what you want? It's going to send totally different data to your original question? – Liam Jan 27 '14 at 14:37
  • Um, I think so. the "name" is the name of the field in my database. So when the action page receives a "Type1ID" parameter, it knows to delete from the database where Type1ID = href's value. If it received a Type2ID then it knows to delete where Type2ID = href's value. And so on.. – volume one Jan 27 '14 at 14:39
  • 1
    This throws an error for me. **I don't think you can specify a key like that.** – crush Jan 27 '14 at 14:42
  • @volumeone: You just have to use Type1ID, Type2ID and so on.. inside name attribute of link and path inside href attribute. and the code will get values of current clicked link using $(this). In case it navigates you to href link, try changing href to data-href or some other attribute. – Freelance PHP Programmer Jan 27 '14 at 14:42
  • This is not working for me, I'm getting syntax errors. The $(this).attr("name"): part is breaking it. – volume one Jan 27 '14 at 14:43
  • @volumeone Perhaps you should be sending two properties, instead of just one: `id` and `value`. Where `id` is set to the `name` of the link and `value` is set to the `href`. You should be careful with this server-side though. Someone could easily manipulate these values. – crush Jan 27 '14 at 14:48
  • Here's the complete code i made in jsbin. you can modify it as required: http://jsbin.com/iVAbohuV/1/edit?html,css,js,output – Freelance PHP Programmer Jan 27 '14 at 14:57
  • I can't specify the key using a variable. it just sends "name" in the post instead of the value of the name attribute – volume one Jan 27 '14 at 15:04
  • in jsbin, click on "Run with Js" button, then click on any output value named as "Delete Me", you should get the value not the key in alert box like this here: http://i.imgur.com/m4Aj2nF.png also make sure you dont write variable as "name" in quotes or it will send the value "name" as string not its value, Have a look at jQuery documentation for .attr() function: http://api.jquery.com/attr/ – Freelance PHP Programmer Jan 27 '14 at 15:36