简体   繁体   English

通过提交按钮将PHP转换为JavaScript

[英]PHP to JavaScript via Submit Button

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. php和javascript的新手,因此非常感谢您的帮助。

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. 用户输入ISBN号并单击搜索后,div应当显示在下面,显示包含标题,作者和描述的Google图书结果。

The way I am approaching this is to use the contents of var $isbn in my javascript. 我要解决的方法是在javascript中使用var $isbn的内容。 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); 基本上,我想使用输入的ISBN号,并将其“附加”到Google图书搜索的末尾(请参见下文);

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. 如果我将var $ isbn手动设置为'0276427343'-我会收到书本结果并成功查看div的内容。 Just not when they are posted by the form to var $isbn. 只是不是通过表单将它们发布到var $ isbn时。

I will show my code as is now; 我将按原样显示我的代码;

HTML Form HTML表格

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

PHP 的PHP

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

JaveScript 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. 欢迎任何帮助和/或建议。

Your problem is because the form never submits (you stop it with your javascript). 您的问题是因为表单从未提交(您使用JavaScript停止了表单)。

However php is unnecessary for this, you can just extract the value with js: 但是php不需要这样做,您可以使用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);
            });                        
        });
    });
});

You should try to understand the basic concepts of javascript and php before you implement them like this. 在实施这样的方法之前,您应该尝试了解javascript和php的基本概念。

It looks like what you want to achieve is sending an ISBN provided by a client to the server. 您似乎想要实现的是将客户端提供的ISBN发送到服务器。

The client runs Javascript (interpreted by the browser) - the server runs php(interpreted by the server when requested) 客户端运行Javascript(由浏览器解释)-服务器运行php(在请求时由服务器解释)

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. 一个基本的经典概念:将HTML CSS JAVASCRIPT(HTML5)拆分到客户端,并让它完成所有客户端工作,让您的PHP完成所有服务器工作。

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 您现在可以通过不同的方式将信息发送到PHP服务器脚本-通过ajax或通过具有定义的action属性的表单提交

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 :) 我希望这会有所帮助-您首先不需要代码方面的帮助-花一些(2-3)个小时来了解这些概念-然后再回来尝试使代码正确:)

I hope this helps 我希望这有帮助

I think in this case you don't need to use PHP. 我认为在这种情况下,您不需要使用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文件: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

?>

it's because you are trying to get ISBN entered by user into $_POST. 这是因为您试图让用户将ISBN输入到$ _POST中。 Where your JS is based on button click. 您的JS基于单击按钮的位置。 So you can't get isbn field value by this way. 因此,您无法通过这种方式获得isbn字段值。

Change your JS to below. 将您的JS更改为以下内容。

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

PHP code is not needed. 不需要PHP代码。

if($_POST....

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. 我不确定我是否理解正确,但是您可以使用json从PHP返回ISBN号,然后在JavaScript中使用它。

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM