PHP to JavaScript via Submit Button - javascript

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.

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);
});
});
});
});

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
?>

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

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....

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);
?>

Related

Best way to integrate php and Javascript

I have a .php file where I have some script running to display "cards". I have 6 cards showing and the text being displayed is hard coded. I am ready to start pulling from my database and remove my hard code sections.
//Set number of cards to show
multiplyNode(document.querySelector('.card_content'), 6, true);
var authors = ["Margaret", "Lucy", "Odessa", "Shifty", "Saggy", "Lady"];
var BookNumbers = [2563, 8547, 5896, 4157, 5823, 7963];
$(function(){box_title
//$(".card_content").clone(true).appendTo(".main_card_shell");
$('.box_title').each(function (i) {
$(this).html("<div class='card_name'>" + authors[i] + "</div>" +
"<div class='card_number'>" + BookNumbers[i] + "</div>" +
"<div class='tag_row'>" +
"<div class='sample_tag sample_tag4'></div>" +
"<div class='sample_tag sample_tag3'></div>" +
"</div>");
});
})
I know I can pull the data I want from my database via:
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
but how is the best way to get my $result to replace my hard coded authors and BookNumbers array?
You can loop through the results to build a php array with the same structure as your javascript arrays, then use json_encode to convert it to a javascript array format.
<script type='text/javascript'>
<?php
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
// loop through the results to build the php arrays
while($row = $result->fetch_array())
{
// set the author and book number to array with numeric key
$authors[] = $row['Author'];
$BookNumbers[] = $row['Book_Num'];
}
// use json_encode to convert the php array to an javascript array
echo "var authors = ".json_encode($authors).";\n";
echo "var BookNumbers = ".json_encode($BookNumbers).";\n";
?>
</script>
A comment: unless you need interactivity you could build the html with php without using jquery

Trying to set up mailto: link

