Ajax call with javascript not working - javascript

I want to try to get some value from page cart.php from and ajax call, but its not working.
Ajax code is below:
function temp_sell(id) {
//var p_id=document.getElementById('temp').value;
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: "value=" + p_id,
success: function (message) {
alert(message);
$("#your_cart").html(message);
}
});
}
temp_sell.php is below where I want to show some products details
<?php
include("connection.php");
echo $p_id = $_POST['value'];
$qty=1;
$query="SELECT * FROM product WHERE id='$p_id'";
$result=mysql_query($query);
while($data=mysql_fetch_array($result))
{
?>
<form>
<table>
<tr>
<img src="<?php echo "img/".$data['image'];?>"/>
<strong><?php echo $data['pro_name'];?></strong>
<strong><?php echo $data['price'];?></strong>
<input type="text" value="<?php echo $qty;?>"/>
</tr>
</table>
</form>
<?php
}
?>

p_id is undefined, you have commented the p_id value or change temp_sell(p_id).
function temp_sell(p_id)
instead of
function temp_sell(id)
Reference comments : Ajax call with javascript not working

Do this :
function temp_sell(id){
var p_id=document.getElementById('temp').value; // <--- uncomment this line
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: {value:p_id}, // <--- change this
success: function(message){
alert(message);
$("#your_cart").html(message);
}
});
}

Related

Pass an php array to another php file with ajax

I want to send an array, which I got from mysql, and send it with ajax to another php file. I can't send the data to the file. I get the data in the first PHP file. But when I set an alert with the array in JS then the output is undefined. The other PHP file didn't received any data.
PHP send to another PHP file
<?php
$id = $_GET['id'];
$items = mysqli_query($con,"SELECT * FROM COMPARISONFOLDER JOIN ITEM ON ITEM.COMPARISONFOLDER_ID LIKE COMPARISONFOLDER.COMPARISONFOLDER_ID WHERE COMPARISONFOLDER.COMPARISONFOLDER_ID LIKE $id");
while($item = mysqli_fetch_array($items)) {
$shuffledItems[] = $item;
}
shuffle($shuffledItems);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
getItems();
});
function getItems() {
var urlActiveFillSurvey = "https://vinkovic.ch/test1/activeFillSurvey.php/";
jQuery.ajax({
type: 'GET',
url: urlActiveFillSurvey,
data: {data : '<?php echo $shuffledItems ?>'},
processData: false,
contentType: false,
success: function(data) {
jQuery('.data').html(data.responseText);
},
error: function(data) {
jQuery('.data').html(data.responseText);
}
});
}
</script>
</head>
<body>
<div class="data"></div>
</body>
</html>
PHP File which should get the array
<?php
require ('../wp-blog-header.php');
$data = $_GET['data'];
echo "<table border='1'>
<tr>
<th>Item 1</th>
<th>Item 2</th>
</tr>";
echo "<tr>";
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($data[0]['ITEM']).'" width="500" height="auto"/></td>';
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($data[1]['ITEM']).'" width="500" height="auto"/></td>';
echo "</tr>";
echo "</table>";
data: {data : '<?php echo $shuffledItems ?>'},
is where the error is, change to
data: {data : '<?php echo json_encode($shuffledItems) ?>'},
or base64_encode or url_encode the json out put to make it url friendly

PHP not returning Ajax Call

I'm trying to send over the data from my textarea using an ajax call to my PHP file, but we aren't getting any response back from the PHP file.
<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>
<script>
$('#submit').click(function (e) {
e.preventDefault();
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php',
data: {area: info}
});
});
</script>
<?php
if (!empty($_POST['area'])) {
$success = json_encode('succes');
return $succes;
};
?>
-- # Answer # --
I thought I had already tried an echo in this piece of code, but I think I just missed the output on the webpage and thought it wasn't working.
<?php
if (!empty($_POST['area'])) {
echo "success";
};
?>
Thanks Mickael for the answer!
I completely forgot to add an echo to my code.
<?php
if (!empty($_POST['area'])) {
$succes = json_encode('succes');
echo $succes();
};
?>
Your ajax post :
$('#submit').click(function (e) {
e.preventDefault();
// information to be sent to the server
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php?return=1',
data: {area: info},
dataType:'json',
success:function(r){
console.log(r);
}
});
});
and your php response will be like
Php file:
<?php
if ( $_GET['return'] == 1 && isset($_GET['return']) ) {
echo json_encode('succes');
exit;
};
?>

change event not triggered from dynamic selection

