Jump to content

Passing AJAX variables


phppup

Recommended Posts

 

After trolling the internet, I have managed to piece together enough information to accomplish the creation of a working Ajax script which dynamically shows the contents of a table column when a user types inside a text input field.

So, the data from table STATES provides the 'name' field California and the 'abbrev' field CA.

This seems to be accomplished when the first php files connects to the second php file through:

 

$.get("backend.php", {term: inputVal}).done(function(data){

 

Now I want to put the selected information to use.

How can I attach/connect 'name' or 'abbrev' so that these variables are selected in a third file update.php so that CA can be altered to "Cali"

 

The input field displaying this info is name= 'typ' and I've managed to create a JavaScript:

 

function Delta(){

var x = document.getElementById("typ").value;

document.write("You selected <b>" + x + "</b> as your choice.");

 

But this displays the information as a string.

It seems like the long way around to use Java Script to disassemble the string and isolate each variable. And then, of course, I need to pass it to update.php

 

Please help.

Link to comment
Share on other sites

Have you considered modifying the second PHP file so that it returns the desired output? I imagine you could have it return the full state name (California), state code (CA), and whatever abbreviation you want (Cali).

 

 

It seems like the long way around to use Java Script to disassemble the string and isolate each variable. And then, of course, I need to pass it to update.php

 

How is the information being returned to the AJAX script? If you're using JSON, it's fairly easy to isolate the variables.

Link to comment
Share on other sites

In its current form, the script does nothing more than dynamically display information contained in the table. I want to be able to now utilize it.

Knowing that California (as 'state') exists does me no good if I cannot select it to update 'abbrev'.

This is only a template right now.

Simplified plans would replace 'state' with 'customer' and 'abbrev' with 'satisfaction'.

In that case, customer Smith would be selected from Ajax. His satisfaction with our service is a 10. Today, he was disappointed and the 10 needs to be UPDATED to a 3.

Currently, I am unable to satisfy that criteria t through a form because I cannot 'grab' there variable information and retain it for page 3.

Link to comment
Share on other sites

Sorry, I'm confused on what you're trying to do. What does the workflow look like? Is the website already set up so that you know who's record(s) to update? If so, do you have a form that will ask what you need to know (eg. user's satisfaction level)? Is it when the user responds to the form where you are trying to bring in AJAX?

 

Is there a reason you are using AJAX, versus just submitting the form? I'm guessing that the user wouldn't need to change their satisfaction level several times in a sitting.

Link to comment
Share on other sites

The AJAX that I've got is end result of several suggestions and resources.

The full story and it's reality for an end result may untangle the confusion.

I have a form for customer information that inputs data into a table. That works fine.

This customer information corresponds to other related data (ie. last sale, amount, etc.) through a non-disclosed index number.

Since there is a likelihood that a 'first name' and 'lastname' may be duplicated (more than one John Smith), it is imperative that the correct record be updated.

Enter AJAX, which enables user to enter keystrokes that narrow the field of John Smith's dynamically.

The Smithers, Smithsons, and Smithers have been visually eliminated from the dropdown-style display.

Now, there are three John Smith choices.

In addition to 'firstname' and 'lastname' is 'phone'. This can be used to validate that from the choices, the correct John Smith is selected (with the associated [hidden] index.

Great up to here.

The table is populated, the data is dynamically visible.

John Smith with'phone' 5551224 is selected.

And then, NOTHING HAPPENS.

I need to carry the 'phone' or the index to the next phase in order to update his girlfriend's name or add today's sale data.

This is where I've stalled.

Link to comment
Share on other sites

The option values in your dropdown should already be the ids of the customers and that is what gets posted when the form is submitted

EG

<select name='customer' id='customer'>
    <option value='123'>John Smith, 5551224</option>
    <option value='234'>John Smith, 5551234</option>
    <option value='345'>John Smith, 5557890</option>
</select>

On the next page, the required id will be in $_POST['customer']

Link to comment
Share on other sites

Please re-read my initial entry.

The dropdown-style is created with AJAX pulling data from the columns in distint rows (whether 'name' and 'phone' or 'state' and 'abbrev').

 

I created the following as a way to see it.

function Delta(){

var x = document.getElementById("typ").value;

document.write("You selected <b>" + x + "</b> as your choice.");

 

In what manner would I use you suggestion as an alternative??

Link to comment
Share on other sites

I had something like this in mind

 

sample_ajax.php

<?php
include 'db_inc.php';
$db = pdoConnect('test');      // connects to "test" database

// AJAX PROCESSING BIT
if (isset($_GET['custname']) && trim($_GET['custname']) != '') {
    $stmt = $db->prepare("SELECT customer_id
                             , fname
                             , lname
                             , phone
                          FROM customer
                          WHERE lname LIKE ?
                          ORDER BY lname, fname, phone");
    $stmt->execute( [ $_GET['custname'] . '%' ] );
    $opts = '';
    foreach ($stmt as $r) {
        $opts .= "<option value='{$r['customer_id']}'>{$r['fname']} {$r['lname']}, {$r['phone']}</option>\n";
    }
    exit($opts); // return the options as the AJAX response          
}

// report the selected customer
if (isset($_POST['customer'])) {
    echo "You selected customer #{$_POST['customer']}<br><hr>";
} 
?>
<html>
<head>
<meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)">
<title>Sample AJAX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">

    $().ready( function() {
        
        $("#custname").keyup( function() {
            $.get(
                "sample_ajax.php",
                { "custname" : $(this).val() },
                function(resp) {
                    $("#customer").html(resp);
                },
                "TEXT"
            )
        })
        
        $("#customer").change( function() {
            $("#fm1").submit();
        })
         
    })
</script>
</head>
<body>
<form id='fm1' action="" method='post'>
    Enter last name<input type="text" name="custname" id="custname" size="20">
    <br><br>
    <select name='customer' id='customer' size=10 >
          <!-- ajax response text goes here -->
    </select>
    <br><br>
</form>
</body>
</html>
Link to comment
Share on other sites

This looks similar to what I've got: another AJAX developed menu.

So, back to my question: after I make a selection, how does I carry the values and UPDATE the record?

EG: I select John Smith with tele 5554321 and need to change his girlfriend's name from Mary to Wanda.

I need to be able to UPDATE the correct corresponding record.

Link to comment
Share on other sites

In my code above, the $_POST['customer'] variable contains the id of the customer record to be updated. Not rocket science.

if (isset($_POST['customer'])) {
    $stmt = $db->prepare("UPDATE customer SET girlfriend = ? WHERE customer_id = ?");
    $stmt->execute( [ 'Wanda',
                       $_POST['customer']
                    ]);
}
Link to comment
Share on other sites

After several attempts of adjusting this code and creating database tables, it appears not to work and has failed.

 

Perhaps I should rephrase: hope do I use the selected item from an AJAX generated search so that the specific record can be updated in its table?

 

Any helpful info, links, examples would be appreciated.

Link to comment
Share on other sites

For code that does not work, the attempt is appreciated, but not as much as a reply that resolves my issue.

 

Your code did not work. Nor did it address the problem ( (as no update option was included.

 

AJAX seems like a nice way to view data in my table. But I need a way to utilize it. Is there a way to Cchoose aspecified record and UPDATE it?

Link to comment
Share on other sites

We can not help you if you aren't able to debug your own code.

 

With javascript/ajax as the UI this includes using the browser developer tools to look at the network traffic, and the Request/Response data.

 

On the PHP side, at simplest, using echo, var_dump/print_var are helpful. There are also logging tools that once wired in are very helpful. Monolog is one of the best known PHP logging libraries and is used in many frameworks and projects.

 

There is also a Chrome tool that will let you write log messages from your PHP script and have them appear in the Chrome console: https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef

 

There is the well known xdebug extension which can be configured with many editors and IDE's to add an actual traditional breakpoint/step/inspection debugger to your backend code, as well as the browser tools to see what is actually happening with your Ajax responses.

 

I also want to suggest that things may be cleaner if you return json from your php rather than markup.

 

Use javascript routines to transform the data into the markup you want. This provides a separation of concerns, and intrinsically gets around the problem you described of having to parse the data the PHP script provides.

Link to comment
Share on other sites

Here's the code straight off the server (sorry, don't know how to encapsulate it).

The code is not populating data, and offers no method for 'attaching" the the selected record for UPDATE (which was my initially issue) after dynamically searching the table.

<?php
//include 'db_inc.php';



 $db = mysqli_connect("localhost", "MY_INFO", "MY_INFO", "MY_INFO");




//$db = pdoConnect>>>> REMOVED




// AJAX PROCESSING BIT
if (isset($_GET['custname']) && trim($_GET['custname']) != '') {
    $stmt = $db->prepare("SELECT customer_id
                             , fname
                             , lname
                             , phone
                          FROM customer
                          WHERE lname LIKE ?
                          ORDER BY lname, fname, phone");
    $stmt->execute( [ $_GET['custname'] . '%' ] );
    $opts = '';
    foreach ($stmt as $r) {
        $opts .= "<option value='{$r['customer_id']}'>{$r['fname']} {$r['lname']}, {$r['phone']}</option>\n";
    }
    exit($opts); // return the options as the AJAX response          
}

// report the selected customer
if (isset($_POST['customer'])) {
    echo "You selected customer #{$_POST['customer']}<br><hr>";
}
?>
<html>
<head>
<meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)">
<title>Sample AJAX</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">

    $().ready( function() {
        
        $("#custname").keyup( function() {
            $.get(
                "sample_ajax.php",
                { "custname" : $(this).val() },
                function(resp) {
                    $("#customer").html(resp);
                },
                "TEXT"
            )
        })
        
        $("#customer").change( function() {
            $("#fm1").submit();
        })
         
    })
</script>
</head>
<body>
<form id='fm1' action="" method='post'>
    Enter last name<input type="text" name="custname" id="custname" size="20">
    <br><br>
    <select name='customer' id='customer' size=10 >
          <!-- ajax response text goes here -->
    </select>
    <br><br>
</form>
</body>
</html>
Edited by Barand
code tags
Link to comment
Share on other sites

You use the <> button in the toolbar for your  code.

 

What is the structure of your customer table?

 

EDIT: As was evident by my pdoConnect() function, the processing code uses pdo methods. You can't just switch to a mysqli connection and use the same code.

Edited by Barand
Link to comment
Share on other sites

OK.  Of course, I wouldn't have changed it if I knew where to place the information for the PDO connection.

So, let me ask, "where do I put the information so that the PDO-devoted code will connect?

 

And, assuming it does eventually connect, I will be back to my initial question: How do I update the selected record?????

Link to comment
Share on other sites

How do I update the selected record?????

 

Like I already showed you

 

 

In my code above, the $_POST['customer'] variable contains the id of the customer record to be updated. Not rocket science.

if (isset($_POST['customer'])) {
    $stmt = $db->prepare("UPDATE customer SET girlfriend = ? WHERE customer_id = ?");
    $stmt->execute( [ 'Wanda',
                       $_POST['customer']
                    ]);
}
Link to comment
Share on other sites

Would you believe that I was unsure of exactly how to make the PDO connection and that the reason I changed to a 'more comfortable' connection was because I could not get the PDO to work?

 

Or do you think that I changed it just to elicit more problems as a means to continue this fascinating dialogue??

Link to comment
Share on other sites

Here is the PDO connection code

$host = '****';
$username = '****';
$password = '****';
$database = '****';

    $dsn = "mysql:dbname=$database; host=$host; charset=utf8";

    $db = new pdo($dsn, $username, $password, 
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);

Of course you need to make sure the column names in the queries actually exist in your table. Without any information I had to guess at those.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.