4

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.

When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.

How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.

<script>
function setService() 
{   // The customer's "id" grabbed from the aforementioned customer selection list
    customer = $('#customer').val();
    $.get('thePage.php?key=setService?customer='+customer);
}
</script>

This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.

<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
    $customer = $_GET['customer'];
    $customer = intval($customer);
    $s = CustomerProvider::getHasContract($customer);
    if ($s != '')
       { ?> <script>var element = document.getElementById('ticket_service');
          element.value = 'Contracted Hours';</script> <? }
    else return;
} 
?>

I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.

1
  • The basic problem here is that you are throwing away the result from $.get instead of applying it to your page. Move the code from the server output into a callback in JavaScript that makes the element changes. Commented Jun 1, 2016 at 19:53

4 Answers 4

4

You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:

<script>
  function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
    customer = $('#customer').val();
    $.get('thePage.php?key=setService?customer=' + customer, function(data) {
      console.log(data + ' was returned from your php script!');
      if(data.hasContract=='1')
          $('#ticket_service').val('Contracted Hours');
      else
          $('#ticket_service').val('No Contracted Hours');
    });
  }
</script>

And then your PHP script will just look like this:

<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
    $customer = $_GET['customer'];
    $customer = intval($customer);
    $s = CustomerProvider::getHasContract($customer);
    if ($s != ''){
        $hasContract = 1;
    }
    else 
        $hasContract = 0;

    echo json_encode(array('hasContract' => $hasContract));
} 
?>

Therefore returning only the data needed for the client app to continue... not application logic

Sign up to request clarification or add additional context in comments.

4 Comments

Your PHP needs an echo. ;)
I understand the logic and the application of what you're doing here, however it doesn't seem to be actually returning any data. I copy+pasted what you gave me and tweaked it to actually reflect what I needed to get and in my dev log I'm getting " was returned from your php script!" Not sure what I'm fouling up here.
I had a huge head scratcher for a bit, but you have to parse the JSON data that is returned, or else you're going to get an error saying the object is empty. a simple "JSON.parse(data)" in your javascript worked perfectly. Other than that, thanks for your help. It's nice when someone steers you in the right direction.
@dmcoding np. I didn't actually test that script so let me know if anything else is weird ;) You shouldn't have to parse the json in your Javascript. It sounds like your content headers should be set in PHP... so add this to the very top of your PHP file to denote the response header being JSON: header('Content-Type: application/json');
0

Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.

$("#someelement").load('thePage.php?key=setService?customer='+customer);

This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.

If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.

Comments

0

The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:

Request the test.php page, but ignore the return results.

$.get( "test.php" );

Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.

PHP

<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
    $customer = $_GET['customer'];
    $customer = intval($customer);
    $s = CustomerProvider::getHasContract($customer);

    // Default output
    $output = array('hasContract' => false);

    // Customer has contract
    if ($s != '')
        $output['hasContract'] = true;

    echo json_encode($output)

    // Alternative: PHP just returns getHasContract, JS determines action
    // (this would replace $ouput, conditional, and echo)
    // echo json_encode(array("hasContract" => $s));
} 
?>

JavaScript

function setService() 
{   // The customer's "id" grabbed from the aforementioned customer selection list
    customer = $('#customer').val();
    $.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
        // Alternative
        // if (result.hasContract != "")
        if (result.hasContract)
        {
            var element = document.getElementById('ticket_service');
            element.value = 'Contracted Hours';
        }
    });
}

Comments

0

As others wrote, your code doesn't do a thing with the GET variables. the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery. since I'm against GET and pro POST which is safer method, here's an example with POST:

JS:

function postSomthing(customerID){
       $.post(
        'thePage.php',
        {key:'setService',customer:customerID},
        function(data){ 
         if(data!='x'){
         $('#ticket_service').val(data)
         }
         else{alert('no ticket');/*whatever you want to do*/}
        });
}

PHP(thePage.php) :

if(isset($_POST['key']) && $_POST['key'] == 'setService'){
    $customer = intval($_POST['customer']);
    $s = CustomerProvider::getHasContract($customer);
    if ($s != ''){echo 'x';/* false, or whatever you want*/}
    else{echo 'Contracted Hours';}
} 

notes:

  • you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

1 Comment

The element with the id "ticket_service" is on the viewed page. The javascript portion that calls my php comes after my elements are displayed. I named thePage.php as I did just to cut down on confusion. Its name is just filler and has no bearing on the order of how things load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.