I'm trying to send a PHP variable to JavaScript using AJAX and implementing to HTML, but the result doesn't show anything.
My HTML code:
<div class="contain" id="konten_data"
style="margin-top: 20px;"></div>
My JavaScript code:
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=tdepan&id='+id,
success:function(html){
$('#konten_data').html(html);
}
});
}
My PHP code (userAction.php):
($_POST['action_type'] == 'tdepan'){
$link = mysqli_connect("localhost", "root", "", "universitas");
$datas = mysqli_query($link, "SELECT * FROM mahasiswa where user='john' ");
if(!empty($datas)){
while ($datak = mysqli_fetch_assoc($datas)){
echo '<div class="row" style="margin-left: -90px;">
<div class="col-xs-6 col-sm-6 col-md-4">
<img class="img-thumbnail img-responsive"
src="images/test/'.$datak['gmb_batik'].'" alt=""></div>
<div class="col-xs-12 col-md-8">
<div class="content-box-large">
<p>'.$datak['desc_batik'].'</p>
</div>
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-4 col-md-offset-3">
<div class="content-box-large">
<h1 >asal <strong>'.$datak['asal_batik'].'</strong></h1>
</div>
</div>
<div class="col-xs-16 col-sm-6 col-md-2 col-md-offset-1">
<img class="img-thumbnail img-responsive"
src="login/admin/files/qrcode/'.$datak['qr_batik'].'"
alt="">
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-9 col-md-offset-4">
<div class="content-box-large">
<p>'.$datak['pola_batik'].' </p>
</div>
</div>
</div>';
}
}else {``
echo '<tr><td colspan="5">No user(s) found......</td></tr>';
}`
}
I don't know what is wrong, I hope somebody can help me.
Try to change the javascript code to
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: {action_type: "tdepan", id: id},
success:function(html){
$('#konten_data').html(html);
}
});
}
As you can see, data is passed as an object instead of a string.
Also, be aware that if no user was found, you are putting a <tr> inside a <div>.
try to change in your ajax call.
function tampilDepan(id){
var postData ={"action_type":tdepan,"id":id};
$.ajax({
type: 'POST',
url: 'userAction.php',
data: postData ,
success:function(html){
$('#konten_data').html(html);
}
});
}
try to use the format below in calling ajax:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{ "action_type":"' + tdepan + '", "id":"' + id + '"}',
url: 'userAction.php',
success: function (data) {
conosle.log(data);
},
error: function (error) {
console.log(error);
}
});
You are trying to get your data using konten_data probably by using jQuery selector $('#konten_data').val();
, but I don't see it in the PHP code as where you are pushing the data to render onto the DOM. Try setting the value of konten_data by adding an element before the success callback or on DOM render and you should be good from there.
Related
I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code
I'm trying to add some additional data to a form in my laravel blade using js and ajax post, but I can't get the form to submit. I've stripped everything else out to try to find what's wrong, but I'm mystified. Can anyone help?
My blade looks like this;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-md-6 mt-5 mb-2">
<div class="card">
<div class="card-body">
<form id="payment-form">
<button id="card-button" class="btn btn-lg btn-block btn-success">
<span id="button-text"><i class="fas fa-credit-card mr-1"></i>{{ __('Add Payment Method') }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('javascript')
<script>
const cardButton = document.getElementById('card-button');
var form = document.getElementById('payment-form');
cardButton.addEventListener('click', function(event) {
// event.preventDefault();
console.log('On click check');
var payment = '1234';
$.ajax({
type: "POST",
url: "/payment-post",
data: {
payment: payment,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
});
});
</script>
#endsection
You have to use like this
var payment = '1234';
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: "{{url('')}}/payment-post",
dataType: "text",
data: {
payment: payment,
_token: CSRF_TOKEN
},
success: function (response) {
//Do something
}
});
In the end I tracked this down to 'defer' being present in the script tag in the header, which was stopping all the event listeners from working. Once I changed it to this
<script src="{{ asset('js/app.js') }}"></script>
everything working fine.
I have a code that take the value from SharePoint List using REST (ajax), as shown as below:
function getItems() {
$.ajax({
async: true,
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Network Tech')/items",
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function(data) {
data = data.d.results;
console.log(data);
$.each(data, function(index, value) {
var value = value.Service;
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
}
I also have a HTML code for the web page, as shown as below:
<body>
<div class="container">
<div class="col-sm-1">
<h3><br><br>Networking<br></h3>
<div class="panel-group wrap" id="bs-collapse">
<div class="panel">
<div class="panel-heading panel-bg-1">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#" href="#0101" id="v1">Virtual Networking<br></a>
</h4>
</div>
<div id="0101" class="panel-collapse collapse">
<div class="panel-body">
Coming Soon
</div>
</div>
</div>
</div>
</div>
</div>
</body>
Right now I want to take the value from SharePoint List and display it inside the panel-body. I know how to display it on table but I don't know how to do it on this one. Please help me on this.
You can use this Library that developed by me. Get Here
Then you need to do small callback
var appUrl = GetUrlKeyValue("SPAppWebUrl");
var hostUrl = GetUrlKeyValue("SPHostUrl");
var list = SPMagic.ListManager(appUrl, hostUrl, "Network Tech");
list.getAllListItems("Id", 100,).then(function (res) {
console.log(res.d.resutls);
}, function(err){
console.log(err);
}
Then you can use KnockoutJS to do the Bindings for the table.
I have a homepage where there is a menu with some categories and below there are the latest posts:
<ul class="Categories__Menu">
#foreach($categories->take(6) as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
<div class="row" id="posts">
#foreach($posts as $post)
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
#endforeach
</div>
I want that when each category is clicked to show only the posts of that category in the homepage, but in the same homepage, not in a specific category page.
So I have this Ajax:
$(function() {
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
$('#posts').append("<p>"+postObj.name+"</p>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
});
And its working fine, but instead of show just this:
$('#posts').append("<p>"+postObj.name+"</p>");
I want to show the posts with the real html above like:
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
So Im using like this in ajax:
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
alert(category_id);
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
//$('#posts').append("<p>"+postObj.name+"</p>");
$('#posts').append("<div class=\"col-12 col-sm-6 col-lg-4 col-xl-3 mb-4\">\n" +
" <div class=\"card box-shaddow\">\n" +
" <img class=\"card-img-top\" src=\"{{postObj.image}}\" alt=\"Card image cap\">\n" +
" <h5 class=\"card-title h6 font-weight-bold text-heading-blue\">{{postObj.name}}</h5>\n" +
" <div class=\"card-footer d-flex justify-content-between align-items-center\">\n" +
"\n" +
" More\n" +
" </div>\n" +
" </div>\n" +
" </div>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
But it appears an error:
Use of undefined constant postObj - assumed 'postObj'
Do you know why?
PostController:
public function WhereHasCategory(Request $request)
{
$posts = Post::whereHas('categories', function ($categories) use (&$request) {
$categories->where('id',$request->id);
})->get();
return response()->json($posts);
}
Route to the ajax part:
Route::get('posts/where/category/{id}','\PostController#WhereHasCategory')->name('category.posts');
Method to return the homepage view:
public function index(){
return view('home')
->with('categories', Category::orderBy('created_at', 'desc')->get())
->with('posts', Post::orderBy('created_at','desc')->take(8)->get());
}
Make sure you refer to variable in Blade template with $postObj, not postObj. I can see you use it without $, like postObj.image in your tag.
Let's say my json like this and i have 3 different data
[
{
"Pair":"",
"Id":"8ca2df56-2523-4bc3-a648-61ec4debcaaf",
"PubDate":"/Date(1463775846000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"74b2d7c7-bc2c-40ee-8245-7c698befa54d",
"PubDate":"/Date(1463775247000)/",
"Provider":null,
"Market":""
},
{
"Pair":"",
"Id":"0ee3cd96-1df8-49ba-b175-7a75d0840973",
"PubDate":"/Date(1463773687000)/",
"Provider":null,
"Market":""
}
]
What I already try
JQUERY
$.ajax({
type: 'GET',
url: 'news.json',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
$.each(data, function(index, element) {
$( ".content-news h3" ).append( data[0].Title );
**/** Stuck Here and it only call 1 data but i already use each function **/**
});
}
});
HTML
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle"> **/** I Want to Show Id Here **/** </h3>
<h4 id="jprovider" class="author">**/** I Want To Show PubDate **/**</h4>
<p id="jsummary">
**/** I Want to Show Provider Here **/**
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
JSFiddle
I managed to out only 1 result. Can you guys give a hint or tips show me how to templating jquery using json. Please be easy on me. Thanks
THIS IS THE RESULT WHAT I GET RIGHT NOW, Only 1 data display..
You can access the properties via the index on the data property as so:
$.ajax({
type: 'GET',
url: 'news.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Which produces
8ca2df56-2523-4bc3-a648-61ec4debcaaf /Date(1463775846000)/ null
74b2d7c7-bc2c-40ee-8245-7c698befa54d /Date(1463775247000)/ null
0ee3cd96-1df8-49ba-b175-7a75d0840973 /Date(1463773687000)/ null
To handle the templating you can create a function that returns the markup for each item:
function template(title, provider, summary) {
var $temp = $('<div/>');
$temp.append($('<h3/>', {
text: title
}));
$temp.append($('<h4/>', {
text: provider,
class: 'author'
}));
$temp.append($('<p/>', {
text: summary
}));
console.log($temp);
return $temp;
}
$.ajax({
type: 'GET',
url: 'https://cdn.rawgit.com/enki-code/4ec2b6efa84dfed8922b390d2a1a4c5a/raw/dc94405f12d1d5105e54584a6c53ca30d1863b4a/so.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function(data) {
//console.log(data);
$.each(data, function(index, element) {
$('.content-news').append(template(data[index].Id, data[index].PubDate, data[index].Provider));
console.log(
data[index].Id,
data[index].Pair,
data[index].PubDate,
data[index].Provider,
data[index].Market
);
});
}
});
Here is an updated version of your fiddle as an example.
You'll likely have to make a few small adjustments to the CSS and whatnot to get it looking how you like.
you json file have array of objects so first you need to loop for the objects one by one
also don't use each for serialized array cause it takes more time just use the normal for loop
answer is here jsfiddle.net/robert11094/65zjvy5k/3
or just use this html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://subscriptions.fxstreet.com/json/news.aspx?c=A0DC975D13C44CE697EC&i=englishnewscharts',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log(data);
for (var i=0;i<data.length;i++){
var html=
'<div class="ano">'+
' <div class="content-news">'+
' <h3 id="jtitle"> '+data[i].Id+' </h3>'+
' <h4 id="jprovider" class="author">'+data[i].PubDate+'</h4>'+
' <p id="jsummary">'+
data[i].Provider+
' </p>'+
' <div class="img-head" id="img-container">'+
' <!-- <img src="" alt="img" class="img-responsive">-->'+
' </div>'+
' </div>'+
' <div class="social-control">'+
' <div class="head-control">'+
' <p id="jdate" class="inline gray"></p>'+
' <p class="pull-right">show more</p>'+
' </div>'+
' <div class="clear"></div>'+
' <div class="footer-control">'+
' <p><i class="ion-ios-heart ion-spacing"></i>20</p>'+
' <p><i class="ion-chatbox ion-spacing"></i>2 comments</p>'+
' <p><i class="ion-android-share-alt ion-spacing"></i>share</p>'+
' </div>'+
' </div>'+
'</div>';
$('.news').append(html);
}
}
});
});
</script>
<div class="news">
<div class="ano">
<div class="content-news">
<h3 id="jtitle">Hello World</h3>
<h4 id="jprovider" class="author">David</h4>
<p id="jsummary">
This is content
</p>
<div class="img-head" id="img-container">
<!-- <img src="" alt="img" class="img-responsive">-->
</div>
</div>
<div class="social-control">
<div class="head-control">
<p id="jdate" class="inline gray"></p>
<p class="pull-right">show more</p>
</div>
<div class="clear"></div>
<div class="footer-control">
<p><i class="ion-ios-heart ion-spacing"></i>20</p>
<p><i class="ion-chatbox ion-spacing"></i>2 comments</p>
<p><i class="ion-android-share-alt ion-spacing"></i>share</p>
</div>
</div>
</div>
</div>
Try to use $.parseJSON or $.getJSON. It will be easier to find problems.
Reference: jQuery API