PHP script (AJAX is calling this) (within this is this variable):
$name_and_id = $first_name . " " . $last_name . " (" . $row['id'] . ")";
passed back like:
$datarr = array();
$datarr[] = array('name_and_id' => $name_and_id);
echo json_encode($datarr);
JSON successfully accepts like:
$.each(data, function(k, v){
v = v.name_and_id;
...
htmlStr += '<tr onclick="shrow(' + x + ',' + v + ',' + z + ')">'
... populates a div
This loads correctly, but when I click on that tr the request doesn't complete ... console says throwing an error at v ...
Related
I'm new to js and php, in fact web design in general....
I've had a website built by uni students. It uses PHP, JavaScript, Apache, AJAX, MySQL. Sadly the project is finished, but I need to change what is formatted.
What i have and what i require
I have tried to install WAMP on my computer without success.
Instead I edit the .js file in wordpad and swap it out on the server.
//Currently the output from displaying a "law" on my website is this:
//The ± and the second number (sd - in the code below SDBefore) is formatted green for 0<=sd <50.
//The first number (mean - in the code before meanBefore) is not formatted.
//AFAIK the javascript file on the server produces this is currently as follows:
$(".mean-value").html("Loading");
$(".sd-value").html("Loading");
//parse the returned data
var jsonData = JSON.parse(data);
$(".mean-value").html(parseInt(jsonData.mean));
$(".sd-value").html("± " + parseInt(jsonData.sd));
currentHTML = currentHTML + "<td><a href='./event-profile.php?id=" + event.event_id + "' >" + event.event_name + "</a></td>";
if(event.SDBefore >= 0 && event.SDBefore < 50)
{
currentHTML = currentHTML + "<td>" + event.meanBefore + "<span class='sd-value-green'>±" + event.SDBefore + "</span></td>";
}
//.....( JSON is a format for storing and transporting data).
//So what I want to do is one of the following a) or b)
// a) format the mean only according to 0<=sd <50.
Is this correct?
//parse the returned data
var jsonData = JSON.parse(data);
$(".mean-value").html(parseInt(jsonData.mean));
//$(".sd-value").html("± " + parseInt(jsonData.sd)); //Don't need this line
currentHTML = currentHTML + "<td><a href='./event-profile.php?id=" + event.event_id + "' >" + event.event_name + "</a></td>";
if(event.SDBefore >= 0 && event.SDBefore < 50)
{
currentHTML = currentHTML + "<td>" + "<span class='mean-value-green'>event.meanBefore+</span>" + ± + event.SDBefore + "</td>";
}
//b) format the whole law according to 0<=sd <50.
//So I have added the following (in bold):
// Is this correct?
$(".mean-value").html("Loading");
$(".sd-value").html("Loading");
$(".law-value").html("Loading");
//parse the returned data
var jsonData = JSON.parse(data);
$(".mean-value").html(parseInt(jsonData.mean));
$(".sd-value").html("± " + parseInt(jsonData.sd))
$(".law-value").html(parseInt(jsonData.mean) + "± " + parseInt(jsonData.sd));
currentHTML = currentHTML + "<td><a href='./event-profile.php?id=" + event.event_id + "' >" + event.event_name + "</a></td>";
if(event.SDBefore >= 0 && event.SDBefore < 50)
{
currentHTML = currentHTML + "<td>" + "<span class='law-value-green'> event.meanBefore + ± + event.SDBefore" + "</span></td>";
Have a look on ±. This is symbol you would like to change to +/-.
I have ajax data and want to change the format of numbers into currency, how to change the format? in php used echo number_format($list->REAL_SUBPRO_VAL, 2, ',', '.'), how about in ajax?
this is my ajax
function status(id_branch) {
$('#status').show(function(){
$.ajax({
url:"<?php echo base_url() ?>home/list_investasi_status/" + id_branch,
success(res){
var data = JSON.parse(res);
console.log(data);
$('#nama_cabang3').text(data.data2['DISPLAY_NAME']);
var data_status = "";
$.each(data.data, function(key, val){
data_status += "<tr>\
<td>" + val.RKAP_INVS_ID + "</td>\
<td>" + val.RKAP_INVS_TITLE + "</td>\
<td>" + val.RKAP_INVS_COST_REQ + "</td>\
<td>" + val.RKAP_INVS_VALUE + "</td>\
<td>" + 'Detail' + "</td>\
</tr>";
});
$('#show_status').html(data_status);
/*dropdown*/
var d_status = "";
$.each(data.data3, function(key, val){
d_status += "<option >" + val.STATUS_NAME + "</option>";
});
// value="val.STATUS_NAME"
$('#show_d_status').html(d_status);
}
})
});
example: val.RKAP_INVS_VALUE = 10000000, i want to format value to 1.000.000. help please thanks
Try the javascript splice method to insert a . into the string at the places you need. Here is the function doing it:
Moreover, you can use the php method number_format($list->REAL_SUBPRO_VAL, 2, ',', '.') and return your data in JSON so you will get a preformatted text.
var main = '1000000';
var ins = '.';
insert = function insert(main_string, ins_string, pos) {
if (typeof(pos) == "undefined") {
pos = 0;
}
if (typeof(ins_string) == "undefined") {
ins_string = '';
}
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var newstring = insert(main, ins, 1);
alert(insert(newstring, ins, 5));
I've been having an issue with AJAX parsing a JSON Array from a webservice I'm creating. My front end is a simple ajax & jquery combo to display results returned from the webservice I'm creating.
I'm getting an error within Chrome's console stating "cannot read the length property of undefined" despite knowing that there are results from my database query.
After looking for an answer for days I still cannot figure out why I get the console error.
Thank you for any help! :)
function ajaxrequest(e)
{
var r = $('#region').val();
var t = $('#type').val();
console.log(r,t);
$.ajax('https://URL...../.../POI/POI_LOOKUP.php',
{ type: 'GET',
data: 'type='+t+'®ion='+r+'&format=json',
success: onSuccess }
);
}
function onSuccess(data,status,xmlHTTP)
{
var html = "<table><th>name</th><th>type</th><th>country</th><th>region</th>";
for(var i=0; i<data.length; i++)
{
html = html + '<tr><td>' + data[i].name + '</td>' + '<td>' + data[i].type + '</td>' + '<td>' + data[i].country + '</td>' + '<td>' + data[i].region + '</td></tr>';
}
html = html + '</table>';
$('#results').html(html);
console.log(data);
console.log(status);
}
Here is my PHP to search and return all results:
IF ($type == "any" && !isset($region)) /* Search DB for all types of POI for all regions*/
{
$statement = $conn->prepare("SELECT * FROM pointsofinterest;");
$statement->execute();
$row = $statement->fetch();
if ($row == false)
{
header("HTTP/1.1 204 No Content");
}
else
{
$allResults = array();
while($row != false)
{
$allResults[] = $row;
$row = $statement->fetch(PDO::FETCH_ASSOC);
}
echo json_encode($allResults);
}
}
Ideally you should pass back empty results, if there are no results, and let the Javascript decide what to do (display a nice friendly message to the user). I haven't tested this, it's just for guidance, be warned.
PHP
if ($type == "any" && !isset($region)) /* Search DB for all types of POI for all regions*/
{
$statement = $conn->prepare("SELECT * FROM pointsofinterest;");
$statement->execute();
$results = $statement->fetchAll();
if (count($results)!=0){
echo json_encode($results);
} else {
header("HTTP/1.1 204 No Content");
}
}
JAVASCRIPT
You may want to handle the 204 response separately: How to handle a 204 response in jquery ajax?. The code below assumes you may receive an empty JSON response.
function onSuccess(data,status,xmlHTTP)
{
if (data.length==0) {
alert("Friendly user message");
return;
}
var html = "<table><th>name</th><th>type</th><th>country</th><th>region</th>";
for(var i=0; i<data.length; i++)
{
html = html + '<tr><td>' + data[i].name + '</td>' + '<td>' + data[i].type + '</td>' + '<td>' + data[i].country + '</td>' + '<td>' + data[i].region + '</td></tr>';
}
html = html + '</table>';
$('#results').html(html);
console.log(data);
console.log(status);
}
I'm desperately trying to gain access to the $BarcodeID by pressing the DELETE button on my site. All I want to do is retreive this 13 digit number, so that I can use it to remove that row from the item Database (Sql).
I know that as long as I get the correct row I can get the data but i'm wondering if thats even possible because I'm building the table inside a $.post().
Please note that before i started trying to make the button and get the barcodeID in the click function all of the code was working. Thanks!
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr><td id='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".delete").click(function(){
// var BarcodeID = $(this).closest('tr').find('#rowbarcode').val();
var BarcodeID = $(this).parent().find("#rowbarcode").text();
var $row = $(this).closest("tr"); // Finds the closest row <tr>
var $tds = $row.find("td:nth-child(1)"); // Finds the 2nd <td> element
console.log($tds);
//all I want is $BarcodeID
});
});//eof
Image of table on site:
Just for anyone who's interested I found a pretty neat way of solving my problem. Thanks to everyone who helped #Pointy #Taplar #Andreas. What I needed was 'event binding on dynamically created elements'. It is particularly useful when linked with $.post and $.get operations as they complicate data retreival.
Sample output to console:
5000157024671 <- if i clicked the first delete button
6221033101517 <- if i clicked the second delete button
Next stage:
As this is only a reference to a barcode number which has to be removed from the DB I will now pass this onto php via a post operation.
Next part of my project (adding a row search feature) can be found here:
Dynamically created table queries
Sample solution code:
$(document).ready(function(){
$.get("../php/security.php", function(response){
if(response.result == "failure"){
location.href='../user_login.html';
} else {
$("#header").load("../header_logout.html");
//from here down is the relevant code
$.post("../php/item_database.php", {email1:response.data.authUser}, function(indata){
indata.items.forEach(function(element){
$BarcodeID = element.BarcodeID;
$UserID = element.UserID;
$ProductName = element.ProductName;
$BrandName = element.BrandName;
$Weight = element.Weight;
$row = "<tr class='row'><td class='rowbarcode'>" + $BarcodeID + "</td>" + "<td>" + $ProductName + "</td>" + "<td>" + $BrandName + "</td>" + "<td>" + $Weight + "</td>" + "<td>" + "<button class='delete'>Delete</button>" + "</td></tr>";
$("#final_row").before($row);
});
}, "json");//eo post
} //eo else
}, "json"); //eo get
$(".contenttable").on('click', '.delete', function(){
var BarcodeID = $(this).closest('tr').find('.rowbarcode').text();
console.log(BarcodeID);
});
});//eof
I have a button called "Add" which relates to each person in a list.
echo <td><input type=\"submit\" id=\"PlayerAdded".$id."\" value=\"Add\"
onclick=\"add('".$id."','".$name."','".$_SESSION['GameID']."');\"></input></td>";
When "Add" is clicked, I want to add the persons details to a table (working fine), and also add a new row including their name and ID into a table in my DB (this is my problem).
I am aware that PHP won't work in a JS function. I'm also aware that I should never access the database on my site from JS due to the security issues.
So how can I have a button which onclick calls a function which adds to the database?
I tried writing my function in PHP, but it wasn't doing anything when I clicked the button. See my function below:
function add(id,name,game){
var t = ("</td><td>");
var str = ("<tr id='Players" + id + "'><td>")
var ctr = ("</td></tr>")
var PID = ("<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id)
var Pnam = ("<input type='hidden' name='Name" + id + "' value='" + name + "'></input>");
var place = ("<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>")
var points = ("<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>");
var cash = ("$<input name='Cash" + id + "' placeholder=' 0'></input>");
var ticket = ("<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>");
var del = ("<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>")
$('#PlayerAdded').before(str+ PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// This is where I want to insert into the db. Similar to
// <?php
// $sql = "INSERT INTO results (`col`, `col2`, `col3`) VALUES ('$id', '$name', '$game')";
// mysqli_query($dbcon,$sql); ?>
//but I want to be able to do it inside this java script function.
}
Remove the bracket before the variables, which you have written for every variable in function.
Add the ajax piece at the end of your function code.
function add(id, name, game) {
var t = "</td><td>";
var str = "<tr id='Players" + id + "'><td>"
var ctr = "</td></tr>"
var PID = "<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id;
var Pnam = "<input type='hidden' name='Name" + id + "' value='" + name + "'></input>";
var place = "<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>";
var points = "<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>";
var cash = "$<input name='Cash" + id + "' placeholder=' 0'></input>";
var ticket = "<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>";
var del = "<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>";
$('#PlayerAdded').before(str + PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// making ajax call to insert.php and posting the data
$.ajax({
method: "POST",
url: "insert.php",
data: {
"id": id,
"name": name,
"game": game
},
beforeSend:function(){
// show something before data is saved to db.
}
}).done(function(msg) {
$("body").append(msg); //debugging purpose
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
insert.php
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
$id= $_POST['id'];
$name= $_POST['name'];
$game= $_POST['game'];
//write your connection logic
// never write bare queries there is a chance of sql injection.
//Instead use prepared statement, prepare your query then bind the above values to it, then excute.
//write your insert logic below.
}
?>
You need to post the values you want to insert to your database via AJAX, append this to your add() function:
$.post('insertnew.php', { id:id,name:name,game:game }, function(data){
alert(data);
});
insertnew.php:
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
// sanitize your data here, then:
$id = $_POST['id'];
$name = $_POST['name'];
$game = $_POST['game'];
//connect to your db, or instead include your dbconnect.php
$link= new mysqli('localhost', 'my_user', 'my_password', 'world');
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//use prepared statement, prepare your query then bind the above values to it, then excute
$stmt = mysqli_prepare($link, "INSERT INTO results VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, $id, $name, $game);
if(mysqli_stmt_execute($stmt)){
echo "Record has been added successfully";
}else{
echo "Sorry, record could not be inserted";
}
}
?>
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli-stmt.bind-param.php