0

Im fairly new to php and ajax. I am trying to pass along a variable from jquery to a php page that is loaded up in a modal window.

I have php returning the table information for a bunch of users. Next to each users name, I have an edit button. I have jquery grabbing the data-id parameter of that button.

$(document).ready(function() {
$('.editButton').click(function(e){
e.preventDefault();
    var getid = $(this).data('id');

Now I have a php form script that I want to load in a modal window when the "edit" button is clicked. The only way to do that is to make the button that opens the modal window an a tag and use href to call the php script. I want to pass along the variable "getid" to the php script that will use the value to run a query against the database to find the user that was clicked(the data-id parameter is generated by another php script which returns the id of that user). I tried many ways to send the ajax information to the external php script but no matter what I do, cant get it to work. Here is my ajax request:

        $.ajax ({
        url: '/extschedule.php',
        data: {getid : getid},
        type: 'POST',
        success: function(data) {
        alert('success');
        }           
}).error(function() {
Alert('Error');

Here is the php code on extschedule.php:

$connection = mysqli_connect(stuff);

            $idVar = $_POST['getid'];

            $sqledit = "SELECT * from database WHERE id = (".$idVar.")";
            $result = $connection->query($sqledit);


            while($row = $result->fetch_array(MYSQLI_ASSOC)){
                $name = $row['name'];
                $id = $row['id'];
                $team = $row['team'];
                $language = $row['language'];
                $dedicatedHotel = $row['ded_hotel'];
                $satStart = $row['Sat_start_time'];
                $satEnd = $row['Sat_end_time'];..............yadda yadda

I tried using if(isset($_POST['getid']))) but that causes a ton of issues on the php side. Ive searched around a while but still cannot get to any resolution. Can someone help me with this? Thanks in advance!

user247326
  • 151
  • 8
  • 1
    Have you checked the console for errors with the request? – Rory McCrossan Jan 26 '15 at 15:20
  • 1
    you are vulnerable to [sql injection attacks](http://bobby-tables.com), and need to do some basic debugging: Have you checked if `getid` ever gets set properly in your JS code? Did you look at what's coming across in `$_POST`? – Marc B Jan 26 '15 at 15:20
  • 1
    _"I tried using if(isset($_POST['getid']))) but that causes a ton of issues on the php side."_ - What errors did this cause? The code should have been wrapped in the `if` block to stop further execution if `getid` is not defined. Then optionally, log the error or handle a case where `getid` is not defined. – War10ck Jan 26 '15 at 15:22
  • @ Rory - I have checked the console and I see XHR request, I dont see any errors – user247326 Jan 26 '15 at 15:22
  • @marc In troubleshooting earlier, I had jquery printing out the variable's value in the console and it was correct – user247326 Jan 26 '15 at 15:24
  • what is the type of the editbutton? – Hemant Jan 26 '15 at 15:25
  • @War10ck - Depending on where I put the end "}" i would get errors where Variable idVar is undefined, Variable index 'getid' not defined or if i placed the "}" at the end after the echo, the php script would return nothing. – user247326 Jan 26 '15 at 15:25
  • ok, so it works in the client/JS-side of things. what about on the server? `var_dump($_POST)` and whatnot... – Marc B Jan 26 '15 at 15:26
  • The second scenario where PHP returned nothing is what you want. Instead of returning nothing though, log that scenario as an error and return an appropriate error message back to the ajax call. The PHP error comes from the fact that you were trying to use a variable that was `undefined`. If the variable is `undefined` you shouldn't continue execution at all. – War10ck Jan 26 '15 at 15:26
  • @Hemant - the button is set to button. I changed it to submit while troubleshooting but that didnt help things. Got the same errors that I wrote in my respone to War10ck – user247326 Jan 26 '15 at 15:27
  • Can you put in your url the extschedule.php, add a get param like `http://url/extschedule.php?getid=1` change the code to a `_GET` instead of a `_POST` and confirm that the expected output is being displayed without any other changes? – Dave Goten Jan 26 '15 at 15:27
  • Try removing "/" from the url: '/extschedule.php' in the AJAX call – Hemant Jan 26 '15 at 15:29
  • @DaveGoten - ill give that a try and report back – user247326 Jan 26 '15 at 15:30
  • @DaveGoten - That worked perfectly. However, the getid should vary depending on which button is clicked. I have a jquery script to grab the id that should be used as the value of getid. What is the proper way of passing the jquery variable into the url? – user247326 Jan 26 '15 at 15:42
  • @user247326 you're doing it correctly as far as I can tell from what you've given us. I was just making sure that your PHP was returning the correcting output without any errors, if it didn't work with a direct call it wouldn't work with a post. Oh on a side note, you might want to change the `Alert` to `alert` in your error method, it could cause you issues. – Dave Goten Jan 26 '15 at 15:48
  • @DaveGoten will do. I like the url strategy better. I have changed the href in the "edit" button to 'http://localhost/extschedule.php?getid=164'. is there a way to edit the value of getid to equal the data-id of that same button or the variable in the jquery function? – user247326 Jan 26 '15 at 15:56
  • @user247326 I wasn't encouraging you to change it to a url, it was okay as it was, just checking that the power was on before trying to debug the os, as it were. check out `http://api.jquery.com/jquery.post/` the shorthand version of $.ajax for posting – Dave Goten Jan 26 '15 at 16:08
  • I changed the jquery to: var getid = $(this).data('id'); $.post('/extschedule.php', {getid: getid}); and the php simply to: if(isset($_GET['getid'])){ echo "got value"; }else{ echo "no value"; } keep getting no value – user247326 Jan 26 '15 at 16:47

2 Answers2

0

I don't see you echo data when query is success. Can you try it again with: echo "bla bla bla"; in file php.

  • the echo is very long..its basically returning values for every user that are in the database. My situation was confusing enough and didnt want to add additional junk here. The call works under certain situations but not the way I want it to. – user247326 Jan 26 '15 at 15:44
0

I've had some issues several times with this going between PHP versions. I thought I was going insane, and this post - Sending JSON to PHP using ajax explains things a bit better.

  1. In my exp. posting $.ajax messages to PHP evaluating $_POST like that requires you to JSON.stringify. I'll typically set dataType = 'text' in this case, and then things start working. But the above post actually claims you don't have to do that. But I've switched things back and forth a number of times until I could get it to resolve. (I even had cases where things were double escaped. Bug in PHP 5.2.8 as I recall).

  2. You could switch to dataType = 'json', but on the PHP side use file_get_contents('php://input'). That will accept a raw post of application/json (content type).

    $.ajax({
        type: "POST",
        url: 'yourserviceorscript.php',
        contentType: 'application/json; charset=utf-8', // (optional) text/plain; charset=utf-8
        dataType: 'json', // or text
        async: true, // or false
        data: JSON.stringify(data_obj), // obj gets urlencoded
        cache: false,
        success: function(obj) {},
        error: function(xhr, desc, exeptionobj){}
    });
    

What I've noticed is if you don't set the contentType properly it uses the default of 'application/x-www-form-urlencoded; charset=UTF-8' too.

Bottom line though, regardless of what I've seen people use in examples - when they put a raw object vs data: JSON.stringify(data_object), I have not been able to get it to work. PHP side states the original post without stringify looks like "data%5Baction%5D=Server_Checkup", and doesn't resolve. It gets url encoded unless you stringify. See also - How can I use JQuery to post JSON data?

There are a lot of posts on this subject.

Community
  • 1
  • 1
Mark
  • 2,429
  • 20
  • 20