Let me put this as simple as possible. I have a ajax call which loads the dropdown dynamically. I have another ajax call which is used to display details when any item is clicked.
Problem: I cant trigger the event of second ajax call.
If second ajax call is working it has to atleast display triggered when the change event happens. But the change event not even triggers.
Code:
First ajax call
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
Continued 2nd ajax call with closing php..
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$("#name").on('change',function (e) {
var name1 = this.value;
$.ajax ({
data:{name1: name1},
type: 'POST',
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
});
</script>
<?php } ?>
output from dataprod.php
dataprod.php for reference
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<?php
$name1 = $_POST['name1'];
echo $name1;
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
echo 'triggered';
?>

Using only one js file for multiple php ajax calls

First of all, my intention is to have 1 js file where there are multiple ajax calls. I want these ajax calls, which are php files, to have the same js file inside of it but not doing another request, which makes it to run slow after any click.
Some of my main php file:
<head>
<script src="<?php echo $_SESSION['url'] ?>js/direcinfo.js"></script>
</head>
<body>
<div class="direcciones">
<a href="javascript:void(0)" id="c_menu_direcciones" class="c-menu c_menu_direcciones">
<p>
Direcciones
</p>
</a>
</div>
<div id="cuenta_menu_direcciones" class="c-menu-content">
<h1>Direcciones de correo</h1>
<div id="expand_wrapper_dir">
</div>
</div>
</body>
Js file (direcinfo.js):
$('#c_menu_direcciones').click(function(){
$.ajax({
dataType: "html",
type: "POST",
url: "direcalias.php",
success: function(cntnt){
$("#expand_wrapper_dir").html(cntnt);
}
});
return false;
});
$(".alias-dir-a").click(function(){
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});
Ajax loaded file (direcalias.php)
<?php
session_start();
header("Content-Type: text/html; charset=ISO-8859-1");
include_once 'connection.php';
$conn = bbddconnect();
$email=$_SESSION['useremail'];
$query = "SELECT CODIDIR,ALIAS"
. " FROM CLIENTE C,DIRECCION D"
. " WHERE EMAIL LIKE '$email' AND C.CODICNT = D.CODICNT;";
$result3 = mysqli_query($conn,$query)or die(mysqli_error());
$recount = mysqli_num_rows($result3);
echo '<div class="menu-alias madir">';
for($i=0;$i<$recount;$i++)
{
$row = mysqli_fetch_array($result3);
echo '<div class="alias adir ali-'.$i.'">
'.$row['ALIAS'].'
</div>';
}
echo '<div class="alias adir ali-nuevo">
+
</div>
</div>
<div id="direc-content"></div>';
//echo '<script>'.
// 'var url = "'.$_SESSION['url'].'js/direcinfo.js";'.
// '$.getScript(url);'.
// '</script>';
?>
The problem I have is that when the direcalias.php file is called I need to call the js file again (edited part) because if I don't, it does not recognize when I click on $(".alias-dir-a").click(function()). Is what I want to do possible?
It beacuse you call .alias-dir-a before it create. you can use on method
$(document).on("click", ".alias-dir-a", function() {
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});

Jquery Toggle & passing data

I have created a toggle button with jquery but I need to pass my $id so it can execute the mysql in toggle_visibility.php.
How do I pass my variable from my <A> tag ?
<a class="toggleVisibility">Yes</a>
<script>
$("a.toggleVisibility").toggle(
function () {
$(this).html("No");
},
function () {
$.ajax({
type: "POST",
url: "toggle_visibility.php",
data: "id<?=$id; ?>",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(this).html("Yes");
}
);
</script>
It looks like $id is a PHP variable so when the server generates your page it will be printed at the right spot.
But you are missing a = in the string:
data: "id=<?= $id ?>",
If this is not what you want you have to clarify where $id comes from.
Update:
You have to integreate the ID somehow in the table row. E.g. you could set is as rel attribute for the link:
<tr>
<td class="date"><?php print $row['date']; ?></td>
<td><?php print $row['title']; ?></td>
<td class="visible">
<a class="toggleVisibility" rel="<?php echo $row['id']; ?>">Toggle</a>
</td>
</tr>
then you can fetch it in the function with jQuery's attr() method:
$("a.toggleVisibility").toggle(
function () {
$(this).html("No");
},
function () {
$.ajax({
type: "POST",
url: "toggle_visibility.php",
data: "id=" + $(this).attr('rel'),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(this).html("Yes");
}
);

Categories