Hi everyone i'm new to Ajax,i'm using ajax to get values from my database in form of an object array from a separate PHP file and displaying them in a table,everything works fine,but i want to create a link and append the ID obtained from the array so that i can send a GET request to another PHP file which will act upon that particular row.
code for the PHP File
<?php
include 'Module/Credentials.php';
$sql="SELECT * FROM queries";
$query= mysqli_query($connection, $sql) or die(mysqli_error($connection));
$data = array();
while ($row = mysqli_fetch_object($query))
{
array_push($data, $row);
}
echo json_encode($data);
`
Ajax code
javascript
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = "management.php?delete=";
$(document).ready(function(){
$('.link').attr('href', link+ID);
});
console.log(data.length);
html +="<tr>";
html +="<td>"+"<a class='link' href=''>Delete</a>"+"</td>";
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
the ID on the link is not changing its just displaying a single ID=6
Solution
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = `management.php?delete=${ID}`;
html +="<tr>";
html +=`<td><a href='${link}'>Delete</a></td>`;
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
but i'm getting error messages in NetBeans IDE 8.0.2 like
Expected an operand but found error
`var link== `management.php?delete=${ID}`;`
Expected an operand but found error
`html +=`<td><a href='${link}'>Delete</a></td>`;`
Expected eof but found error ` }`
Try a Template Literal like so:
var link = `management.php?delete=${ID}`;
And if you want it on the html
html +=`<td><a class='link' href='${link}'>Delete</a></td>`;
Please note that I'm using the back ticks `
More info here
Before selecting a HTML element you have to create it. After creation you can manipulate.
I have a Laravel 5.5 project
In the app service providers I have shared some variables like this:
public function boot()
{
View::share('path', 'laravel/public');
}
I can access it in every view blade very easily.
But I have ajax search and it comes from a separated JS file included in the master layout.
<script src="{{ asset('style//js/searchajax.js')}}"></script>
This is the searchajax.js code
var path = '/laravel/public/';
$("#userSearchAjax").bind('change keyup',function(){
var userSearchAjax = $(this).val().trim();
if(userSearchAjax != '')
{
$.ajax({
type:'GET',
url: '/laravel/public/userssearchajax',
data: {userSearchAjax:userSearchAjax},
success:function(data){
var result = "<tr class='info'><td>اسم المستخدم</td><td>الصورة</td></td><td>البريد الالكتروني</td></td><td>رقم الهاتف</td></td><td>الفرع</td></td><td>اعدادات</td></tr>";
for(i = 0;i<data.length;i++)
{
result+= "<tr class='warning'><td>"+data[i]['user_name']+"</td>";
result+= "<td>";
result += "<a data-title='"+data[i]['user_name']+"' data-lightbox='image-1' target='_blank' href='"+path+"uploads/users/"+data[i]['id']+"/"+data[i]['id']+".jpg'><img alt='"+data[i]['user_name']+"' title='"+data[i]['user_name']+"' src='"+path+"/uploads/users/"+data[i]['id']+"/"+data[i]['id']+".jpg' class='thumb' /><br /></a>";
result+= "</td>";
result+= "<td>"+data[i]['user_email']+"</td>";
result+= "<td>"+data[i]['user_phone']+"</td>";
result+= "<td>"+data[i]['user_department']+"</td>";
result+= "<td><a class='btn btn-success'>عرض</a>";
result+= "<a class='btn btn-info'>تعديل</a></td></tr>";
}
result += "";
$("#search-result").html(result);
}
});
}
else
{
$("#search-result").html("");
}
})
My problem is that I can't access the shared variable $path inside js file
even shared model like Auth and other default models in Laravel I cant access them inside the js file.
Thanks
<script>
var path= {!! $path !!};
</script>
I would also recommend changing the variable name to "public_path". There are other paths you could need.
This question was also similar to:
laravel-5 passing variable to JavaScript
You can set the path in your JS code by injecting the code using Blade like this {{$path}} or {{session('path')}} ... provided you have set the session('path') somewhere at right time and right place.
I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>
I have function that works with JSON.
function makeItem(data){
var tbl_body = "";
$.each(data, function() {
var id = parseInt(this.ProductId);
var tbl_row = "";
tbl_row += "<a href='article.php?cat=<?=$cat?>&subcat=<?=$subcat?>&id="+id+"'>";
tbl_row += "<div class='subCatImg'><img src='imagesDB/articles/<?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?>'></div>";
tbl_row += "<div class='subCatName'>"+this.ProductNameBG+"</div>";
tbl_row += "<div class='subCatText'>"+this.ProductNameBG+"</div>";
tbl_row += "</a>";
tbl_body += "<div class='categoryWrap'>"+tbl_row+"</div>";
})
return tbl_body;
}
The problem is that the variable id works only the first time - in the a tag but not in the second nor the third time.
Is it because the a tag is not immediately closed or because the second and the third time I'm trying to use it in php array. I'm sure that the array works because if I hardcore it(<?=$main[1]['dir]?>) the image is displayed(no need for quotation marks, I need integer).
The thing is that I have to make it dynamic so I can't just type some number.
Why does it work the first time but not the others?
You can convert your PHP array into a json object like this :
var main = <?php echo json_encode($main) ?>;
then iterate through it.
#epascarello is correct. PHP is server side, were JS is client side. Instead, try to do something like
UPDATED:
tbl_row += <?php print("\"<a href='article.php?cat=$cat&subcat=$subcat&id=\" + id + \"'>\""); ?>
tbl_row += <?php print("\"<div class='subCatImg'><img src='imagesDB/articles/$phpVal1/$phpVal2'></div>\""); ?>
tbl_row += <?php print("\"<div class='subCatName'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"<div class='subCatText'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"</a>\"");?>
In this, you will have to pass the value of the id and the dir from JS to php so php can parse it's multidimensional array. You'll notice that <?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?> has changed to $phpVal1/$phpVal2.
You can do this a number of ways - perhaps through a click of a button. But php will be done first, and then the JS.
In essence, you are getting all the values from the server (php) and forcing it to write the client side (JS) for you.
I am working on a script that copies a row ID from one table and creates a new table on the page with all rows that have been selected via checkbox in order to create a comparison table of selected results and I've run into an issue with the synergy between two of my ajax calls.
When the following row is created in the original table, the class that is assigned to the <a> element of that row triggers an ajax call which then populates a modal that shows up on the page with additional information.
This is the line
echo "<td><a id='$id' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
When the modal is triggered this way, the information populates just fine.
Now, within the script that populates the new table, I make a call to another separate script which re queries the selected row ids and sets the html.
Here is that portion of the script :
$('.compareCheck:checked').each(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'compare.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
dataType: "json",
success : function(data){
var row = "<tr class='removeRow'>";
row += "<td>" + data.provider_num + "</td>";
//HERE IS WHERE THE RE-CREATION OF THE MODAL CALL GOES \/
row += "<td><a id='" + ele_id + "' data-toggle='modal' href='#provmodal' class='push'>" + data.provider_name + "</a></td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['233_net_charity_care']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['291_cost_of_non_mcr_bad_debts']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['301_cost_of_uncomp_care']) + "</td>";
row += "<td style='text-align:right;'>" + ((data['233_net_charity_care']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "<td style='text-align:right;'>" + ((data['291_cost_of_non_mcr_bad_debts']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "</tr>";
$("#compareTable > tbody").append(row);
}
});
});
As you can see in my current implementation I am using the ele_id var, but I have also tried things like data.id and data['id']. All of which trigger the modal but produce no results from the php script.
Here are my two php scripts:
Script A: Populating the modal - (modalquery.php)
<?php
require_once("link_costreport_2013.php");
$id = $_POST['post_id'];
$modalquery = $link->prepare("SELECT * FROM s10 WHERE id = :id");
$modalquery->bindParam(':id', $id, PDO::PARAM_INT);
$modalquery->execute();
$modalresults = $modalquery->fetch();
print_r("<h4>State: ".$modalresults['state']."</h4>");
print_r("<h4>City: ".$modalresults['city']."</h4>");
print_r("<h4>Street: ".$modalresults['street']."</h4>");
print_r("<h4>Zip: ".$modalresults['zip']."</h4>");
print_r("<h4>County: ".$modalresults['county']."</h4>");
?>
and script B - The script that turns the re-query into values for the new comparison table (compare.php)
<?php
include_once('functions.php');
include_once('link_costreport_2013.php');
if(isset($_POST['post_id'])){
$id = $_POST['post_id'];
}
$query = $link->prepare("SELECT *
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
also in case it helps, here is my script for turning the .push class into a trigger for the ajax call which returns the modal content.
$(function(){
$('.push').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'modalquery.php', // in here you should put your query
data : 'post_id='+ ele_id, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success : function(r)
{
// now you can show output in your modal
$("#provmodal .modal-body").html(r).promise().done(function(){
$("#provmodal").modal('show');
});
}
});
});
});
I'm new to using ajax and jquery in this fashion so any insight at all would be excellent.
thanks in advance
:EDIT: Here is the output from json_encode($results) when ID = 1
{"id":"1","report_record_num":"548598","provider_num":"381301","provider_name":"COTTAGE GROVE COMMUNITY HOSPITAL","street":"1515 VILLAGE DRIVE","city":"COTTAGE GROVE","county":"LANE","state":"OR","zip":"97424-9700","cbsa":"21660","urban_or_rural":"Rural","ownership_type":"Voluntary, Nonprofit, Church","divider":"","divider2":"","1_cost_to_charge_ratio":"0.703459","2_net_rev_from_mcd":"3920096","3_recieve_sup_mcd_payments":"Y","4_include_if_yes":"N","5_dsh_or_sup_payments":"84890","6_medicaid_charges":"6192717","7_medicaid_cost":"4356323","8_dif_net_rev_and_cost":"351337","9_schip_net_rev":"0","10_stnd_alone_schip_charges":"0","11_stnd_alone_schip_cost":"0","12_diff_schip_rev_and_cost":"0","13_net_rev_from_state_local":"0","14_charge_under_state_law":"0","15_state_local_program_cost":"0","16_dif_between_net_rev_and_cost":"0","17_private_grants_and_donations":"6886","18_gov_grants":"0","19_tot_unreim_cost_mcd_schip_gov":"351337","201_tot_init_charity_for_uninsured":"593922","202_tot_init_charity_for_insured":"1072203","203_tot_init_charity_all":"1666125","211_cost_of_init_charity":"417800","212_cost_of_init_charity":"754251","213_cost_of_init_charity":"1172051","221_partial_pmt_charity_pat":"4385","222_partial_pmt_charity_pat":"8868","223_partial_pmt_charity_pat":"13253","231_net_charity_care":"413415","232_net_charity_care":"745383","233_net_charity_care":"1158798","241_charges_beyond_los_inc":"N","251_charges_beyond_los_lim":"0","261_total_bed_debts":"0","271_medicare_bad_debts":"79275","281_non_medicare_bad_debts":"-79275","291_cost_of_non_mcr_bad_debts":"-55767","301_cost_of_uncomp_care":"1103031","311_cost_of_unreim_and_uncomp":"1454368"}
:EDIT2: Ok, so I went back and took some pics of what is happening. Somehow my modal text is not appearing in the second table <a class="push"> element. Here are the pics:
!(http://imgur.com/xgsOzSy) - This is in the first table
!(http://imgur.com/uSsI3DM) - This is what happens in the second when the same link is pressed. I believe it's not triggering the ajax .push call.
Try changing:
$(document).on('click','.push',function(){
For:
$('.push').on('click', function(){
In the first case the event handler is added to every element with the "push" class that is present in the DOM at the moment of the execution of the "click" function. The second case, the one wich uses the "on" function, it adds the event handler to the elements already present and those which are not yet in the DOM, those which you create after the execution of the adition like the ones you add to the table.
Wish i make my self clear, i am trying to improve my english.