PHP to JavaScript via Submit Button

179 views Asked by At

I am working on an app for personal dev and have ran into some trouble. Fairly new to php and javascript so help is appreciated.

It's a simple form with an input and sumbit button. Once the user inputs an ISBN number and clicks search, a div should appear below showing a Google Books results containing title, author and description.

The way I am approaching this is to use the contents of var $isbn in my javascript. This could be the complete wrong way to do it, which is why I'm here. Basically I want to use the inputted ISBN number and 'attach' this to the end of the Google Books search (see below);

var url='https://www.googleapis.com/books/v1/volumes?q='[USER ISBN INPUT HERE];

If I manually set the var $isbn to '0276427343' - I do receive book results and see the div contents successfully. Just not when they are posted by the form to var $isbn.

I will show my code as is now;

HTML Form

<form name="form" method="post" action="">               
<input name="isbn_search" id="isbn_search" type="text">                
<button id="submit" name="submit">search</button>      
</form>

PHP

if(isset($_POST['isbn_search'])){ 
$isbn = $_POST['isbn_search'];
}

JaveScript

$(document).ready(function() {
var isbn = <?php echo $isbn; ?>;
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$('#submit').click(function() {
    $.getJSON(url,function(data){
        $('.result').empty();
        $.each(data.items, function(entryIndex, entry){
            var html = '<div class="results well">';                    
            //html += '<h3>' + entry.id + '</h3>';
            html += '<h3>' + entry.volumeInfo.title + '</h3>';                  
            html += '<div class="author">' + entry.volumeInfo.authors + '</div>'; 
            html += '<div class="description">' + entry.volumeInfo.description + '</div>';  
            $('.result').append(html);
        });                        
    });
    return false;
    });
});

Any help and/or suggestions are welcome.

5

There are 5 answers

1
Mimouni On BEST ANSWER

I think in this case you don't need to use PHP.

but simply try this :

<div>               
   <input id="isbn_search" type="text">                
   <button onclick="do_search();" id="submit" name="submit">search</button>      
</div>
<div class="result"></div>


<script>
function dosearch(){

var isbn = document.getElementById('isbn_search').value; //$('#isbn_search').val(); : if you like jquery :D
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;

$.getJSON(url,function(data){
        $('.result').empty();
        $.each(data.items, function(entryIndex, entry){
            var html = '<div class="results well">';                    
            //html += '<h3>' + entry.id + '</h3>';
            html += '<h3>' + entry.volumeInfo.title + '</h3>';                  
            html += '<div class="author">' + entry.volumeInfo.authors + '</div>'; 
            html += '<div class="description">' + entry.volumeInfo.description + '</div>';  
            $('.result').append(html);
        });  

        //here we send this query to database (thanks to AJAX):
        //=====================================================
        $.ajax({
             type: 'POST',
             url: './db_insert.php',
             data: {'isbn' : isbn },
        });                      
    });

}
</script>

if you want to save the search in a database,

we create a php file : db_insert.php

<?php

// first : init access to data base :
//====================================
$user="root";   //user of database
$pass="";       //password of database
$db="test";     //name of database
$host = "localhost";   //host name

$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, $pdo_options);
$bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$bdd->query("SET NAMES 'utf8'");



//second : insert in a table named "all_search" in this case :
===============================================================
    $req = $bdd->prepare('INSERT INTO all_search(isbn, date_in) VALUES(:isbn, :date_in)');
    $req->execute(array(
        'isbn'      => $_POST['isbn'],
        'date_in'   => date('Y-m-d H:i:s')
    ));


//emm... I think thats all, Enjoy :D

?>
3
Steve On

Your problem is because the form never submits (you stop it with your javascript).

However php is unnecessary for this, you can just extract the value with js:

$(document).ready(function() {

    $('#submit').click(function(ev) {
        ev.preventDefault();
        var isbn = $('#isbn_search').val(); //get isbn direct from input, no need for php
        var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
        $.getJSON(url,function(data){
            $('.result').empty();
            $.each(data.items, function(entryIndex, entry){
                var html = '<div class="results well">';                    
                //html += '<h3>' + entry.id + '</h3>';
                html += '<h3>' + entry.volumeInfo.title + '</h3>';                  
                html += '<div class="author">' + entry.volumeInfo.authors + '</div>'; 
                html += '<div class="description">' + entry.volumeInfo.description + '</div>';  
                $('.result').append(html);
            });                        
        });
    });
});
0
shyammakwana.me On

it's because you are trying to get ISBN entered by user into $_POST. Where your JS is based on button click. So you can't get isbn field value by this way.

Change your JS to below.

var isbn = $('#isbn_search').val();

PHP code is not needed.

if($_POST....
1
Cooper On

I'm not sure if I understand you correct but you can return the ISBN number from PHP with json and then use it in your JavaScript.

<?php
$isbn = $_POST['isbn'];
json_encode($isbn);

?>
0
Max Bumaye On

You should try to understand the basic concepts of javascript and php before you implement them like this.

It looks like what you want to achieve is sending an ISBN provided by a client to the server.

The client runs Javascript (interpreted by the browser) - the server runs php(interpreted by the server when requested)

A basic classical concept: split your HTML CSS JAVASCRIPT (HTML5) to your client and let it do all client stuff get your PHP to do all the server stuff.

You can send information to your PHP server script in different ways now - via ajax or with the submitting the form with a defined action attribute

I hope this helps - you dont need help with the code first of all - spend some (2-3) hours understanding the concepts - then come back and try to get your code right :)

I hope this helps