djt
djt

Reputation: 7535

Get MySQL Record using Php & JQuery

Here's my scenario:

I have a drop down menu, with different values. When option 'A' is chosen, I want it to use JQuery to call a Php script. That Php script will make a database query which returns a record ID. When that record ID is returned to the javascript, javascript will direct the browser to a particular URL based on the returned ID (i.e. /products/$ID)

Right now, I have it so that the dropdown menu triggers a javascript function. I also have the Php script that does the database work. Im just not sure what should go in the javascript function, or how to make it connect with he Php script, and how I get the returned data (and how to deal it with the return type -- xml, html, etc)

Im using JQuery library, and Php 5.x.

Upvotes: 1

Views: 1901

Answers (2)

Dave Kiss
Dave Kiss

Reputation: 10495

$("#menu-item").click(function() {

    jQuery.ajax({
        type: "POST",
        url: "yourScript.php",
        data: "data=foo",
        success: function(response){
            //redirect to id using response
            window.location.replace("http://yoursite.com/products/" + response);
        }
    });

});

Of course, this will need to be customized to your unique situation.

Upvotes: 1

shmeeps
shmeeps

Reputation: 7853

A simple example would be to take a form like

Example.php

<form id="form" name="form">        
    <select name="dropdown" id="dropdown">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>

    <input type="submit" id="submit" name="submit" value="Submit!" />
</form>

Then link it with some JQuery to intercept the form, and send it to a PHP file

JQuery.js

$(document).ready(function(){
    $("#dropdown").change(function(event) {
        $.ajax({
            type: "POST",
            url: "query.php",
            data: $('#form').serialize(),
                datatype: "json",
            success: function(data){
                var ret = jQuery.parseJSON(data);
                    // Redirect to ret.link
            }
    });
    event.preventDefault();
    });
});

Then, create the PHP file to interpret it

query.php

$stmt = $sql->dbh->prepare("SELECT `Link` FROM `Links` WHERE `ID` = :id");

$stmt->bindValue(':id', $_POST['dropdown']);

$stmt->execute();

$link = $stmt->fetch()['Link'];

echo json_encode(array('link' => "{$link}"));

die();

Upvotes: 2

Related Questions