Continuously retrieving the send data in php via AJAX request - php

I face one problem while coding, the thing is that I want to retrieve the same data from the sending script to another one let me explain
<button type="button" name="btn_more" data-vid="<?php echo $product; ?>"
id="btn_more">Load more data</button>
<input type="hidden" name="category" value="<?=$category;?>" id="category">
I have to buttons first calls the ajax and passes the parameter, second one holds the data from database
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_product_id = $(this).data("vid"); //this stands for <button>
var cat=$("#cat").val(); //this one for hidden input
$('#btn_more').html("Loading...");
$.ajax({
url:"ajax/shopProduct.php",
method:"POST",
data:{last_product_id:last_product_id, category:category},
dataType:"text",
success:function(data) {
if(data != 'No rows') {
$('#remove_row').remove();
$('#load_data_table').append(data);
} else {
$('#btn_more').html("No results");
}
}
});
});
});
and here in shopProduct.php i get the post data
if($_POST) {
$let = filter_var($_POST["last_product_id"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
$category= filter_var($_POST["category"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
}
And based on these two values I make an SQL statement to retrieve data, and display some info as a output, and again show the load more button as
<div id="remove_row"><button type="button" name="btn_more" data-vid="<?php
echo $product; ?>" id="btn_more">Load more data</button></div>
The actual problem is that the $category value stops existing as the second click calls from other script. How can i continuously fetch $category value from the first script to the current one?

You are using wrong selector. Change this line -
var cat =$("#cat").val()
to
var category = $("#category").val()

Related

Get AJAX POST Using PHP

I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.

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.

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

ajax validation for multiple forms on page, all have same class

basically i am making a CMS and want to have in post editing.
How it works atm is that the blog post is echoed out (PHP) and there is a hidden ckeditor which when an edit button is clicked gets displayed. The edit button is then replaced with a save button.
This all works fine and good however the issue comes when saving the blog post.
the php works fine, and the ajax validation also works fine but ONLY when there is 1 blog post.
When there is more than 1 post the errors come. The issue is that it seems to be that the save post button is sending all of the data from every blog post. I checked it with the firebug net and saw that all data is being sent.
I just need a way of making it so that the save button in the form, only affects the data inside of that form. At the moment the error / success message is displayed by all of them.
Here is the post echoed out:
<div class="blogtest">
<form action="process/updatepost.php" class="updatepost" method="post">
<input type="button" class='.$editenabled.' value="Edit">
<input type="submit" class="saveupdatebutton" value="Save">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<div class="text">
<div class="buildtext">'.$text.'</div>
<div class="editor"><textarea name="ckeditor" class="ckeditor">'.$text.'</textarea></div>
</div>
</form>
</div>
This is the javascript:
$(document).ready(function(){
$(".updatepost").submit(function(){
$(".error").remove();
$(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var blogpost = $('.ckeditor').val();
// Validation
if (blogpost == '') {
check = false;
$('.ckeditor').after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $(".updatepost").serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$('.ckeditor').after('<div class="success">Post Updated</div>');
else
$('.ckeditor').after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for reading. Hope you can help.
You just need to limit the validation logic to the form that's actually being submitted. Right now $('.ckeditor').after('<div class="error">Text Is Required</div>'); is modifying all items that match the ckeditor class name. See below -- I've added a variable called $targetForm which grabs the form being submitted and modified the code appropriately to only reference the children of that form.
$(document).ready( function() {
$(".updatepost").submit(function() {
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckeditor.val();
// Validation
if (blogpost == '') {
check = false;
$ckeditor.after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$ckeditor.after('<div class="success">Post Updated</div>');
else
$ckeditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});

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