0

I need to create an ajax processing file, where this javascript is to send the variable myGroupId to, then send it back to my edit.php file where I can then run a query off of the returned file.

I am not experienced with ajax, so I need to know how the processing file should look regarding the javascript variable being converted to a php variable. I know I need to create another folder to send the javascript variable.

I just need to know how to do the ajax processing file (or whatever you want to call it).

Here is my javascript:

 <script type="application/javascript">
    $(document).on("click", ".open-EditRow", function () {
    var myGroupId = $(this).data('id');
    $(".modal-body #groupId").val( myGroupId );

    // ajax call
    var url = "?groupId=" + encodeURIComponent(myGroupId);
    $.get(url, function(data){
    // do something here
    });
      });
  </script>

I'll call the separate file ajaxProcessing.php. Now if someone could show me how that file should look to convert myGroupId to a php variable, I would be grateful.

When it is sent back to my edit.php file, I should be able to reference it as $_GET['groupId'].

Thank you in advance.

HoodCoderMan
  • 103
  • 7
  • 26

1 Answers1

0

Adapted from the jQuery documentation (http://api.jquery.com/jQuery.get/):

$.get(url, {GroupID: myGroupId})
.done(function(data) {
  alert("Data Loaded: " + data);
});

However, if you're passing data to be processed by this script, you should really be using POST:

$.post(url, {GroupID: myGroupId})
    .done(function(data) {
      alert("Data Loaded: " + data);
    });

At any rate, you could get the resulting variable on your ajax processing file by using $variable = $_GET['GroupID']; (or $_POST['GroupID'])

NOTE: To prevent SQL Injection, you must sanitize your $variable, either through mysqli_real_escape string or uses prepared mysqli statements More specifically, don't create a query like "Select * FROM table_name WHERE GroupID= $variable" (I know my syntax is incorrect here, but you get the idea).

Also, make sure you're using mysqli or PDO - mysql is deprecated.

JRizz
  • 226
  • 3
  • 12
  • So I added that code to my javascript. But now what? When I click the button, it spits out the alert window, and in the alert, it shows all the html from edit.php. What am I doing wrong? – HoodCoderMan Aug 15 '13 at 13:32
  • I actually had a similar question to that one (http://stackoverflow.com/questions/17973386/ajax-request-callback-using-jquery). Basically, anything your ajax processing script outputs (html, php echo statements, etc) gets passed back to your .get() (or .post() )function. A common solution is to have one script dedicated to receiving the AJAX call and returning data, with no HTML being output - i.e. that script echo's ONLY the data you want your AJAX function to receive. Without knowing more about the context of your overall structure it's hard to say if that's a feasible option for you. – JRizz Aug 15 '13 at 13:36