I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode() to create a JSON data which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}... is successful, an alert is displayed showing the data.items. The problem I am facing is that, when data.items is greater than or equal to 1 the alert is prompted, but when data.items is equal to 0, no alert is prompted.
Kindly help me solve this problem
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0) $total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total))); the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0 before your condition it should also fix the issue, without having to die early.
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Adding die(json_encode(array('items'=>$total_items))); at the end of the condition if($total_items == 0) and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed
Related
I have a javascript program that submits a form to a PHP page that collects data depending upon the form entries. I have verified that the data is returned correctly. In the following piece of the code, the success portion of the ajax call is shown:
success: function(msg){
var newWindow = window.open("_blank");
var result = $.parseJSON(msg);
var array =
newWindow.document.open();
newWindow.document.write("<!DOCTYPE html><html><head></head><body>");
for( var i=0; i<result.entries.length; i++ ) {
var obj = result.entries[i];
newWindow.document.write(unescape(obj));
}
newWindow.document.write("</body></html>");
newWindow.document.close();
newWindow.focus();
alert( "Printout complete" );
}
The tab is opened, and the entries[i] elements, which are strings, are written to the new tab. This is what is displayed on the browser window:
<h1>Age 1</h1><h2>Test</h2><br/>Test
The page source shows:
<html><head></head><body>"<h1>Age</h1><h2>Test</h2><br/>Test"</body></html>
The PHP page which filled the result obj contained:
...
if( $age != $last_age ) {
$last_age = $age;
array_push($items,"<h1>Age $age</h1>");
}
if( $age == $last_age && $event != $last_event ) {
$last_event = $event;
array_push($items,"<h2>$event</h2>");
}
array_push($items,"<br/>$data");
}
$result["entries"] = $items;
header("Content-type: application/json");
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($result);
It appears that putting the h1 etc. into the strings to be returned result in them being encoded as <h1> etc. They then show up in the source code for the page as '<', but the entire lines containing the entries[i] is enclosed in double quotes. If where I write unescape(obj), I substitute "<h1>Hello World</h1>", I get that rendered on the page.
How do I get the HTML to the page and have it rendered with the h1, h2, etc.?
Well, it was going around my elbow to get from my finger to my thumb, BUT, I got it to work. In the PHP I changed to store a JSON array as each element in items, viz.
$nameAttr = 'h1';
$item = array();
$item[$nameAttr] = "Age $age";
array_push($items,$item);
similarly for h2 element and straight text element.
In the index.html page where it is processed I replaced the newWindow.document.write(obj), with:
var objJSON = result.entries[i];
$.each(objJSON, function(key, value) {
if( key == 'h1' ) {
newWindow.document.write("<center><h1>"+value+"</h1></center>");
} else if (key == 'h2' ) {
newWindow.document.write("<center><h2>"+value+"</h2></center><br/>");
} else {
newWindow.document.write(value);
}
});
}
It rendered as I wished! This seems inordinately complex to do such a simple thing as one might have many types of entries on the page such as <tr>, etc. This method would require 'keys' for each html element and a subsequent handler for that key. If anyone has a clue how to include the html tags in the PHP code, it would be helpful!
I've already set up a basic SimpleCart.js web shop and am trying to implement realseanp's solution for adding a promo/discount code feature.
He uses the following JavaScript to post the user's entered promo code to discount.php:
jQuery("#promoSub").click(function Discount() {
//Interact with PHP file and check for valid Promo Code
jQuery.post("discount.php", { code: jQuery('#code').val() } , function(data) {
console.log(jQuery('#code').val());
if (data=="0" || data=='') {
console.log("Wrong Code");
}
else {
//create our cookie function if promo code is valid
//create cookie for 1 day
createCookie("promo","true",1);
var y = (data/100);
for(var i=0; i<simpleCart.items().length; i++){
var itemPrice = simpleCart.items()[i].price();
var theDiscount = itemPrice * y;
var newPrice = itemPrice - theDiscount;
simpleCart.items()[i].set("price", newPrice)
}
simpleCart.update();
//hides the promo box so people cannot add the same promo over and over
jQuery('#promoCodeDiv').hide();
}
});
});
...which echoes back a 0 or the discount percentage if the correct code has been passed:
<?php
$x = 0;
if ($_POST["code"]=="HOLIDAY") { $x = 5; };
echo $x;
?>
However, when I console.log(data) from within the success function, data appears to be the entirety of the PHP script as a string instead of the echo.
Why is this, and what modifications do I need to make to rectify it? I'm very new to PHP and having difficulty understanding why jQuery.post() isn't receiving the echo.
I have a PHP script setup that echo's JSON responses depending on what the user has done (or not done as the case may be):
The responses look like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
Each response is generated like this:
echo $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
This is picked up by pNotify and displayed - lovely. (See below .done function for ajax request)
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var array = json_to_array(msg);
}
if (array['type'] !== 'none') {
if (array['title'] !== null) {
pushNotification(array['title'], array['response'], array['type'], array['hide']);
} else {
pushNotification(ucfirst(array['type']), array['response'], array['type'], array['hide']);
}
}
ready_status();
});
If the response cannot be validated by tryParseJSON(); the reponse is written directly to the page for debugging.
The problem is when I echo multiple responses back like this:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NDat]","title":"Exception","hide":false}
tryParseJSON() sees it as mumbo jumbo and prints it to the page.
Question
How do i pick up the above two lines as separate responses and parse them through my function and sub-sequentially to pNotify without combining them into a single JSON array?
Solution
As pointed out this was over complicated. Instead I combined each response (PHP side) into a an array:
$res['json'][] = $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
Then echo'ed it at the end of the script:
echo json_encode($res['json');
On client side, I used a for loop, sending them to pNotify in each iteration:
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var obj = json_to_array(msg);
}
for (var i=0;i<obj.length;i++) {
if (obj[i]['type'] !== 'none') {
if (obj[i]['title'] !== null) {
pushNotification(obj[i]['title'], obj[i]['response'], obj[i]['type'], obj[i]['hide']);
} else {
pushNotification(ucfirst(obj[i]['type']), obj[i]['response'], obj[i]['type'], obj[i]['hide']);
}
}
}
ready_status();
});
Instead of creating so sperate JSON-Outputs merge it to one single output string.
For this just wrap your two arrays you are currently outputting separately in an array like so
$myOutput[0] = responseArray1;
$myOutput[1] = responseArray2;
echo json_encode($myOutput);
This way you will get a valid JSON-response. Everything else is just some dirty workaround and causes shivers to everyone who has to review your work.
I have a page where I use jQuery load() method to display a table of results based on a post request of some fields. But I need this load() to display the table and also inform javascript if a condition is met in the PHP script, so probably I need a json response. I don't know if it's possible to use the complete() callback to achieve that. I only need a single variable to pass from my PHP script to javascript.
I'm using load() because I believe other ajax methods need to do the HTML template part from javascript, am I right?
Hope I made myself clear, thanks
UPDATE1:
Here is my js code:
$("#listaNegraView").load('procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()},
function(data){console.log(data);}
);
And here is PHP script:
case 'listaNegra':
$_POST['nombres'] = mb_convert_encoding($_POST['nombres'], 'Windows-1252', 'UTF-8');
$_POST['apellidoP'] = mb_convert_encoding($_POST['apellidoP'], 'Windows-1252', 'UTF-8');
$_POST['apellidoM'] = mb_convert_encoding($_POST['apellidoM'], 'Windows-1252', 'UTF-8');
$listaNegra = $personaDB->existsPersonaListaNegra($_POST);
$pct100 = false;
if(!empty($listaNegra) && is_array($listaNegra)){
foreach($listaNegra as &$persona){
$persona['match'] = '';
$porcentaje = 80;
if(strtolower($persona['nombres']) == strtolower($_POST['nombres'])){
$persona['match'] .= 'name';
$porcentaje += 10;
}
if($_POST['nacimiento'] == $persona['fecha_nacimiento']){
$persona['match'] .= 'date';
$porcentaje += 10;
}
$persona['porcentaje'] = $porcentaje;
if($porcentaje == 100)
$pct100 = true;
}
unset($persona);
}
include(ROOT.RUTA_TPL.'ventas/listanegra.tpl.php');
break;
UPDATE 2:
Specifically the condition I want to pass to jasvascript is variable $pct100
You are "directly" outputting HTML code so I think, as a quick workaround, you should write the $pct100 in a hidden field/dom element and then access it with the complete callback in your javascript code.
This is an example of what I am suggesting
$("#listaNegraView").load(
'procesos/funcionesAjax.php',
{accion: 'listaNegra',
nombres: $("#nombres").val(),
apellidoP: $("#apellidoP").val(),
apellidoM: $("#apellidoM").val(),
nacimiento: $("#nacimiento").val()
},
function(data){
$('#where-to-put-html-code').html(data);
var pct100 = $('#where-to-put-html-code #hidden-field-id').val() == '1' ? true : false;
}
);
Answer added by the suggestion of the asker.
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!