PHP undefined index from function send via jQuery - javascript

I am trying to make a function that will insert a html code (div) into a container, said div has an ID of the number of elements inside that container +1 (so when it adds the first it won't be 0). I am fairly (read 1 week) new to JS, jQuery and PHP so I am having trouble tyding up my code so it can do what I need.
Right now when I use the function it is displaying a undefined index error. The process the code should run is this:
In one page I enter some data and click a Accept button which saves that data into a database (Done).
2.When I click the accept button it also call a function that creates the aforementioned div, this code is in another file and its called with:
<script src="js/createLabDiv.js"></script>
The code of function goes like this (most likely with error >.< )
function agregar("#btnAceptar") {
var div = document.createElement('div'); //Creates div variable.
div.id = querySelectorAll('lista > div').length +1; //assigns id to div based on elements inside the list
var numero = div.id; //I'll need this to display a specific set of info depending on the div id.
'<div class="box"> // Code for the div.
<p>Lab #'numero'</p>
<p class="info">Info</p>
<p class="info">Reservar</p>
</div>';
document.getElementById('lista').appendChild(div); //Where it is isnserting it.
var request = $.ajax({ //Here it gets muddy, I want to send this data to a php file so I can call it on my list.php
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'createDiv',
'pDiv':div,
'pNumero':numero},
dataType: 'json',
});
}
3.On my includes php file I have:(Again kinda murky)
function getLabs(){
$idDiv=createDiv();
$query = "SELECT bk.idlab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $idDiv";
$result = do_query($query);
return $result;
}
function createDiv(){
$idDiv = $_POST['pNumero'];
echo $div = $_POST['pDiv'];
$result = $idDiv;
return $result;
}
4.And lastly in a different page I have:
<div class="scroll-area" id="lista">
<?php createDiv() ?>
</div>
Just in case, all of these pages contain the scrip for the js. and the includes for the php.
Both of them are working with the data I entered into my database for testing purposes, also the add (agregar) button on the add.php IS inserting correctly the data from the form, the list.php page which includes the piece of code just above this wall of text is also working when displaying the data from one Lab I already added to the database, the reason I needed number above was that when I called this:
<div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>InformaciĆ³n de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<?php displayLabs() ?>
<input type="button" value="Eliminar" id="btnEliminar" onclick="eliminar()" />
<input type="button" value="Modificar" id="btnModificar" onclick="window.location='modificarLab.html';" />
</div>
It was displaying the info of all the labs in the databse, thus why I added the WHERE bk.idlab = #idDiv.
I am quite stuck right now, so any kind of help would be very appreciated, I will probably be able to reply until tomorrow cuz I think I feel kinda sick from staring at my monitor all day >.>
Thanks a lot in advance and best wishes!

Related

How to pass JavaScript random.Math results to PHP

