How to USE GET method with jQuery - javascript

I cannot get a value of $id_pinjam = #$_GET['id_pinjam']; here's PHP code
<?php
include '../../inc/koneksi.php';
$id_pinjam = #$_GET['id_pinjam'];
$tgl_kembali = date("Y-m-d");
$queryResult = $db->query("SELECT * FROM detail_pinjam WHERE id_pinjam = '$id_pinjam'") or die($db->error);
echo $id_pinjam."<br>";
while($fetchData = $queryResult->fetch_assoc()){
echo "<tr>
<td class='text-center'>".$fetchData['id_detail']."</td>
<td class='text-center'>".$fetchData['id_pinjam']."</td>
<td class='text-center'>".$fetchData['kode_pustaka']."</td>
<td class='text-center'>".$fetchData['tgl_jatuh_tempo']."</td>
<td class='text-center'></td><td class='text-center'></td></tr>";
}
?>
Here's jQuery code(to load data):
loadDataPinjam();
function loadDataPinjam(){
var dataHandler = $("#load-data-pinjam-here");
dataHandler.html("");
$.ajax({
type : "GET",
data : "",
url : "proses/pinjam/getDataPinjam.php",
success : function(result){
var resultObj = JSON.parse(result);
$.each(resultObj,function(key, val){
var newRow = $("<tr>");
newRow.html("<td class='text-center'>"+val.no_anggota+"</td><td class='text-center'>"+val.nama+"</td><td class='text-center'>"+val.alamat+"</td><td class='text-center'>"+val.id_pinjam+"<td class='text-center'>"+val.tgl_pinjam+"</td><td class='text-center'>"+val.jml_pinjam+"</td><td class='text-center'>"+val.status+"</td><td style='width: 20px;'><a href='?page=kembali&id_pinjam="+val.id_pinjam+"'><img src='img/return.png' class='icon'></a><input type='hidden' name='getIdPinjam' id='getIdPinjam' value='"+val.id_pinjam+"'></td>");
dataHandler.append(newRow);
});
}
});
}
and when i click link, GET parameter is not set, but when i set $id_pinjam manually than code is working. Help me to identify issue?

I think the problem is that you are sending nothing via Ajax.
Try:
url : "proses/pinjam/getDataPinjam.php?id_pinjam=YourValue",

You can use below 2 methods for GET method in jQuery
1. Use $.get method
Please check below link for reference:
https://api.jquery.com/jquery.get/
$.get("test.php", {number: numValue} , function(data){
// Display the returned data in browser
});
2. Standard $.ajax method
$.ajax({
method: "GET",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function( data ) {
alert( "Data : " + data );
});
As per your above sample code you need to pass parameters while you call ajax method

Related

Pass variable string from javascript to php using ajax

How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.

Not able to POST Variable to Another Page (PHP, Javascript, AJAX)

I have a while loop (inside the "searchvessel.php") that display the content of a query and have a button "upgrade" for each record of that query.
`while($fetch = $read->fetch_array()) {
?>
<tr>
<td id="1" style="display:none;"><?php echo $fetch['VesselID']?></td>
<td id="2"><?php echo $fetch['VesselName']?></td>
<td><input type="submit" class="button" name=<?php echo $fetch['VesselID']; ?> value="Upgrade"/></td>
</tr>`
This "Upgrade" button when click will call to a Javascript code that use the value inside the tag name to pass to another page using AJAX.
<script type = "text/javascript">
$('.button').click(function(){
alert($(this).attr('name'));
$.ajax({
type: "POST",
data: {
name: $(this).attr('name')
},
url: "vesselrecord.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
complete: function(){
window.location.href = "vesselrecord.php";
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
</script>
I were able to prompt/alert the value of vessel identification using the "alert($(this).attr('name'));" then
Move/Transfer to the "vesselrecord.php
But inside the "vesselrecord.php" there is no value in the $_POST['name']. Looks like there is an issue on my ajax code. Can you guide me on this? TIA.
Below is my code inside the "vesselrecord.php"
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vessel_id = strip_tags($_POST['name']);
}
When you change the location of the window, you make a $get request not $post, that is why you are not getting any value $_POST['name'].
You can change the location from-
window.location.href = "vesselrecord.php"
to-
window.location.href = "vesselrecord.php?myquerystringdata=" + $(this).attr("name");
and then on you php file you can write code to get value from query string.
'name' is nested within 'data'. Maybe you need to access data.name? I'm more used to JS than PHP so I'm not sure how to express this. Hope this helps.
data:{
name:'Al'
}

How to get another page on ajax?

I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case

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.

Set session when clicking html link?

I have searched and tested different solutions all day without luck. In the below code I want (when clicked) to set a session on the "open" links I echo in the foreach loop. I tried using AJAX but I am new to AJAX and could not make it work. I know how to do it using GET but it is too risky, so i welcome your suggestion and preferably examples.
$task_array = array_combine($task_id_unique, $task_status);
foreach ($task_array as $card_nr => $card_status) {
?>
<table>
<tr>
<th>card nr.</th>
<th>Status</th>
</tr>
<td><?php
echo $card_nr;?></td>
<td>
<?php
if ($card_status == true) {
echo "<a href=workcard.php>Open</a>";
}
else echo "Done ". $card_nr;?></td>
</table>
What have you tried and what doesn't work, because this looks like what you need...
HTML:
Register Now!
PHP:
if(isset($_GET['a'])){
$_SESSION['link']= 'whatever';
}
And if you need to do it without a page refresh, then use AJAX.
You should use ajax on click of link:
$.ajax({
url: 'test.php',
dataType: 'json',
type: 'post',
data: {name: "value", name2: "value2" /* ... */},
success: function (data) {
}
});
in your test.php, $_POST['name'] is equal to "value". and there you can do everything you want.
first, add html class on "Open" link and custom html5 attribute to store your card data. for example data-card.
Open
next, create Onclick event for a link to send an ajax request.
$( document ).ready(function() {
$(".your-class").click(function() {
var card_nr = $(this).attr('data-card');
$.ajax({
url: "workcard.php",
type: "POST",
data: "card=" + card_nr
}).done(function() {
// do something
});
return false;
});
});

Categories