ajax load shortcode in response [duplicate] - php

I have a form in a page-form.php file, on Sumbit i need to send the data to formResult.php to connect to db and get results (products IDs).
With Ajax in the form.php file i need to load the products IDs in a shortcode like that : [product id="1, 2, 3"].
form.php part of getting the result from DB :
while( $row = mysqli_fetch_assoc($result) ) {
echo $row["ID"]; // it does display the IDs in page-form.php
echo do_shortcode('[product id="'.$row["ID"].'"]'); // if i add this line, nothing is shown ... the problem is here
}
echo '</div>';
page-form.php part of getting the result from form.php
$(document).ready(function(){
$('#repeater_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"/formResult.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
$('#success_result').html(data);
}
})
});
});

Related

Load more button not working and showing all the records on the page

I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work

ajax add to cart using php and sessions

Similarly as in PHP Ajax add to cart not working my add to cart is also not working. I am trying to show the added product name, price, quantity and total price in <div id="mycart"> here </div> but it's not working and I am not getting any errors in console. Things that do work:
I get the success alert: Product has been added to cart
but it doesn't show up in my div.
Can anyone tell me what I am doing wrong?
My form on products.php
<form class="form-item" method="post" action="?action=add&id=<?php echo $row["id"]; ?>">
bla bla input
<input type="submit" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart">
My ajax.js
<script>
$('.form-item').on('submit', function() {
var id = $(this).attr("id");
var titel = $('#titel' + id).val();
var price = $('#price' + id).val();
var quantity = $('#quantity' + id).val();
$.ajax({
url:"cart-process.php",
method:"POST",
dataType:"json",
data:{
id:id,
titel:titel,
price:price,
quantity:quantity,
},
success:function(data)
{
$('#mycart').html(data);
alert("Product has been added to cart");
}
});
return false;
});
</script>
and my cart-process.php
<?php
session_start();
if(!empty($_SESSION['shopping_cart'])){
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $row){
$output .='<i class="ti ti-close"></i>';
$output .='<span>'.$row['titel'].'</span><span class="text-muted"> x '.$row['quantity'].'</span><br /> ';
$total = $total + ($row['quantity'] * $row['prijs']);
}
$output.='<br />Totaal:€ '.number_format($total, 2).'';
if (isset($_SESSION['shopping_cart'])){
if (count($_SESSION['shopping_cart']) > 0){
$output.='Cash payment';
$output.='Paypal payment';
}}
}
echo json_encode($output);
?>
You need to make two changes, first, tell your ajax function that you expect to receive html response:
$.ajax({
url:"cart-process.php",
method:"POST",
dataType:"html",
...
Second, do not try to json encode the PHP output, it is not json:
echo $output; // not json_encode($output);
I see it may be 3 problems
Ajax Call
$.ajax({
url:"cart-process.php", // script location
method:"POST", // if you use post, then get the values from $_POST
//dataType:"json", NO NEED
data:{
id:id, // this is how the array will be read
titel:titel,
price:price,
quantity:quantity,
},
success:function(data) //success call
{
$('#mycart').html(data);
alert("Product has been added to cart"); // even if no data is returned
//alert will be shown
}
});
return false;
Your are posting with an ajax/js script
Must obtain the variables from the $_POST array on server side, but on the server side i dont see when you are adding new product to your chart.
If you are saving the new product to the session
//as the var names on your js script will be preserved on php side
// you can just add it, if you dont needd to process this info
$_SESSION["shoping_cart"][] = $_POST;
//Now you use a loop to build the html
And here is where the third problem shows, your ajax call expects a JSON response and, php json_encoding the html response? no need, just echo $html; and on your js data = $html after the succesfull call, then add the html to the element,
$("#elementid .orclass").html(data)
Hope my answer helps you.

Get value from select with jquery

On my homepage (home.php) I have a first script who take some result of php page (test.php) and display on div #details-menu.
It's the list of "product" table from database.
After when result is selected, I would like to validate it and display on alert.
But it doesn't work... Some idea to help me ?
Here my code :
HOME.PHP (jquery code)
// First display the list of idcat
$(".displaymenu").on('click', function()
{
var idcat=1;
$.ajax({
type: "GET",
url: "test.php",
data: "idcat="+idcat+"",
success: function(msg){
$("#details-menu").html(msg);
}
});
});
// Second validate the choice after selected one product
$('#details-menu').on('click', '.validproduct', function() {
var idproduct=$(this).attr("choice_idproduct");
alert(idproduct);
});
HOME.PHP (html code) :
<div id="details-menu"></div>
TEST.PHP :
<?php
$idcat=$_GET['idcat'];
echo '<select id="choice_idproduct">';
$result = mysql_query("select * from myproduct where idcat='$idcat'");
while ($r_prod = mysql_fetch_array($result_prod))
{
echo '<option value="'.$r_prod['idproduct'].'">'.$r_prod['nameproduct'].'</option>';
}
echo '</select>';
echo '<div class="validproduct">VALIDATE</div>';
?>
You are trying to get an attribute of your div, what is not exists. #choice_idproduct is the child of the div, not an attribute.
Get the value of the select instead.
Try this:
var idproduct=$("#choice_idproduct").val();

Ajax display msg on submit without refresh

I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Categories