Ajax not firing in div populated by ajax - javascript

I have a div which is populated via an ajax request.
Within the div is a form which when completed should use the same type of ajax request to populate a further div. I have used the same method to create both but the second javascript does not run:
First one (which works):
<div class="content_text" id="searchbysurname">
<p><form name="searchbysurname">
<b>Search by Surname: </b><input class="inline" type="text" name="q">
<input type="submit"></form>
<script>
$('#searchbysurname form').submit(function(){
var data=$(this).serialize();
// post data
$.post('searchbysurname_test.php', data , function(returnData){
$('#resultstable').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
<div id="resultstable"></div>
Second one (which is in the resultstable div) that doesnt work:
<? require_once("dbcontroller.php");
$db_handle = new DBController();
$q = ($_POST['q']);
$employees=array();
$sql = "SELECT employees.employeeid, employees.firstname, employees.surname FROM employees where UCASE(employees.surname) LIKE UCASE('%".$q."%')";
$employees = $db_handle->runQuery($sql); ?>
<table class="invisible">
<?
if(isset($employees) && !empty($employees)){
foreach($employees as $k=>$v) {
?>
<tr><td><?php echo $employees[$k]["firstname"]; ?> <?php echo $employees[$k]["surname"]; ?> </td>
<td><div id="viewemployeedetails<? echo $employees[$k]["employeeid"]?>">
<form>
<input type="hidden" name="id" value="<? echo $employees[$k]["employeeid"]?>">
<input type="submit" value="View">
</form>
</div></td>
<div id="mainpart"><b></b></div>
<script>
$('viewemployeedetails<? echo $employees[$k]["employeeid"]?> form').submit(function(){
var data=$(this).serialize();
// post data
$.post('viewemployeedetails.php', data , function(returnData){
$('#mainpart').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>

I know it's not related to your question but you shouldn't be using the PHP short tag notation, it has been deprecated: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
Your first block of code is HTML with inline Javascript, which is an awful way to do things, you will get hard to debug errors if you insist on using Javascript in this way. You should be putting your Javascript in a separate file from the HTML and including it just before the final body tag. Ideally you should be using window.onload (or other similar methods, like a closure or jQuery's .ready() method) to ensure that DOM traversing elements of your script are only parsed after the DOM is fully loaded.
Your second block of Javascript code will never run because it doesn't exist when the browser parses the HTML. It's only injected later but Javascript doesn't work that way. You can inject javascript dynamically but not like that. You would have to do something like this:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);
I took this code from here: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

Related

Javascript receiving NULL object from PHP

I'm trying to send a JSON object from PHP to my Javascript code. I'm new to PHP, so I'm running into some troubles achieving this. As a note, all of my HTML, PHP, and javascript code are contained within a single PHP file. I looking for solutions that don't use AJAX or Jquery, so I've been trying the json_encode method. Unfortunately, while my code will compile, my javascript object seems to be NULL after I parse it.
I have tried json_encode from a variable in javascript and, while there are no errors, it still returns a NULL object. I also have tried to send it to a hidden form field and retrieve it from there using DOM, to little success. I suspect that maybe my PHP code is simply not running after form submission, but I don't know if that is the root of my issue or my syntax is incorrect when attempting to transfer a php object to my javascript code.
<?php
$street = $city = $state = $location = $url = $lat = $lon = "";
$geolocation = $coords = $temp = $details = null;
$temparray = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['location']) && $_POST['location'] == 'Yes'){
$geolocation = json_decode($_POST["geolocation"]);
$lat = $geolocation->lat;
$lon = $geolocation->lng;
$details = find_forecast($lat, $lon);
}else{
$street = $_POST["street"];
$city = $_POST["city"];
$state = $_POST["state"];
$temparray = find_coords($street, $city, $state);
$lat = $temparray[0];
$lon = $temparray[1];
$details = find_forecast($lat, $lon);
}
}
?>
I didn't include the functions in my php code above because I know that the php code itself works (I tested in a separate environment with hardcoded values).
<script type="text/javascript">
document.getElementById('theform').addEventListener('submit',
function(evt){
evt.preventDefault();
var stuff = "<?php echo json_encode($details); ?>"; //tried 2 ways
to achieve
var arr = JSON.parse("<?php echo json_encode($details); ?>"); //2nd
way to test if it would work
console.log(arr);
document.getElementById("timezone").innerHTML = "<p
id='timezone'>" + arr.timezone + "</p>";
})
This is my javscript code where I try to retrieve the JSON object, encode it, and parse it. Unfortunately, my "arr.timezone" results in a "undefined" value and my console.log(arr) results in "null".
<form id="theform" onSubmit="return checkInput()" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" target="testiframe">
<h2><i>Weather Search</i></h2>
<label for="street"><b>Street</b></label>
<input id="street" name="street" type="text" value="">
<div class="sub-entry">
<input type="checkbox" id="location" name="location" value="Yes">
Current Location
</div>
<br><br>
<label for="city"><b>City</b></label>
<input id="city" name="city" type="text" value="">
<br><br>
<label for="state"><b>State</b></label>
<select name="state" id="state">
<option value="state">State</option>
<option value="line">----------------</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
<br><br><br><br>
<div class="button">
<input id="search" name="Search" onclick="checkInput()"
type="submit" value="Search">
<input id="clear" name ="clear" onclick="clearform()"
type="button" value="Clear">
</div>
</form>
<div id= "blue" class="blue">
<p id="timezone"></p>
</div>
If it helps, this is part of my form. My file is named hello.php at the moment. Additionally, I have the target = testiframe (also an iframe tag at the bottom of my html) because I researched that it is a way for you page to not refresh after a form submission, as I wanted the user input values to remain after you submit. I tried removing this feature, and my javascript still didn't work properly though.
I've gotten no syntax errors. I should receive a JSON object from my find_forecast() and my data.timezone should not be undefined.Any help would be appreciated, as I've been stuck on this problem for awhile.
json_encode() formats the result so it's a valid JavaScript literal. Don't put quotes in the JavaScript when you use <?php echo json_encode(...) ?>. You also don't need to call JSON.parse() (but if you do, you have to put it in single quotes, because double quotes are used in the JSON itself).
<script type="text/javascript">
document.getElementById('theform').addEventListener('submit', function(evt){
evt.preventDefault();
var stuff = <?php echo json_encode($details); ?>;
console.log(stuff);
document.getElementById("timezone").innerHTML = "<p id='timezone'>" + stuff.timezone + "</p>";
})

Dynamically send javascript value via form

I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

Calculate input of html text fields with php

At the moment, I try to create a survey in a webpage. At the end of the survey, users are able to fill two text fields with values. With these values, my plan is to calculate an output, displayed for them at the same page. So:
Input: a
Input: b
Result: ab+b-ab (do not concentrate this please, its just an example)
My plan is that the user is able to fill the two input fields and by a buttonclick, a php function is calculating the result field (by my own algorithm depending on input - this is already working) and fills this field. Do i have to link to another webpage for this purpose?
And how is it possible to grab the two input values and give it to my php function?
And as last thing, how is it possible to start a php function either embedded in html or in an own file?
I tried your solution and some others as well (fetching inputA and inputB from the DOM with document.getElementById does not work. Below is my code
<form>
InputA:<br>
<input type="text" id="inputA"/></br>
InputB:<br>
<input type="text" id="inputB"/></br>
Output:<br>
<input type="text" id="output"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
<script type="text/javascript">
$("#calculate").click(function(){
$.get( "submit.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
</script>
submit.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$output = $value1 + $value2;
echo($output);
}
?>
When I check with firebug the error, i get a: no element found exception in both (html and php) files. Seems like the problem is, that with: value1: $("#inputA").val(); no value is givent to the server or it can not be handled there.
If i grab the value from the DOM, I can "bring" the value inside the .click function but there is still a "no element found exception" by calling the submit.php.
I have no idea what i am doing wrong, any suggestions? Do i need to install/bind anything in for using JQuery?
After some additional changes, it finally worked (one thing was the header line in the submit.php file):
<form>
WorkerID:<br>
<input type="text" id="workerId"/></br>
CampaignId:<br>
<input type="text" id="campaignId"/></br>
Payment Code:<br>
<input type="text" id="payCode"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript">
$("#calculate").click(function(){
$.get( 'submit.php', { wId: $('#workerId').val(), cId: $('#campaignId').val()} )
.done(function( data ) {
$('#payCode').val(data.payCode);
});
});
and submit.php:
<?php
header('Content-Type: text/json');
$workerId = $_GET['wId'];
$campaignId = $_GET['cId'];
$payCode = $campaignId . $workerId;
$result = array("status" => "success",
"payCode" => $payCode);
echo json_encode($result);
?>
To simplify, i am using jQuery, doing this in vanilla JS is a real pain in the a** in my opinion.
You can use .get(), which is the GET shorthand for .ajax().
With that code, you bind a handler on your submit button and make a AJAX request to your PHP and fill the result your PHP gives into your result field asynchronously.
$("#calculate").click(function(){
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
Also change your submit to something like this:
<input name="go" type="button" value="Calculate" id="calculate" >
Like that, your button won't submit a form and therefore synchronously load your PHP.
Since you seem new to JavaScript and you had this comment
my button, but here i got redirected to submit, no idea how i can go back to page before with filled textfield
in your question, i'll tell you, JavaScript works while the DOM (Document Object Model) is loaded, means you can access your elements when already loaded and alter them.
Getting the value of a input is as easy as that in jQuery:
$("#inputA").val();
With the AJAX you get what your php will return in data.
// the { value1: $("#inputA").val(), value2: $("#inputB").val() } object
// is what you send to your PHP and process it
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
// data is what your php function returned
});
Using JS you can now change your elements as just said, effectively meaning to change the value of your output here:
$("#output").val(data);
"Working" Example: JSFiddle (There is no PHP to access to, so it will not do anything actively)

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources