I am using Laravel framework. I get stuck on this. I get data successfully. But, when I want to display the data, it displays me data in array form. Can anyone help me how to display the Listing. I have one layout inside div
<div class="col-md-9 col-sm-9 col-xs-12" id="ajaxListings">
#include('layouts.publicLayout.get-listings')// here i have implemented layout
</div>
and
function filteredlistings(){
$.ajax({
url:'search-listings',
data:{
'service_name':title,
'location':location
},
type:"get",
success:function(allData)
{
$("#ajaxListings").html(allData);
},
error: function()
{
alert('error');
}
});
}
And here is my function :
public function search_listings(Request $request){
if($request->ajax()){
$data = $_GET;
$users = DB::table('users')
->join('business_services', 'users.id', '=', 'business_services.user_id')
->join('listings','users.id', '=', 'listings.user_id')
->select('users.id', 'business_services.name', 'business_services.list_id','listings.location')
->where(['business_services.name'=>$data['service_name'],'users.service_name'=>"Seller"])
->where('listings.location','like','%'.$data['location'].'%')
->get();
$users = json_decode(json_encode($users),true);
foreach($users as $alluser){
$ids[] = $alluser['id'];
}
$allData="";
if(!empty($ids)){
$allData = User::with('listings')->whereIn('id',$ids)->get();
$allData = json_decode(json_encode($allData),true);
}
$title = "Nails";
echo "<pre>"; print_r($allData); die;
}
}
Iguess that you want to return the layout + the data, so you could use :
return view('layouts.publicLayout.get-listings',compact('allData'));
Instead of :
echo "<pre>"; print_r($allData); die;
You could access your data inside the layout using $allData.
Hope this helps.
The issue is this:
echo "<pre>"; print_r($allData); die;
Instead of print_r, return the data as JSON so that it can be parsed by jQuery:
return response()->json($allData);
Then in your jQuery success function you can iterate over the data
success:function(allData)
{
// simple example showing the firstnames
var example = '';
$.each(allData, function(){
example += ', ' + this.firstname;
});
$("#ajaxListings").text(example);
},
Related
I've been banging my head against the wall for 2 days now, searching back and forth for solution for this problem, please enlighten me with this one:
I have this JavaScript Code that include a blade file and pass a data through it.
const loadTemplate = (locationinfo) => {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
#include('pages/business-space/templates/t1',[
'locationinfo'=>'${JSON.stringify(locationinfo)}', //this is the code
])
</div>`;
return info;
}
When I log JSON.stringify(locationinfo) in my console it is just a plain json string:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
In my t1.blade.php if I echo the locationinfo variable it still displays the same:
echo $locationinfo;
//and the result:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
But When I tried to decode it using json_decode it becomes null. Here is my code:
$arr = json_decode($locationinfo); //this is null
foreach ($arr as $key => $value) {
echo $key;
}
Another Error:
$arr = json_decode($locationinfo, true);
foreach ($arr as $key => $value) {
echo $key;
}
//error: foreach() argument must be of type array|object, null given
Why is this happening? Thanks in advance.
First make sure that $locationinfo is exactly a json string. I suspect it is a php associative array.
Try echo $locationinfo['id'];. If value appears u don't want to decode it. Use
$locationinfo directly withot json decode.
If it is a json, Try using like this,
$arr = json_decode($locationinfo, true);
Add a stripslashes.
$data = json_decode(stripslashes($data),true);
Demo : http://codepad.org/XX9QD3iX
Answered here : https://stackoverflow.com/a/37599821/19168006
Edit : example in demo has stdClass error, this is the working one :
http://codepad.org/lfJJu5yA
you can't pass js data to php ,because php renderd first.
but
you can call ajax and return blade to response
your ajax call
const loadTemplate = (locationinfo) => {
$.ajax({
data: {
'locationinfo': locationinfo,
},
type: "post",
url: "{{route('someRoute')}}",
success: function (data) {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
${data}
</div>`;
return info;
},
error: function () {
//has error
}
});
}
your route
Route::get('/getAjaxData', [AjaxController::class,'show']) ->name('someRoute'); // but i use __invoke controller
your controller
<?php
namespace YOUR_NAMESPACE;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function show(Request $request)
{
$data = $request->input('locationinfo');
return view('pages/business-space/templates/t1')->with([
'locationinfo' => $data,
]);
}
}
I am trying to show some records from my table columns named tid and ketprob by showing Modal when clicking on a link. The modal and query looks fine (checked by echoing last_query), but the modal is showing no data... Please help me :(
JS Code:
$('#showdata').on('click', '.item-info', function(){
var tid = $(this).attr('data');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>repeatproblem/infoReprob',
data: {tid:tid},
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
},
error: function(){
alert('Gagal Info Kode Error!');
}
});
});
My Controller:
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
My Model:
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
You are using return $query->row(); syntax in your model if this condition is true: $query->num_rows() > 0, so that means your model will return the object representation of the first row of the query and the $result variable in your controller below will be an object with two properties: tid and ketprob
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
Now have a look at your ajax call success callback function
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
}
Since your controller above uses echo json_encode($result); syntax, your ajax call will return the json representation of $result variable and the data variable in your success callback function above will be like below
{ "tid": "1", "ketprob": "abc" }
The problem is, data.length in your ajax success callback function will be undefined because data isn't an array, so the for loop won't be executed and html will be an empty string, see this jsfiddle. That's why your modal is showing no data.
To fix the problem, I'd suggest changing your model code as below
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
return $query->result();
}
By using return $query->result(); syntax, your model will always return an array of object. As the result, your ajax call will return a json like this
[ { "tid": "1", "ketprob": "abc" } ]
which is a json array, so data.length in your ajax success callback function won't be undefined and your modal will show the data. See this jsfiddle, you'll see that the html variable is not empty.
I guess you should use echo $query->row(); instead of return $query->row();.
Solved by changing return $query->row(); to return $query->result();
Going to learn about this. Or can anybody tell about the different.. Thanks
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
I am trying to make a user search system like facebook using ajax and php json. But i have one problem.
From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like
<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>
but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.
JS
$('body').delegate('#searchkey','keyup', function(){
clearTimeout(timer);
timer = setTimeout(function(){
var box = $('#searchkey').val();
contentbox = $.trim(box);
var dataString = 'keys=' + contentbox;
if(contentbox !==''){
$.ajax({
type: "POST",
url: siteurl +"requests/search.php",
data: dataString,
dataType:"json",
cache: false,
beforeSend: function(){},
success: function(data){
$('.un').html(data.username);
$('.uf').html(data.fullname);
}
});
}
});
});
search.php
<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
$keys = mysqli_real_escape_string($db, $_POST['keys']);
$keyRestuls = $WidGet->SearchUser($keys);
if($keyRestuls) {
// If array is in data
foreach($keyRestuls as $datas) {
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
echo json_encode( $data );
}
}
}
?>
SearchUser function is here
public function SearchUser($keys){
$keys = mysqli_real_escape_string($this->db, $keys);
$result = mysqli_query($this->db,"SELECT
username,
uid,
fullname FROM
users WHERE
username like '%{$keys}%' or fullname like '%{$keys}%'
ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
Your PHP script is generating a malformed JSON
{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}
It shoulds generate
[
{"username":"marc1","fullname":"Marc Zuckerberg"},
{"username":"marc3","fullname":"Marc Zeyn"},
{"username":"marc2","fullname":"Marc Alp"},
]
You can fix it by appending to an array instead of writting each row independamently
foreach($keyRestuls as $datas)
{
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data[] = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
}
echo json_encode( $data );
And then you'll have to loop over $data in your JS, I suggest you use $.each
function success(data) {
$.each(data, function(key, value) {
console.log(value.username + ": " + value.fullname);
})
}
I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help
I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);