Parse variable to URL in PHP (JSON) - javascript

I'm having an issue to load all the movieID and parse it into the location $movieID for url2.
With the code that i am having now (First Code), it will only retrieve one particular movie. When I click on the button, it have an alert box stating if it's success or error. I understand that because $url2 is outside of the loop. Hence, it's only able to retrieve one particular movie.
On second code, I have place it inside the for loop. However, it will keep looping and when I try to click on the button, it doesn't works. There is no alert box pop up.
How can I make the button works for all the $movieID that parse through the link?
First Code:
<?php
$url1 = json_decode(file_get_contents('http://www.movie.com:/retrieveMovies'));
$counter = count($url1);
for ($i = 0; $i < $counter; $i++){
$movieID = $url1[$i]->movieId ;
}
$url2 = json_decode(file_get_contents(' http://movie.com/movieOne?seatNum=' . $movieID),TRUE);
foreach ($url2 as $obj){
$testingResult = $obj['avail'];
echo "<button onclick = testBTN('".$testingResult."')>Seat ID</button>";
}
?>
<script>
function testBTN(x) {
if (x == "OK"){
alert("Seat booked" );
}
else
{
alert("Error in booking seats" );
}
}
</script>
second code:
<?php
$url1 = json_decode(file_get_contents('http://www.movie.com:/retrieveMovies'));
$counter = count($url1);
for ($i = 0; $i < $counter; $i++){
$movieID = $url1[$i]->movieId ;
$url2 = json_decode(file_get_contents(' http://movie.com/movieOne?seatNum=' . $movieID),TRUE);
foreach ($url2 as $obj){
$testingResult = $obj['avail'];
echo "<button onclick = testBTN('".$testingResult."')>Seat ID</button>";
}
}
?>
<script>
function testBTN(x) {
if (x == "OK"){
alert("Seat booked" );
}
else
{
alert("Error in booking seats" );
}
}
</script>

Related

If PHP echo code returns a value then run script. Else nothing

I have the following code which returns the result I require inside of a tab. But because the JavaScript is in the same file it shows a blank tab when there is no data to show. I remove the JavaScript and the tab disappears. How can I run the JavaScript only if data is present so the tab will disappear? Or can I call it from another file?
<?php echo $block->escapeHtml($block->getProduct()->getData($this->getCode()));
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
Since you have to hide the tab if escapeHtml() returns empty value. So you can create a condition block to add the script if escapeHtml() returns a non-empty value.
<?php $EH = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if ($EH) {
echo $EH;
?>
<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>
<?php } ?>
My knowledge on PHP is not the best, so I will just describe it like that.
Just save the data in a variable
If the data exists (e.g. is not empty)
Print data and JavaScript code
If it does not exist, do nothing
Here is some pseudo-code:
<?php
data = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
if (data exists) {
echo data;
echo /* Your JavaScript Code*/;
}
?>
Use a if statement that within the php tags that check value id present then you can render the the java script tags as well as the value.
<?php
$val = $block->escapeHtml($block->getProduct()->getData($this->getCode()));
$script = '<script type="text/JavaScript">
var commareplace = document.querySelectorAll("div > #bikefitment");
for (var i = 0; i < commareplace.length; i++) {
commareplace[i].innerHTML = commareplace[i].innerHTML.replace(/,/g, "<br />");
}
</script>';
if($val != "" || $val !=null)
{
echo $val;
echo $script;
}
?>

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

how to fix undefined variable in php?