I have a webpage that has a form to insert vendor data, once inserted the company name is the placed into a select box. when the company is selected a table is called with all the vendor information.
My problem is the
the vendor_email is called from a php script, is there a way to make the value of the id insert into a mailto: function.
<tbody id="records">
<td id="vendor_company"></td>
<td id="vendor_rep"></td>
<td id="vendor_email"></td>
</tbody>
<div class="row" id="no_records"><div class="col-sm-4">Plese select vendor name to view details</div></div>
here is my php and js code
<?php
include_once("Database/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, companyName, repName, venderEmail FROM vender_contact
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
my js code
$(document).ready(function(){
// code to get all records from table via select box
$("#vendors_data").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url:"getVendor.php",
dataType: "json",
data: dataString,
cache: false,
success: function(vendorData) {
if(vendorData) {
$("#heading").show();
$("#no_records").hide();
$("#vendor_company").text(vendorData.companyName);
$("#vendor_rep").text(vendorData.repName);
$("#vendor_email").text(vendorData.venderEmail);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
It's absolutely possible! You simply need to use .html() instead of .text().
Note that the mailto comes on the href attribute, which is unique to the <a> tag. As such, you'll want to place your inside of your <td id="vendor_email"></td>:
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
Which will render as something like:
vendorData = {};
vendorData.vendorEmail = 'test#test.com';
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vendor_email"></div>
In addition to this, please be aware that your MySQLi is vulnerable to SQL injection. You should use prepared statements, and also ensure that your database user only has the required privileges in order to prevent this.
You can refer to this post for further information on how to prevent SQL injection in PHP :)
Hope this helps!
By using jQuery's .html() method you can insert html like so:
$( '#vendor_email' ).html( '' + vendorData.vendorEmail + '' );
By the way, I couldn't help but notice that you've spelled vendor as "vender" in venderEmail.

How to get translated names from database using ajax in laravel?

I am creating tag's input where somebody can write tag. In both languages of course. But the problem is that I can't translate them. I do not know how to do it. Can you help me? Here's my code:
JS:
suggestion: function(data) {
return '<li class="list-group-item">' + "#lang('" + "main." + data.name + "')" + '</li>'
}
Route:
Route::group(['prefix'=>'api','middleware' => 'auth'], function(){
Route::get('find', function(Illuminate\Http\Request $request){
$keyword = $request->input('keyword');
Log::info($keyword);
$positions = DB::table('positions')->where('name','like','%'.$keyword.'%')
->select('positions.id','positions.name','positions.display')
->get();
return json_encode($positions);
})->name('api.positions');
});
The easiest way to do that is by having multiple column in your datase :
• name_en
• name_fr
• name_es
and then
check your targeted local :
$local = 'en';
$positions = DB::table('positions')->where('name_'.
$local,'like','%'.$keyword.'%')
->select('positions.id','positions.name_' . $local .' as
name' ,'positions.display')
->get();

Expressing php code in Javascript

I am trying to insert html code through a php variable in javascript. I am getting the following error below. Please can someone advise?
Error Message: "Unexpected Identifier 'Inactive'" ($option has values 'Inactive'/ 'Active')
PHP
$tr_active_Options = '';
$sql1 = "SELECT status FROM tr_active";
$result = $mysqli -> query($sql1);
while($row = $result -> fetch_assoc()){
$option = $row['status'];
$option = '<div class="dpOtions" onclick="track.addChosenOption(\''.$option.'\', \'act_ui\')">'.$option.'</div>';
$tr_active_Options .= $option;
}
$tr_active = '<div class="drpClass"><div class="dropOptionsDiv" id="actList_ui">'.$tr_active_Options.'</div></div>';
JAVASCRIPT
document.getElementById('anchor').innerHTML = '<div id="editWrap"><?php echo $tr_active; ?></div>';
The ' in your string are terminating the JavaScript string you've started with '.
You can safely have PHP generate a string for use in JavaScript using json_encode, like so:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
<?php echo json_encode($tr_active); ?> +
'</div>';
Note how the JavaScript string ends, then we use + to join it with the one that PHP will output (json_encode will handle the strings), then we + it with another JavaScript string after it. What the browser will see will look like this:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
"contents of $tr_active here" +
'</div>';
...which is valid.
That said: Using PHP to generate HTML with embedded JavaScript inside attributes is asking for a world of hurt. Separate those concerns! :-)

how to pass xml data on button click to some other page using jquery

am getting data from data.xml on button click, which i want to disaply on some other page on same button click. It means, on button click i should navigate to some other page and display data.please note that am not using
jquery Mobile.
$('#findPO').click(function() {
$.get('data.xml',function(data){
/* window.location.href = 'Search_Result.html'; */
$('#resultContainer').empty();
$(data).find('project').each(function(){
var $project = $(this);
var html = '<div class="data">';
html += '<h3>' + $project.attr('company') + '</h3>';
html += '<div class="product">' + $project.find('product').text() + '</div>';
html += '<div class="type">' + $project.find('type').text() + '</div>';
html += '<div class="members">' + $project.find('members').text() + '</div>';
$('#resultContainer').append(html);
});
});
return false;
});
I have to use only javascript or jquery html and css.
On button click, create the html you wish to send to the other page (as a string) and stick it into a variable. Then, create a form with an input field with, for example, name="input_to_send" and stick the HTML (string var) into that field:
$('#input_to_send').val(strHTML2Send);
Then, use jQuery's .submit() method to submit the form to the destination page.
The form's action="somepage.php" attribute will, of course, contain the name of the destination page, and also method="POST".
So, the $.get() routine would look like this:
$.get('data.xml',function(data){
/* window.location.href = 'Search_Result.html'; */
$('#resultContainer').empty();
$(data).find('project').each(function(){
var $project = $(this);
var html = '<div class="data">';
html += '<h3>' + $project.attr('company') + '</h3>';
html += '<div class="product">' + $project.find('product').text() + '</div>';
html += '<div class="type">' + $project.find('type').text() + '</div>';
html += '<div class="members">' + $project.find('members').text() + '</div>';
$('#resultContainer').append(html);
var myForm = '<form id="form2send" action="other_php_file.php" method="POST">';
myForm += '<input name="input_to_send" type="hidden" value="' +html+ '" /></form>';
$('#some_spare_empty_div').html(myForm);
$('#form2send').submit();
});
});
On the receiving end, you will receive the html you sent like this:
<?php
$h = $_POST['input_to_send'];
echo '<div id="put_it_here">';
echo $h;
echo '</div>';
Do you need a larger code example? Judging from the code in your question above, I don't think you do.

Categories