Unable to access AJAX Response Data through jQuery - javascript

I have searched and tried for hours but unsuccessful.
I have an existing page which displays simple data from DB using PHP in an HTML table. Now I want to implement AJAX functionality so that data is refreshed without page refresh.
I have implemented this solution, to my understanding, the AJAX call part is working and the values are getting refreshed as expected. but I am stuck in getting the values.
index.php (main page)
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>
<table border="1" id="output"></table>
<script id="source" language="javascript" type="text/javascript">
$(function() {
update_content();
});
function update_content()
{
$.ajax({
url: 'query.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to query.php
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
if(data){
(data + '').length;
}
var temp = new Array();
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
}
});
setTimeout(function(){
update_content();
}, 1000);
}
</script>
</body>
</html>
query.php (used for AJAX call)
<?php
include('inc/connection.php');
# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>
If I run query.php directly in the browser, I see all the data in this format:[{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]
But on my main page, I see undefined inside the table.
I'd ideally like to have all the values (using a JS loop in the above code may be) to display all the records fetched from DB (variable no. of records).
HINT/MODIFICATION
When I change:
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
to
$('#output').html("<tr><td>"+data[0]+"</td></tr>");
in index.php
AND
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
to
$table_data[]=$row;
in query.php, then I get only first row as a string like
20170614,AUD,40.
END HINT/MODIFICATION
I am sorry if that's a silly question/problem. I am new to jQuery and trying AJAX for first time.
P.S. I know mysql_* functions are deprecated and I am aware of the vulnerability.
Your help would be highly appreciated.

When you update your data table you'll probably want to just rebuild the table. In your callback function, you need to loop through the array and add new rows to the table.
$.ajax({
url: 'query.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) {
if (!Array.isArray(data) || !data.length) {
return;
}
$("#output").empty(); //clear old table data
for(var i = 0, len = data.length; i < len; i++) {
$("#output").append(
"<tr><td>" + data[i].LastUpdated + "</td>" +
"<td>" + data[i].symbol + "</td></tr>" +
"<td>" + data[i].sum + "</td></tr>"
);
}
}
});

You have to change code as mentioned below.
From
data["symbol"]
to
data.symbol
Let me know if it not works.

Related

Saving a search result in Mysql with jQuery/Javascript

I'm trying to save google's API search results in a Mysql database in localhost.
My problem
I'm using a for loop to show every possible result from book research, such as "Harry Potter".
I do this with AJAX and then I cycle the results.
The main problem is that if I want to save one of the results, what is saved is just the last one because every variable is overwritten during every cycle.
Here is the code, saveBook.php is just a .php file where I do an insert into query.
$.ajax({
url:"https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
type: 'GET',
success: function(data){
for(i=0; i < data.items.length; i++)
{
title = $( '<p> ' + data.items[i].volumeInfo.title + '</p>');
author = $('<p> ' + data.items[i].volumeInfo.authors + '</p>');
img = $('<img><a href=' + data.items[i].volumeInfo.infoLink +
'><br></br><button>Read More</button></a>' );
url= data.items[i].volumeInfo.imageLinks.thumbnail;
save = $('<br><button onclick="save()">Save</button></br>
</br>');
img.attr('src',url);
title.appendTo("#result");
author.appendTo("#result");
img.appendTo("#result");
save.appendTo("#result");
}
},
});
}
}
function save(){
$.ajax({
type:'POST',
data: {
url: url,
title: title,
author: author,
},
url: "saveBook.php",
success: function(data){
alert("Success!");
location.replace("home.php");
}
})}
Another problem is:
how should I use this JSON
data: {
url: url,
title: title,
author: author,
},
to actually return a string with title and author, because url is correctly saved.
I've had some time to think over your project. While I'm not sure of all of your project requirements, a fundamental pursuit should be to minimize the calls to the api. For this reason, let your users search via a standard (non-ajax) search input/form and load the api results into the html with php, then use your ajax call to allow multiple save calls from a single load of search results (if that makes sense for your project). Basically, I suppose I am discouraging the auto-reload after saving a single item; otherwise you can avoid ajax again.
Also, as far as I know authors is an array, so you'll need to join/implode the values into a single string.
foreach (json_decode($apijson, true) as $item) {
echo '<div class="book">';
// your other elements in the row
echo "<button onclick=\"save('" ,
htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['title'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars(implode(', ', $item['volumeInfo']['authors']), ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['imageLinks']['thumbnail'], ENT_QUOTES, 'UTF-8') , "');\">Save</button>";
echo '</div>';
}
Then these parameters can be directly fed to your ajax function.
Be sure to validate and use sensible data sanitizing techniques and use a prepared statement when you INSERT.
You can return a success message from your ajax, and then hide() the saved row/book.
You can return a vague (not exact) error message if the insert did not make an "affected row".
Problem solved thanks to #mickmackusa. I have declared the variable "save" as a global array and, then, I have passed every string with a proper escape. Now it's working fine! Thank you very much.
save[i] = $('<button onclick="save((\'' + data.items[i].volumeInfo.authors + '\'),(\'' + data.items[i].volumeInfo.title + '\'),(\'' + data.items[i].volumeInfo.infoLink + '\'))">Save</button><br><br>')

Server-side table deletes row from tables (but not database) using JS, Php, or Ajax

Project Link: https://databasetable-net.000webhostapp.com/
This following code correctly deletes a row in a table:
$('#example').on('click', '.delete_btn', function () {
var row = $(this).closest('tr');
var data = table.row( row ).data().delete;
console.log(data);
alert("delete_btn clicked");
row.remove();
});
However, it is not permately deleting the row. If you refresh the page, the row that got 'deleted' still exists. I believe this is because I am not deleting the row out of the database. Normally in php you safely remove a row in a database with something like this:
id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header('location: index.php');
EDIT: Revised Code Index.php:
(document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},
//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { 'del_id' : del_id},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
alert("delete btn clicked");
ele.remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
}); //http://jsfiddle.net/zfohLL0a/
}); //end doc ready
delete.php code:
$del_id = $_POST['del_id'];
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array);
?>
Partial Solution: Sample format how to setup the ajax. You have to start off by using the datatables.net "ajax": method for the original server.php. But then after that you use the normal $.ajax methods for the add.php, delete.php, etc. It is confusing because you use two different syntax for ajax. Easiest to just look at the sample link. Youtube video for same code
Another helpful link that discusses sending info to and from the ajax/json are one two three Four
Updated answer using your latest updated code.
JS
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { //Set up your post data as an array of key value pairs.
'del_id' : del_id
},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
ele.fadeOut().remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
});
delete.php
$del_id = $_POST['del_id'];
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array); //Your ajax is setup to expect a json response.
//json_encode the $array and echo it out. You have to do this.
//When you "echo" out a value, that is what the server is going to submit back to the ajax function.
//If you do not do this, the ajax script will not recieve a response from the delete.php page.
This code should work for you.
In addition to Joesph's response who was extremely helpful:
"The console shows "Uncaught RangeError: Maximum call stack size exceeded". It looks as though the Ajax call isn't being issued (nothing is showing on the network tab) - so it must be when creating the request. I suspect I may need to JSON.stringify your del_id."
Someone suggested this:
"The main stack problem is caused by var edit_id = $(this).closest('tr'); . You try to send that whole jQuery object as data in the ajax. Then jQuery can't serialize it internally and throws a fit
You probably want some property like ID or a data attribute from that row to send (not clear what expectations are)."
Please post if you have any recommendations. I will edit in any finalized code solution soon.

