1

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do... I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.

My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.

I'm not sure if I need to add

<input type="hidden" name="team_id" value="<?=$team->id ?>">

or

<tr data-teamid="<?=$team->id; ?>">

or something like that to my form....but either way, it gets passed through this AJAX file...

<script type="text/javascript">
     function updateNames() {
       jQuery('#form-message, #form-errors').html("");
       var post_data = jQuery('form[name="update_names"]').serialize();
       $.ajax({
         url: 'parsers/update_names.php',
         method: 'POST',
         data : post_data,
         success: function(resp) {
          if(resp == 'success'){
            jQuery('#form-message').html("Names and Scores have been Updated!");
           }else{
             jQuery('#form-errors').html(resp);
           }
         }
       });
       return false; // <--- important, prevents the link's href (hash in this example) from executing.
     }
     jQuery(document).ready(function() {
       $(".linkToClick").click(updateNames);
     });
   </script>

And is making it to my parser file, which looks like this...

require_once '../core/init.php';
 $db = DB::getInstance();
 $errors = [];

 // $camp_id = Input::get('camp_id');
 $camp_id = 18;
 //Find the Teams that Belong to the Camp
 $sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
 $teamsQ = $db->query($sql);
 $all_teams = $teamsQ->results();

//validation and sanitization removed for simplicity.

if(empty($errors)){
  $fields = [];
  foreach($_POST as $k => $v){
    if($k != 'camp_id'){
      $fields[$k] = Input::get($k);
    }
  }

   $db->update('teams',$all_teams->id,$fields);
   echo 'success';
}else{
  echo display_errors($errors);
}

SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?

A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?

So, how would I get that camp_id to

 $sql = "SELECT * FROM teams WHERE camp_id = $camp_id";

And the team_id to

   $db->update('teams',$all_teams->id,$fields);

I tried to break this down to the simplest form and it's still not getting to the function. This code...

<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>

<script type="text/javascript">
     function updateNames() {
  alert('test');
     }
</script>

Gives me... Uncaught ReferenceError: updateNames is not defined

Dan Hoover
  • 235
  • 1
  • 14
  • 1
    The hidden input is the easiest way, that way it gets passed with the form together with all the other values. What exactly is the problem when you do it like that? – jeroen Jan 02 '16 at 21:20
  • I just don't know how to get that information in the parser file and use it. So, if I'm sending team_id via ajax, how do I plug that into my query? – Dan Hoover Jan 02 '16 at 21:25
  • The variables would be part of the `$_POST` array in your PHP. – Jay Blanchard Jan 02 '16 at 21:33
  • I'm guessing the fact that I'm serializing my data that gets sent to the parser file makes that a lot more complicated, because when I var_dump $_POST over in the parser, it's empty, but I know the data is actually making it over there. – Dan Hoover Jan 03 '16 at 00:23
  • Hi Dan, did you solve this problem? Was my answer helpful to finding a solution? If problem persists, please post update -- and a comment under my answer (so I am notified of the update) -- and we'll continue to brainstorm with you. – cssyphus Jan 03 '16 at 14:54

1 Answers1

0

The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():

<input type="hidden" name="team_id" value="<?=$team->id ?>">

Looking at your ajax code, your parser file would be called parsers/update_names.php.

To verify that the desired field is getting to your parser file, add this to the top for a temporary test:

<?php
  $tid = $_POST['team_id'];
  echo 'Returning: ' .$tid;
  die();

and temporarily modify the ajax code block to:

$.ajax({
    url: 'parsers/update_names.php',
    method: 'POST',
    data : post_data,
    success: function(resp) {
        alert(resp);
    {
});
return false;

If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.

Thus, you can now determine:

1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working

Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • I'm still working on it. I guess my last comment didn't post for some reason. I'm getting some weird results. I'll keep you posted. Thanks so much for taking the time to answer. It means a lot. – Dan Hoover Jan 03 '16 at 20:46
  • Sorry it took me so long to get back to you...I got so frustrated after spending 4 days fighting with AJAX I needed to take a break so I didn't meltdown :) I implemented your changes and I don't see any alert message in my code when I click the update button – Dan Hoover Jan 04 '16 at 16:40
  • Aha! A key clue. In the success function, it will fire the `alert()` regardless of what the alert will contain. It might have the team_id, it might be blank - both clues - but it WILL fire. If it doesn't fire, your javascript code is broken. So you need to find out where. A few ideas: (1) Use Chrome's DevTools (F12) console page and see what errors are revealed. (2) Put another `alert('test');` at the top of your js and delete everything else to see the alert. Then begin adding back blocks of code until it breaks - your js error will be in that block of code. Find that error..! – cssyphus Jan 04 '16 at 17:17
  • Thank you! I'm going to strip everything else out of my form and do a really simple form and try to minimize the possibilities of overlooking something! – Dan Hoover Jan 05 '16 at 02:01
  • I'm totally lost. I've hacked my code up so much trying to figure out what's up. I pasted my latest try (keeping the JS on the same page and I'm still not getting an alert. – Dan Hoover Jan 05 '16 at 02:21
  • What I would do now is to simplify -- and go for a few immediate wins. Take the simple examples listed in the bottom of [**this answer**](http://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery/17974843#17974843) (that's a link) and create exactly those examples on your system. The 20 mins you spend duplicating them and making them work will save you HOURS of troubleshooting your own project. (Remember to upvote any answers that you find helpful - that's how SO works...) Next, simplify your own problem. Start with hardly anything, get it working, build on that til done – cssyphus Jan 05 '16 at 02:34
  • Also, as part of simplifying, don't use `serialize`. Manually code getting the values of each form field, e.g.: `var nm = $('#name').val();`. It might be easier for you to add IDs for ease of coding: `$('#team_id')` instead of `$('[name=team_id]')` - so ``. I've been AJAXing for years and I still avoid serialize myself. – cssyphus Jan 05 '16 at 02:44
  • Awesome. I can't thank you enough for taking the time to show me this stuff. I'll start on that right now. – Dan Hoover Jan 05 '16 at 14:33
  • The two greatest tips I can give you: (1) learn to use F12 (DevTools) in Chrome. On a page, right-click the element and choose `Inspect` is the greatest help to figuring out CSS - you can change it LIVE on the right panel. Also, using `console.log(varName);` is super-useful (easier and less intrusive than `alert(varName)`. (2) Learn and use FirePHP, which is the same thing for the PHP side. Why program blind? Get variable results to print out from your PHP files in real time. – cssyphus Jan 05 '16 at 16:05
  • I'm still working on this. I do appreciate your help. – Dan Hoover Jan 12 '16 at 15:44
  • I wrote [another answer to a different question](http://stackoverflow.com/a/34735490) that might be of help to you. God speed with your project. – cssyphus Jan 12 '16 at 16:09