How to pass dynamic variables from a url to php via ajax

Asked

Viewed 835 times

2

First of all I have looked in several other posts on the subject here and I did not find what I need, my scenario is the following I am generating several EX links:

challenge.php? id=2&name=Joao

challenge.php? id-3%name=Jose

and I need to pass this via ajax to my php page that processes it. however the page is not getting the data what can be? follows my code

urls generated
<a id='desafiar' href='desafiar.php?idd={$linha['id']}&d={$linha['username']}'></a>

script

 $(document).ready(function() {
    $("#desafiar").click(function( e ) {
            e.preventDefault();
            var url = $( this ).attr('href');
            $.ajax({
                 cache: false,
                type: "POST", 
                 url: "desafio.php", 
                data: {url},
                success: function( data ){
                $("#resultado").html( data );
                }
              });
    });
 });

in the page that picks up php

  $iddesafiante = $_SESSION['user_id'];
  $desafiante = $_SESSION['username'];
  $iddesafiado = $_GET['idd'];
  $desafiado = $_GET['d'];

open to suggestions

  • Possible duplicate of send the javascript variable to php

  • You’re using type: "POST", in Javascript and $_GET in PHP. You have to use the same in both.

  • @Khaosdoctor I voted to leave open, because despite the problems seem, are different things, in the link that posed the problem is "send the variable", in this case the difficulty is with GET and POST, which makes a different problem.

1 answer

3


You’re using type: "POST", in Javascript and $_GET in PHP. You have to use the same in both.

If you are not using the anchor link then I suggest you use another way to pass these values. You can have a json in HTML like this:

<a id='desafiar' data-idd="{$linha['id']}" data-d="{$linha['username']}" href='desafiar.php'></a>

That makes more sense to me, and then you can use

$(document).ready(function() {
     $("#desafiar").click(function(e) {
         e.preventDefault();
         var data = this.dataset;
         $.ajax({
             cache: false,
             type: "GET",
             url: "desafio.php",
             data: data,
             success: function(data) {
                 $("#resultado").html(data);
             }
         });
     });
});
  • I understood here the part of the date-variables within the link understood, more in the ajax in the date:{}; would it be only date:{data} even? this var data = this.dataset; already leaves in ready format?

  • @Arsomnolasco really should be just data: data,, corrected. Yes the .dataset is already an object (Domstring) and jQuery converts to the required format.

  • can be passing as many variables as you want through the date- inside the link?

  • @Arsomnolasco yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.