send jQuery generated table to another php page

In my project (some kind of online game store), i have a jQuery generated table from click on original table row. The original table is populated from mysql database. On submit i need to send that generated table to another php page. I'm quite new with it and so far this is my code:
on php_first.php
generated table
<form action="php_second.php" id ="form_send" name ="form_send1" method="POST">
<div>
<table id="generated_table" style="display:none" name ="generated_table1">
<tr><th>Game</th><th>Platform</th> <th>Genre</th> <th>Price</th><tr>
// generated rows here
</table>
<input type="submit" value="Confirm" id="btnOrder" style="display:none"></input>
</div>
</form>
generated rows
$(document).ready(function(){
$('#original_table tbody tr').click(function(){
var data = $(this).children("td").map(function(){
return $(this).text();
}).get();
var row= '<tr name ="new_row"><td name = "game">' + data[0] + '</td><td name = "platform">' + data[1] +
'</td><td name = "genre">' + data[2] + '</td><td name = "price">' + data[3] +
'<button type="button" onclick="remove(this)" class ="btn_remove">Remove</button>' +'</td></tr>';
$("#generated_table tbody").append(row);
$('#generated_table').show();
$('#btnConfirm').show();
});
ajax post to php_second.php
$('#btnOrder').click(function(){
var table= $('#generated_table');
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {data: table},
async: false,
success: function(data){
alert(data);
}
});
However, ajax dosen't do alert(data) so i asume this is the problem but i cant determine it.
and on php_second.php
<table id="table_order" name = "table_order1" style="display:show">
<?php
if(isset($_POST['generated_table'])){
$table= $_POST['generated_table'];
echo $table;
}
?>
</table>
The problem is that i cannot post table data to another php (and print that table on other php when redirected). Tried to use ajax to send row data on row click, or passing div where table is but nothing. It shows no errors but no data is passed.
This is my first question so it is possible that i missed out some details to make the problem more clear. Thanks!
EDIT
I've tried Kalaikumar Thangasamy's code and ajax is working fine now, but the problem is on other php page.
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
echo $table;
}
else {
echo "None selected";
}
?>
The $_POST['data'] or any other parameter from first php is always null.
Change data: {data: table} to data: {'generated_table': escape(table)}. Posting data as but referring post data in $_POST['generated_table']. You suppose to be used $_POST['data']. Try this
var table= $('#generated_table').html();
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {'generated_table': escape(table)},
async: false,
success: function(data){
alert(data);
}
});

Passing JavaScript array from view to Laravel controller