I'm have created a random slot machine with JavaScript, which works perfectly fine.
After the result is shown in the slot machine, a button to open a modal/dropdown window appears, here the user can get more details about their results (bigger image, text, titles, google map locations etc).
But for the next part of my project I have created user logins (using PHP & MySQL), so now I want to save the randomly generated result shown inside the modal/dropdown window (JavaScript) to the user's personal profile side (PHP/SQL) so that they can recheck their results when ever they feel like it.
Does anyone know any good solutions?
I have a JavaScript random image generator (with accompanying attributes) which looks like this:
const array = [
{img: 'img1.png', text:'image one', title:'etc etc etc'}
//img2 & img3 under here.
];
function generate(){
setTimeout(funtion first_img() {
index = Math.floor(Math.random() * array.length)
var display = array[index]
var result = document.getElementById('box').innerHTML += '<div><h2>' + `${display.title}` + '</h2><img src="' +`./img/${display.img}`+'"><p>'+`${display.text}`+'</p></div>'
document.querySelector('input["data"]').value = result;
}, 3000);
}
function modal_window(){
document.getElementById('before-box').style.display = 'none';
document.getElementById('modal-window').style.display = 'block';
}
This is displayed in my Index.php file after the button is clicked.
<button onclick="generate()">Generate Image</button>
<div class="open-modal-btn">
<button onclick="modal_window()">See details</button>
</div>
<div id="before-box"></div>
<div id="modal-window">
<div class="box"><
<form method="get" action="profile.php">
<input type="hidden" name="data"/>
</form>
See Profile Results
</div>
</div>
Now, I want to save this result to my Profile.php file and save it there for like two weeks, ish, but I don't know how, the $_GET['data'] is just an example because I can't have name="" attributes in div tags, which is why I don't know what should be there - it would have worked with input name="data", but in my case, the user is not supposed to contribute.
<?php
include ('conn.php');
session_start();
$res = $_GET['data'];
echo $res;
?>
I have the JavaScript array stored inside my SQL database in the same manner, with numbered ID as 0-2 (since JavaScript arrays start at 0), is there any way I can match the random number index with the SQL ID when retrieving the data maybe?
for example:
<?php
$id = $_GET['data'];
$sql = mysqli_query($conn, "SELECT * FROM array WHERE id = '$id'");
?>
Any solutions or tips are greatly appreciated, thanks!
PS: I do not mind implementing new code languages/variants to resolve this issue (AJAX, Python, etc) anything helps.
From: a desperate bachelor student :`)
You need to submit the form but you use outside for go to profile, instead you need to use a button inside form like:
<form method="get" action="profile.php">
<input type="hidden" name="data"/>
<button type="submit">See Profile Results</button>
</form>

Pass PHP variable from one page to another to get correct item from button [duplicate]

This question already has answers here:
PHP Pass variable to next page
(9 answers)
Closed 1 year ago.
I have 2 pages, content.php & pagecontent.php, and in content.php I display products info from database into table tags and inside has a grid of 2 rows and 3 columns that I echo descriptions of the products into. One of the grids row holds a button with and thumbnail image over it so that it would link or send user to pagecontent.php for that specific product info page. On pagecontent.php the user will be able to add the product/s to a cart/wishlist(not there yet, future stuff).
Ok so far on content.php I've been able to display all products from database, from the query and while loop, works, I was able to change stuff in database and changes would happen on content.php. I've had no success on passing a variable or id with $_GET, and I believe that's what I would want to use for this case. Also don't think my ajax is correct or it's missing things. I was trying to figure out how the button would get the products PartsID (1,2,3,etc...) from database, PartsID is the column name, to later be called when clicked then pass it to pagecontent.php to get correct product info from button. If there's a better way then the way I have the being used then let me know.
content.php
<?php
$stmt = $pdo->query("SELECT * FROM Parts");
while ($product = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<td>
<?php
echo '<button type="button" class="testButton" onclick="test()">
<img src="images/APA802AC.jpg">
</button>';
?>
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>
<?php
echo $product["Manufacturer"];
?>
</p>
</td>
<script type="text/javascript">
function test(itemid) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
{
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "pageContent.php?id=" + itemid, true);
xhr.send();
}
</script>
pagecontent.php
This page has tables as well but no grids. I need to get previous page button clicked PartsID(1,2,3,etc...) here and display that products info where I echo $row.
<div class="productInfo">
<h2 class="productTitle">
<?php
echo $row["PartTitle"];
?>
</h2>
</div>
<td>
<?php
echo $row["Availability"];
?>
</td>
<td>
<?php
echo $row["Price"]
?>
</td>
I would really hope for some detailed help please. I've tried all sorts of different variations of code and research, learning as I go with little time I have, new to php and javascript/ajax so go easy on me please. I hope I was clear and makes sense. Thanks!
First of all, your line
window.location.assign("pageContent.php").innerHTML = xhr.responseText;
is not doing what you think it is doing. "location.assign" loads a different page. Haven't tried myself to see if that will through an error to console for the innerHTML dereferencing, but you should check the network tab in your browser, most probably you will see 2 calls to pageContent: one with parameter (your ajax call) and 2nd one without (your location.assign call).
Secondly, if you have a multipage php application, you probably dont need ajax, as the page content is generated on the server side and after that it becomes static. Ajax is more suited for a single page applications with dynamic content.
w/o changing your application code too much, try to remove the ajax call and use only window location:
<script type="text/javascript">
function test(itemid) {
window.location.assign(_your_base_url_ + "pageContent.php?id=" + itemid)
}
</script>
I believe that would allow you to see the parameter on the server side in $_GET query.
P.S. I havn't been doing php lately so the above answer is more or less a concept. You may have to check php documentation for how to access the parameters. And reading some tutorials on this subject is not such a bad idea, as it seems that you do have some gaps in understanding the overall concept of doing web applications with php.

Getting Javascript/jQuery and PHP To work together

UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.

need javascript or jquery function to wrap php code (window.setInterval bootstrap list group)

Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics

jQuery Auto-submit form inside of a <div> loads in new page

I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>

Categories