I have checked all related questions on SO, but still looking for the best answer.
I am coding a review system where anyone can comment and logged in users can like their review (Like or undo their like only ...not dislike).
For that, I am using a checkbox and onClick call an ajax function that will like the review and if click again it will undo the action.
problem
Initially, When someone like the review, ajax call will like it and on Success it will change attr onClick to unlike(); function but again when i click on it it does not work fine...
MY TRY
<?php if($review['is_liked']){ ?>
<input type="checkbox" name="review_like" id="<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>" checked="checked" onclick="unlike(<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>);" />
<?php } else { ?>
<input type="checkbox" name="review_like" id="<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>" onclick="like(<?php echo $review['review_id'] . '-' . $review['customer_id'] . '-' . $review['product_id']; ?>);" />
<?php } ?>
And JS (id passing to JS func looks like 1105-249532-18117)
<script>
function unlike(id){
console.log('unlike');
var id2 = toString(id).split('-');
console.log('Unlike: '+id);
console.log('split id: '+ id2);
$.ajax({
url: 'index.php?route=product/product/like_review',
type: "get",
data: {
'is_liked': 1,
'review_id': id[0],
'customer_id': id[1],
'product_id': id[2]
},
dataType: 'json',
success: function(json) {
console.log(json);
$('.btn-thumbs-up').find('input[type=checkbox][name=review_like]').attr("onclick","like(id);");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
function like(id){
console.log('like');
console.log('Liked: '+id);
var id2 = toString(id).split('-');
console.log('split: '+id2);
$.ajax({
url: 'index.php?route=product/product/like_review',
type: "get",
data: {
'is_liked': 0,
'review_id': id[0],
'customer_id': id[1],
'product_id': id[2]
},
dataType: 'json',
success: function(json) {
console.log(json);
$('.btn-thumbs-up').find('input[type=checkbox][name=review_like]').attr("onclick","unlike(id);");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
the id i am passing to like/unlike function is not working fine in console and also split function even use toString func or wdout...
Please fix this or suggest better way to do this task...
You could handle it at client side with simpler conditions. Change the <input> tag to:
<input type="checkbox" name="review_like" data-id="<?php echo $review['review_id']; ?>" data-customer="<?php echo $review['customer_id'] ?>" data-product="<?php echo $review['product_id']; ?>" checked="<?php echo ( $review['is_liked'] ? "checked" : ""); ?>" />
And add this jQuery script to handle the checkbox change:
$('input[name="review_like"]').change ( function ()
{
$.ajax (
{
url: 'index.php?route=product/product/like_review',
type: "get",
data:
{
'is_liked': $(this).prop('checked'),
'review_id': $(this).data ( 'id'),
'customer_id': $(this).data ( 'customer'),
'product_id': $(this).data ( 'product')
},
dataType: 'json',
success: function ( json)
{
console.log ( ( $(this).prop('checked') ? 'Unliked' : 'Liked') + ' review ' + $(this).data ( 'id') + ', customer ' + $(this).data ( 'customer') + ', product ' + $(this).data ( 'product'));
},
error: function ( xhr, ajaxOptions, thrownError)
{
alert ( thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
Related
I have a php code that post value using ajax to another php page , but the value provided is not reflecting in UI nor in console .
$(document).ready(function() {
$('#CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
// perform actions for each file found
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" id ="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
?>
So when i give console.log in function and onclick , it returns value but when i try to pass CustomerName , it just returns null .
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "<script>console.log('Customer Name: " . $lat . "');</script>";
echo "<script>console.log('ENVIRON: " . $pat . "');</script>";
?>
Here is output i get :
Change id to class for CustomerName , I have added/ changed your code, see if it helps to solve your problem.
$(document).ready(function() {
// changed # to . for class
$('.CustomerName').click(function() {
customername = $(this).text();
load_data(customername);
// console.log(customername); // works
});
function load_data(Customername) {
// console.log(Customername); // works
$.ajax({
url: "getvalueafterclick.php",
method: "POST",
data: {
Customername: Customername,
EnvironmentType: "BA"
},
success: function(data) {
$('#result').html(data);
// console added to check what it is giving
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
}
});
<?php
//your code
// perform actions for each file found
// here in link change id to class for customer name
foreach (glob("CustomerConfigFiles/*.json") as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.substr(substr($filename,20), 0, -5).'</a>';
}
// my testing code
$data =["a","b","c","d","e","f","g","h"];
// perform actions for each file found
// here in link change id to class for customer name
foreach ($data as $filename) {
echo ' <a href="#" class="CustomerName" class="mm-active">
<i class="metismenu-icon pe-7s-rocket"></i>'.$filename.'</a>';
}
?>
getvalueafterclick.php
<?php
$pat =$_POST['EnvironmentType'];
$lat =$_POST['Customername'];
echo "Customer Name:" . $lat . "-";
echo "ENVIRON: " . $pat ;
?>
Value changed to null in ajax after updating the shipping city value from text field. I don't known what is the problem.. please help me Friends.
my php code:
public function updateshippingcity() {
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$json['new_shipping_city'] = $this->request->post['shipping_city'];
$this->db->query("UPDATE " . DB_PREFIX . "order SET shipping_city = '" . $this->db->escape($this->request->post['shipping_city']) . "' WHERE order_id = '" . (int)$this->request->get['order_id'] . "'");
$this->response->setOutput(json_encode($json));
}
}
my ajax code :
<script type="text/javascript">
$("#update-shipping-city").click(function() {
var name_val = $('input[name="new_shipping_city"]').val();
$.ajax({
url: 'index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>',
type: 'post',
dataType: 'json',
data: {
shipping_city: name_val
},
beforeSend: function() {
$('#update-shipping-city').attr('disabled', true);
},
complete: function() {
$('#update-shipping-city').attr('disabled', false);
},
success: function(json) {
}
});
alert("shipping city has changed");
});
my html code:
<div class="col-md-12">
<input name="new_shipping_city" value="<?php echo $shipping_city; ?>"></input>
<button id="update-shipping-city" > update </button>
</div>
I had achieved finally by post method.
<script type="text/javascript">
$(function() {
$("#update-shipping-city").click(function(e) {
e.preventDefault();
var scity_val = $('input[name="new_shipping_city"]').val();
$.post("index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>", {
shipping_city: scity_val
}, function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
Finally, my problem cleared. thank guys for contributing on my question :)
Apologies for this question if something out there covers this. I searched and found many relevant posts which has allowed me to get to this point.
I have a form snippet with 1 input box and a button and a div for a status message:
<div>
<div>
<div>
<input id="discount_code"name="discount_code" placeholder=" Enter discount code."></input>
</div>
<div>
<a class="btn btn-xs btn-primary" id="btn-validate">Validate</a>
</div>
</div>
<div id="status_msg" style="border: 1px solid black"></div>
</div>
Then I have the following bits of javascript:
The bit that triggers based on the click:
$('#btn-validate').on('click', function(e) {
e.preventDefault();
validateCode(11); // "11" is a php-provided ID variable
});
The javscript with the ajax call:
function validateCode(eventID) {
var codeValue = $("#discount_code").val();
if (FieldIsEmpty(codeValue)) { // outside function that exists/works fine
$('#status_msg').html('Enter a discount code.').fadeIn(500);
$('#status_msg').fadeOut(2500);
//bootbox.alert("Please enter discount code to validate.");
} else {
$.ajax({
type: 'POST',
cache: false,
async: true,
url: '/include/discount_validation.php',
dataType: 'json',
data: {
event_id: eventID,
discount_code: codeValue
},
beforeSend: function() {
$('#status_msg').html('');
$('#status_msg').fadeIn(0);
},
success: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
});
}};
And I have a PHP file that, suffice it to say, is working and producing the following json outputs based on the input:
// do php database things...
header('Content-Type: application/json');
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => "$message"));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => "$message"));
}
In the above, I have bootbox.alert lines commented out but when they are active, the box appears and the message is as I would expect it to be.
And lastly, the first condition that triggers if the input box is empty, both fires the alert (when not commented) AND changes the text of #status_msg.
I put the border in to verify visibility and #status_msg is visible but just is not set when either success or error fires.
First check if you getting an object in the response
in the success add
alert(JSON.stringify(data));
If it shows the object then you are good to go else check the php file where you creating the object.
If object is recieved in the success of ajax then you need to parse the json object using jQuery.parseJSON
For Eg:
response = jQuery.parseJSON(data);
Now you have a javascript object with name response.
Now use it
response['status'] or response['message'] in the success of the ajax.
check the code
first discard : " from php code $message variable
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
then use the response on font end success function :
success: function(data) {
$('#status_msg').html(data.message);
$('#status_msg').fadeIn(0);
},
Set your data like this inside ajax().
success: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
AND
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
I'm having the hardest time getting a simple form to process using jQuery and PHP. I've tried getting the data via $_POST, $_GET, and $_REQUEST but I guess I'm missing a simple line of code or a complete process altogether.
app.js
$(document).ready(function() {
$('#sucMsg').hide();
$('#errMsg').hide();
$('form').on('submit', function(event) {
event.preventDefault();
var form = $(this);
alert(form.serialize());
$.ajax(form.attr('action'), {
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: form.serialize(),
success: function(result) {
form.remove();
$('#sucMsg').append(result);
$('#sucMsg').fadeIn();
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
$('#errMsg').append(thrownError);
$('#errMsg').fadeIn();
}
});
});
});
formProcess.php
<?php
if ($_POST) {
echo "Posted something.";
} elseif ($_GET) {
echo "Getted something.";
} else {
echo "Nothing is working...";
}
$tagNumberPost = $_POST['inputTagNumber'];
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
$tagNumberRequest = $_REQUEST['inputTagNumber'];
$priceRequest = $_REQUEST['inputPrice'];
$makeRequest = $_REQUEST['inputMake'];
if (isset($_REQUEST['inputTagNumber'])) {
echo '$_REQUEST works...\n';
} elseif (isset($_POST['inputTagNumber'])) {
echo '$_POST works...\n';
} elseif (isset($_GET['inputTagNumber'])) {
echo '$_GET works...\n';
} else {
echo "Nothing is working...";
}
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
?>
What I'm expecting to get back is the all the echo's in my formProcess.php to print out in my #sucMsg div.
Why are you setting your contentType: as application/json? You do not need that. Remove it.
contentType: 'application/json', // remove this line
Just leave it to its default as application/x-www-form-urlencoded if your request is POST.
And in your PHP, $tagNumber is undefined.
if (isset(
$_POST['inputTagNumber'],
$_POST['inputTagNumber'],
$_POST['inputMake'],
)) {
$tagNumber = $_POST['inputTagNumber']; // define tagNumber
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
}
I have a form with an id or 'display'. It has one value to send which is a select item that I gave an id of 'services' to.
I want to send the value of 'services' to a function I have created in a seperate php page. The page is called 'functs.php' and the function name is called 'searchResults'.
The 'searchResults' function works, this much I know. It queries a database and outputs 8 seperate php echo statements. I have ran the PHP function and know it works. I know the issues is with my javascript because, well, I am not the greatest at JavaScript and usually shy away from it.
As of right now, the code is not doing anything. My form has its own action to post to a seperate php page.
<form id="display" action="resultPage.php" method="POST">
I am trying to use the javascript/ajax to instantly update the contents of a div BUT if the user has jscript turned off, I want the form to ppost to the alternate page. Here is my jscript.
$(document).ready(function() {
$('#display').submit(function(e) {
var formData = $('#services');
$.ajax({
type: "POST",
url: functs.php,
data: '$formData',
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
e.preventDefault();
return false;
});
});
PHP CODE:
<?php
function searchResults()
{
require 'db_config.php';
$sql= "SQL CODE HERE"
$theStyle = <<<HERE
"height:100%;
width:70%;
margin:4% AUTO 0;
padding:1.75em;
font-size:1.25em;
border-radius:5em;
color:white;
background-color:#b72027;
;"
HERE;
while ($row = mysql_fetch_array($result))
{
echo ("<div style = $theStyle>");
echo ("<table>");
echo ("<tr><td>" . $row["0"] . "</td></tr>");
echo ("<tr><td>" . $row["1"] . "</td>");
echo ("<tr><td>" . $row["2"] . ", " . $row["3"] . " " . $row["4"] . "</td></tr>");
echo ("<tr><td>Phone: " . $row["5"] . "</td></tr>");
echo ("<tr><td>" . "" . $row["6"] . "" . "</td></tr>");
echo ("<tr><td>" . $row["8"] . " " . $row["9"] . ", " . $row["10"] . "</td></tr>");
echo ("<tr><td>" . $row["11"] . "</td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td>" . $row["7"] . "</td></tr>");
echo ("</table>");
echo ("</div>");
echo ("<br />");
}
}
?>
Your JS code has a couple of issues. The PHP script name needs to be a string inside of quotation marks, and the formData variable has an unnecessary "$." Try this:
$(document).ready(function() {
$('#display').submit(function(e) {
e.preventDefault();
var formData = $('#display').serialize();
$.ajax({
type: "POST",
url: 'functs.php',
data: formData,
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
});
});