I have an index.php page. The function of this page is infinite scrolling using AJAX, PHP and MySQL. The top portion contains PHP MySQL codes and bottom contains JavaScript.
I want to print the total number of rows in center of the page, but every time I try it shows "undefined variable" error.
I think when loading the page, the total number of variable tries to print first and then the PHP query takes place, so it shows "undefined variable", but when I put the total number of variable inside the PHP codings, there is no problem.
How can I prevent this?
My index.php is
//my php part here
<?php
if(isset($_POST["anotherID"])){
require_once("config.php");
$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%' ORDER BY rand() LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
$count = $actual_row_count;
exit;
}
?>
//my html part here
<html>
//some html codes
<?php echo $count; ?>
//some html codes here
//my java scripts here
<script type="text/javascript">
var busy = false;
var limit = 6
var offset = 0;
var anotherID = 5
function displayRecords(lim, off) {
$.ajax({
type: "POST",
async: false,
data: "limit=" + lim + "&offset="+ off+"&anotherID="+anotherID,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button"><div id="loader_image"><img src="loader.gif" alt="" width="24" height="24">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
//some html codes her
</html>
I know when a page is loading, the HTML parts are first loaded and then my jQuery stimulates the PHP part and then my results appear.
How can I fix this?
Why does $count always show "undefined variable"?
Thanks in advance.
You get an error of undefined $count because $count is defined only inside the if statement.
When the if clause doesn't apply $count is not defined.
Add an else clause to the if and initialize $count=0; and it will solve your problem.
Example:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>

Cloned div values not send through POST

I have a javascript function that clones a div which contains a inputfield, now the problem is that the cloned inputfield values isnt send through post. Only the first value of the array gets a value.
Anyone know what could be the problem?
Post button:
if(isset($_POST['VolgendeStap'])) {
$phonenumberAmount = count($_POST['phoneNumbers']);
echo $phonenumberAmount;
echo '<br>';
echo $_POST['phoneNumbers'][0];
echo $_POST['phoneNumbers'][1];
}
Divs with inputfield
echo "<div class='allPhoneNumbers'>";
for($j = 0; $j < $phonenumberAmount; $j++) {
echo "<div id='phoneNumber{$j}'>";
echo "<input type='text' name='phoneNumbers[]'>";
echo "<input type='button' class='removeButton' value='x'>";
echo "</div>";
echo '<script>';
echo 'current++;';
echo '</script>';
}
echo "</div>";
echo "<input type='button' id='cloneButton' onclick='cloneDiv(phoneNumber0);' value='Nog een nummer'>";
Javascript:
var max = 5;
var current = 0;
// Duplicates the DIV
function cloneDiv(divID) {
if(current < max) {
var newDiv = $(divID).clone();
newDiv.attr("id", "phoneNumber"+current);
current++;
newDiv.children()[0].value = '';
newDiv.find(".removeButton").show();
newDiv.children()[1].onclick = function() {
$(this.parentNode).remove();
current--;
if(current < max) {
$("#cloneButton").show();
}
};
newDiv.appendTo(".allPhoneNumbers");
if(current == max) {
$("#cloneButton").hide();
}
}
}
it looks like you are declaring the "var current = 0" on every page load, and when you post the form it executes that part of code (couse it causes the page to reload) and that's why you always see only the first one. You should have a function that sets the "current" initial and future values by actually counting the number of divs. Let me know if it works out, cheers!

How do i display a data from one page to another?

i have display data from xml file to the index.php like this
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent=='image')
{
echo '<div><img src="'.$data.'" ></div>';
echo '<div>';
echo '</div>';
}
elseif($agent=='id')
{
echo '<div class = "Left">';
echo '<input type = "button" name="Agent" id = "'.$data.'" class = "subs-btn" value = "Select this Agent" OnClick = Selected(this.id);>';
$_SESSION['Selected'] = $data;
echo '</div>';
echo '<br/>';
echo '<br/>';
}
else
{
echo '<div class = "inline1">';
echo $data;
echo '</div>';
echo '<br/>';
}
processXML($data);
}
}
processXML($xml);
you guys can see here i am generating a button and onclick function is call - Selected(this.id);
So here is the code of function
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
}
So due to this agent is selected. Now i had one button at the end of the page
<input type = "submit" name="Continue" class = "btn btn-primary right" value = "Continue">
now i want to display data which is related to selected agent on another page. So how can i display this data with respect to selected agent?
Please Help.
You would need to something along the lines of the following. This is more just psuedo code than an actual working example, as I don't know what you want to display about an agent
Note: I am assuming you have jQuery included.
JS
function Selected(elem) {
var buttons = document.getElementsByClassName('subs-btn');
var length = buttons.length;
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage="url('images/subs-btn.png')";
buttons[i].value="Select this Agent";
}
document.getElementById(elem).style.backgroundImage="url('images/subs-btn-act.png')";
document.getElementById(elem).value="Agent Selected";
//Start here
var AgentData = ""//something about the agent. their id or some other identifier
//here you would make an ajax call to a php script
$.ajax({
type:"POST",
data: AgentData,
url: "someurl"
});
}
PHP
$_SESSION["AgentData"] = $_POST["AgentData"];
Now you would be able to access that data about the selected agent anywhere as long as there is a valid session.

Categories

Resources