How to insert php script inside jquery? - javascript

I have this jquery sample, just wondering how to insert php (e.g. /a href="/?php echo $sample['SAMPLE\']; ?/"/) in the "var para1" in the below.
var storyIndictor = jQuery(_storyIndictors[position]);
var _content = jQuery("div.jqans-content", container);
var img = jQuery('<img style="float:left;clear:left;"></img>');
var para = jQuery('<div ></div>');
var para1 = jQuery('<h1> </h1>');
var title = jQuery(settings.contentTitle + " a", story).attr('title') || jQuery(settings.contentTitle, story).text();
img.attr('src', jQuery('img', story).attr('longdesc') || jQuery('img', story).attr('src'));
para1.html("<h1>" + title + "</h1>");

You can just echo out a variable
var para1 = jQuery('<h1><?php echo $another_variable; ?></h1>');

var _content = jQuery("div.jqans-content", container);
var img = jQuery('<img style="float:left;clear:left;"></img>');
var para = jQuery('<div ></div>');
var para1 = jQuery('<h1><?php echo $phpvar; ?></h1>');
var title = jQuery(settings.contentTitle + " a", story).attr('title') || jQuery(settings.contentTitle, story).text();
img.attr('src', jQuery('img', story).attr('longdesc') || jQuery('img', story).attr('src'));
para1.html("<h1>" + title + "</h1>");
para.html("<p>" + jQuery(settings.contentDescription, story).html() + "</p>");
You mean like that?

Try this:
var para1 = jQuery('<h1> <?php echo $sample['SaMPLE_SAMPLE']; ?> </h1>');

Its not a good practice to embedded php code in javascript. I have post a way you can try this.
<input type="hidden" id="sample" value="<?php echo $sample['SaMPLE_SAMPLE']; ?>" />
or <div id="sample" data-sample="<?php echo $sample['SaMPLE_SAMPLE']; ?>"></div>
<script>
var sample = $('#sample').val();
//or
var sample = $('#sample').data(); //if you use data atrr
var para1 = $('<h1>' +sample+ '</h1>');
</script>

Simply you can use php inside your js code:-
var varName = '<?php echo $sample['SAMPLE']; ?>';
don't forget to echo. as you missed in your example
so your var para1 will be:-
var para1 = jQuery('<h1><?php echo $sample['SAMPLE']; ?></h1>');

Related

Call PHP function inside JavaScript inside echo

I have read the other similar questions, but not found the answer, so here it is:
<?php
function load($page) {
echo "page: ".$page;
}
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '<?php load(page); ?>'
}
})
</script>
";
?>
The problem is that <?php load(page); ?> is not executed. If I write load(page); outside the echo, it works. Can anyone help me ?
Change the function to return:
function load($page) {
return "page: ".$page;
}
You're executing PHP with the echo so just use the return of load():
echo "
<script type='text/javascript'>
var page = 0;
window.addEventListener(...., function(){
var x = .....
......
if(x = ....)
{
page = page + 1;
var runQuery = '" . load($page) . "'
}
})
</script>
";

Extracting information from database using JSON and AJAX

I'm trying to make a simple "search" box using Javascript, AJAX, php and JSON. For this project, I'm just using the database "world" I downloaded from mqsql website.
I'm running into a problem when trying to extract the information from my database. It just takes the first line of information and then I get this
error: "SCRIPT5007: SCRIPT5007: Unable to get property 'Continent' of undefined or null reference
ajaj.js (65,3)"
Thanks in advance for any help you are able to give me!
Here is my ajaj.js code:
var ajaxRequest=new XMLHttpRequest();
var input;
var button;
function init(){
input = document.getElementById('search');
input.addEventListener("keyup", sendRequest, false);
button = document.getElementById('sendButton');
button.addEventListener("click", sendSecondRequest, false);
}
function sendRequest(){
ajaxRequest.onreadystatechange = getRequest;
var searchTxt = "country=" + input.value;
ajaxRequest.open("GET", "getCountries.php?" + searchTxt, true);
ajaxRequest.send();
}
function getRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
var jsonObj = JSON.parse(ajaxRequest.responseText);
var dataList = document.getElementById('countries');
dataList.innerHTML="";
for(var i = 0; i<jsonObj.length; i++){
var option = document.createElement('option');
option.value = jsonObj[i]['Name'];
dataList.appendChild(option);
}
}
}
function sendSecondRequest(){
ajaxRequest.onreadystatechange = getSecondRequest;
var infoCountry = "country=" + input.value;
ajaxRequest.open("GET", "getCountries2.php?" + infoCountry, true);
ajaxRequest.send();
}
function getSecondRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
alert(ajaxRequest.responseText);
var jsonObj2 = JSON.parse(ajaxRequest.responseText);
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
}
}
window.addEventListener("load",init,false);
It's here where the problem lies, I just don't know how to get it to work:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
I've tried a few different solutions but I can't get it working, I've tried to combine the code into one line using:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>" + "Continent: " + jsonObj2[2]["Continent] + "<br>";
but that doesn't seem to work for me either.
Rest of my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<script type="text/javascript" src="ajaj.js"></script>
</head>
<body>
<h1>Sök information om ett land</h1>
<input type="text" list="countries" id = 'search' placeholder="Land">
<datalist id="countries">
</datalist>
<button type="button" id="sendButton">Hämta information</button>
<p id="result"></p>
<p id="result2"></p>
<p id="result3"></p>
</body>
</html>
getCountries.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country%"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
getCountries2.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
db.inc.php
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'Abc12345');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'world');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
$db = new PDO($dsn, DB_USER, DB_PASSWORD);
?>
EDIT: I just got the answer from the comments, the information is on the same row, not different, therefore it didn't work with
jsonObj2[2]["Continent"]
but it did work with
jsonObj2[0]["Continent"]
Thank you #sean!
It means that jsonObj2[2] isnt object. It seems like you dont have 3 rows (jsonObj2[2]) in database return array.
Try
jsonObj2[0]["Code"] + jsonObj2[0]["Continent"] + sonObj2[0]
["Population"]
It should work but dont know why you target to rows 0,2,7.