I am trying to pass objs array to a function in Laravel controller using ajax. I am not recieving any data after the post.
<script>
var itemCount = 0;
var objs=[];
$(document).ready(function(){
var temp_objs=[];
$( "#add_button" ).click(function() {
var html = "";
var obj = {
"ROW_ID": itemCount,
"STREET_ADDRESS": $("#street_address").val(),
"CITY": $("#city").val(),
"ZIP": $("#zip").val()
}
// add object
objs.push(JSON.stringify(obj));
itemCount++;
// dynamically create rows in the table
html = "<tr id='tr" + itemCount + "'><td>" + obj['STREET_ADDRESS'] + "</td> <td>" + obj['CITY'] + " </td> <td>" + obj['ZIP'] + " </td><td><input type='button' id='" + itemCount + "' value='remove'></td> </tr>";
//add to the table
$("#multiple_table").append(html)
// The remove button click
$("#" + itemCount).click(function () {
var buttonId = $(this).attr("id");
//write the logic for removing from the array
$("#tr" + buttonId).remove();
});
});
$("#submit").click(function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address',
type: 'POST',
dataType:'json',
contentType: 'application/json',
data: objs
});
});
});
</script>
In my controller function is like this
public function search_address(){
$data = json_decode($_POST['data'], true);
print_r($data);
}
I guess that I am having a problem with the url in ajax and I am not sure how a controller's url is obtained.
Thank you
Can you change:
$data = json_decode($_POST['data'], true);
to:
$data = json_decode(Input::get('data'));
and make sure you have: use Input; above your class extends Controller
See if that works.
Edit: Also make sure your routes (in the Controllers folder) are correct.
You should console.log() your javascript by placing the following in you ajax post:
error : function(e){
console.log(e);
}
You can then see what errors you are getting in your browsers' developers tools panel.
You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:
$("#submit").on('click', function() {
$.ajax({
url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
type: 'POST',
data: {'data': objs, '_token' : '<?=csrf_token()?>'},
success : function(data){
// Do what you want with your data on success
},
error : function(e){
console.log(e);
}
});
});
Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:
<input type="hidden" id="_token" value="{{ csrf_token() }}" />
in your HTML, then pull this value from inside your ajax request:
data: {'data': objs, '_token' : $('#_token').val()}
EDIT
I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:
Route::post('/searchAddress', 'YourController#search_address');
Then use:
url: /searchAddress
in your ajax request.

AJAX call working on local server but not online

When a user goes to one of the pages (let's call it page1), the PHP loads the HTML content for an array containing data about the users.
Once the page is loaded (DOM ready), I use jQuery to perform an AJAX call to retrieve the HTML for that array of data. I do this to get the benefit of using separate PHP template files. In this way, PHP will call the PHP template for every array in the bi-dimensionnal array and return the HTML.
page1.php:
<script type="text/javascript">
var globalArray = <?php echo json_encode($freres); ?>;
jQuery(function($) {
liste(); // Ajax call to get HTML for the data in "globalArray"
});
</script>
AJAX call:
function liste() {
$.ajax({
data : {
array : globalArray,
dataName : 'someName',
file : 'templates/t_item_file'
},
dataType : 'html',
success : function(data, textStatus, jqXHR) {
var table = $('table');
var rows = $('<table>' + data + '</table>').find('tr');
rows.each(function(i, e) { // insert with fade-in animations
var row = $(e);
row.hide();
table.append(row);
row.delay(i * 15).fadeIn(250);
});
},
type : 'GET',
url : config.site + 'ajax/view' // configured in header
});
}
Somewhere in t_header.php:
<script type="text/javascript">
var config = {
base : "<?php echo base_url(); ?>",
site : "<?php echo site_url(); ?>"
};
</script>
The config route that redirects to ajax/view/...
$route['ajax/(:any)'] = 'c_ajax/$1';
The method of the controller c_ajax that handles the AJAX call:
public function view() {
$file = $this->input->get('file');
$array = $this->input->get('array');
$dataName = $this->input->get('dataName');
foreach ($array as $vars) {
$data[$dataName] = $vars;
$this->load->view($file, $data);
}
}
When I do this using EasyPHP on localhost, everything works fine, and I receive the HTML as expected, something like :
<TR>
<TD>...</TD>
//...
</TR>
<TR>
//...
And then I insert it into a table. But, when I try to do it on my website in FireBug, I can see that the AJAX response is not 200, but 302 Moved Temporarily.
Can anyone help me to figure out what to do to get it to work, because I spend almost the last four days learning jQuery and AJAX, and it doesn't work (online only).
Instead of
file : 'templates/t_item_file'
give full path of the controller
eg:"http://www.yourdomain.com/---/templates/t_item_file"
Problem solved. I load the HTML data in PHP and pass it to JavaScript, and then use jQuery to animate DOM Elements.
Previously, I didn't pass HTML but raw data in a PHP array, and then tried to get the HTML for all the elements of thie array via Ajax (HTML for all elements in only one call). I think there was too many parameters in the request and that's probably was caused the error.

Categories