How to add var javascript value into id name?

How to add var javascript value into id name ?
I have $i = 5; and var i = 2;
How to concatenate php var $i with javascript var i ?
I tried like this but not work.
$('#test<?PHP echo $i; ?>'+i).live('click', function() {
do something
});
and
$('#test<?PHP echo $i; ?>'+i+'').live('click', function() {
do something
});
How can i do that ?
var phpi = '<?PHP echo $i; ?>';
$('#test' + phpi + i).live('click', function() {
//do something
});
or if you want PHP $i + JS i for exmaple (3 + 2 = 5)
var phpi = <?PHP echo $i; ?>; // no quotes here as we need number
$('#test' + (phpi + i)).live('click', function() {
//do something
});
PHP echo makes some space so that might hamper the selector use it like this

Autocomplete not working for dynamically created content

I am having a bit of trouble trying to add a autocomplete field to my dynamically created content. Previously it worked fine as the textbox was generated in HTML, but I cannot figure how to make it work with dynamically generated content (even trough I am using static textbox id for test purposes)
Autocomplete:
jQuery(document).ready(function($){
var products= JSON.parse( '<?php echo json_encode($products_list) ?>' );
var t = 0;
var r = '<?php echo json_encode($number_of_rows_tuote) ?>';
var availableProducts = [];
var cellPlace = [];
while(t < r){
availableProducts.push(products[t]['prsku']+":"+products[t]['prname']);
cellPlace.push(t);
t++;
}
$( "#product2" ).autocomplete({
source: availableProducts
});
});
Dynamic create content
function addElement()
{
var contentID = document.getElementById('more');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML ="<br><div class='product'><TABLE><tr>";
newTBDiv.innerHTML += "<td><input type='text' placeholder = 'product_code' name='sku_" + intTextBox + "' id='sku_" + intTextBox + "'/></td><td><input type='text' id='product2' name='product2'></td>;
contentID.appendChild(newTBDiv);
}
<body onload="addElement();">
Try to call your autocomplete function after the addElement function .
OR
simply add
$( "#product2" ).autocomplete({
source: availableProducts
});
these lines at the last of your addElement function like this
function addElement()
{
var contentID = document.getElementById('more');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML ="<br><div class='product'><TABLE><tr>";
newTBDiv.innerHTML += "<td><input type='text' placeholder = 'product_code' name='sku_" + intTextBox + "' id='sku_" + intTextBox + "'/></td><td><input type='text' id='product2' name='product2'></td>;
contentID.appendChild(newTBDiv);
$( "#product2" ).autocomplete({
source: availableProducts
});
}
Call function to bind autocomplete as shown below and remove onload from body.
<body>
NOTE - you have missed " at the end of dynamic element string i.e. after </td>, please correct it.
jQuery(document).ready(function($){
var products= JSON.parse( '<?php echo json_encode($products_list) ?>' );
var t = 0;
var r = '<?php echo json_encode($number_of_rows_tuote) ?>';
var availableProducts = [];
var cellPlace = [];
while(t < r){
availableProducts.push(products[t]['prsku']+":"+products[t]['prname']);
cellPlace.push(t);
t++;
}
$('body').load(function(){
var contentID = document.getElementById('more');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML ="<br><div class='product'><TABLE><tr>";
newTBDiv.innerHTML += "<td><input type='text' placeholder = 'product_code' name='sku_" + intTextBox + "' id='sku_" + intTextBox + "'/></td><td><input type='text' id='Product2' name='product2'></td>";
contentID.appendChild(newTBDiv);
//bind autocomplete
$( "#Product2").autocomplete({
source: availableProducts
});
});
});

autoincrement id in javascript variable

didn't really succes with assigning values to new ids in my while(row) statement:
Here is an easy example, hope you understand what I want to do. Thanks
<?php...
$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;
$teamname = rows['team'];
?>
<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';
//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement.
//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that
//var id_1 = team; //team 1
//var id_2 = team; //team 2
<?php
}
?>
var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
I would recommend using an array rather than individual variables, as you have a list of team names:
<?php
$teamnames = [];
while(rows = mysql_fetch_data){
$teamnames[] = rows['team'];
}
?>
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>
Then you end up with a client-side JavaScript array of team names. While you could then output them with document.write, there's probably a better option.
But here's your document.write updated to use the array:
var n;
for (n = 0; n < teamnames.length; ++n)
{
// Note: There's almost certainly a better choice than `document.write`
document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}
Replace your code with the following and it should give you the output that you're after...
<script>
<?php
//...
$id_counter = 1; //Initialise counter
while($row = mysql_fetch_assoc()){
echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
$id_counter++; //Increment the counter
}
?>
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>

Categories

Resources