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.
Related
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
Formulated my options string using .each and sending it via .post to an external script.
clicked.closest("form").find("input,textarea").each(function(){
var input=$(this);
if(index==1){
options = "{"+input.attr("name")+":'"+input.val()+"'";
}else if(index==no_inputs){
options += ","+input.attr("name")+":'"+input.val()+"'}";
}else{
options += ","+input.attr("name")+":'"+input.val()+"'";
}
index++;
});
alert(options);
$.post('../pages/ajax/add_orders.php',options,function(data){
alert(data);
});
..problem is when my php call script is..
<?php
print_r($_POST);
?>
I simply get an empty array with no values.
The first alert shows the formulated string correctly.
But the second one returns an empty value.
Any help greatly appreciated.
You're post needs to be an actual object, you're creating a string.
clicked.closest("form").find("input,textarea").each(function(){
var input=$(this);
if(index==1){
options[input.attr("name")] = input.val();
}else if(index==no_inputs){
options[input.attr("name")] = input.val();
}else{
options[input.attr("name")] = input.val();
}
index++;
});
I think the above way will work.
try this instead:
var options={};
clicked.closest("form").find("input,textarea").each(function(){
var input=$(this);
options[input.attr("name")] = input.val();
});
I am trying to modify a Cookie through an Ajax petition but it doesn't work. It modifies the Session but not the cookie. Here is my code:
HTML:
<li class="en_GB" id="1" onclick="changeLanguage('en_GB;1')"><span></span>ENGLISH</li>
Javascript:
function changeLanguage(lang){
$.ajax({
url: 'lib/loadLanguageList.php',
data: {lan: lang},
type: 'POST',
success: function(data){
location.reload();
}
});
}
PHP (loadLanguageList.php) / Action:
if(isset($_POST['lan']) && preg_match("/([a-z]+_[A-Z]+;[0-9]+)/", $_POST['lan'])){
setUserLanguage($_POST['lan']);
}
PHP (loadLanguageList.php) / function EDITED*:
(Following the suggestion of #MikeBrant, I've edited the function)
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
}
setcookie("locale","",time()-2592000);
setcookie("locale_id","",time()-2592000);
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
print_r($locale);
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
But the cookie is not being deleted and the print_r print $locale variable as it should be. I don't understand why the setcookie function didn't work.
First, let's rewrite your function to where it makes better logic sense in terms of the code path flow (i.e. we have simplified the conditionals).
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
if(!isset($_COOKIE["locale"])){
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
} else {
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
}
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
}
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
Now let's walk through the use cases here. Let's say the user already has a locale cookie set and they are trying to change it.
This user would pass this conditional:
if(isset($lan))
And should fail this conditional
if(!isset($_COOKIE["locale"]))
This means this code block would be executed:
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
This would change the cookie value for the duration of the script execution only, as nothing in the response to the browser would trigger a change in cookie value.
My guess is that you want to ALWAYS call setcookie().
Also I would think the whole (!isset($lan)) section of code could be removed in favor for throwing some kind of error, as having a "set" function without passing it a value doesn't seem to make much sense.
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!
I'm using PHP, Smarty, jQuery, AJAX, Colorbox - a jQuery lightbox, etc. for my website. There is some old code done using jQuery AJAX method to display the message in popup using standard jQuery library functions. Now I want to replace that typical popup using Colorbox popup. In short Iwant to change the design part only the message part is as it is. I tried to do this but couldn't succeeded yet. Can you help me in doing the necessary changes to the existing old code in order to show the messages in Colorbox popup instead of typical popup? For your reference I'm putting the old code below:
Code from smarty template to give a call to the jQuery AJAX function is as follows:
<span class="submit edit_user_transaction_status" value="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</span>
The code from js file which contains the existing AJAX code is as follows:
$(document).ready(function() {
//This function is use for edit transaction status
$(document).on('click', '.edit_user_transaction_status', function (e) {
e.preventDefault();
$.colorbox.close();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('value');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
Now the code snippet from PHP file which contains the PHP code and success message is as follows:
case "edit_user_transaction":
$transaction_no = $request['txn_no'];
$transaction_status_update = $request['transaction_status_update'];
$transaction_data_assign = $request['transaction_data_assign'];
$user_id = $request['user_id'];
$from_date = $request['from_date'];
$to_date = $request['to_date'];
$page = $request['page'];
if($request['transaction_no']!=''){
$query = "&transaction_no=".$request['transaction_no'];
}
// If public transaction status is entered
if($request['transaction_status']!='') {
$query .= "&transaction_status=".$request['transaction_status'];
}
// For checking transaction no is empty, blank, and numeric
if($transaction_no!='' && !empty($transaction_no)) {
$objUserTransactions = new UserTransactions();
$objUserPackages = new UserPackages();
//if transaction status update to success and transaction data not yet assign
if(empty($transaction_data_assign) && $transaction_data_assign == 0 && $transaction_status_update == "success") {
$user_transactions = $objUserTransactions->GetUserTransactionsDetailsByTransactionNo($transaction_no, $user_id);
$i = 0 ;
$j = 0 ;
//Create array related study and test
foreach($user_transactions['transaction_details'] as $my_cart) {
if(!empty($my_cart['pack_id'])) {
if($my_cart['pack_type'] == 'study') {
$data['study'][$i] = $my_cart['pack_id'];
$i++;
}
if($my_cart['pack_type'] == 'test') {
$data['test'][$j]['pack_id'] = $my_cart['pack_id'];
$data['test'][$j]['pack_expiry_date'] = $my_cart['pack_expiry_date'];
$data['test_pack_ids'][$j] = $my_cart['pack_id'];
$j++;
}
}
}
if(!empty($data['study'])) {
$objUserStudyPackage = new UserStudyPackages();
//Update packages sold count & purchase date in package table
$objUserStudyPackage->UpdateStudyPackagePurchaseData($data['study']);
//For insert packages related data to package_user table
foreach($data['study'] as $study_pack_id) {
$objUserPackages->InsertStudyPackagesToPackageUser($study_pack_id, $user_id);
}
}
if(!empty($data['test'])) {
$objUserTestPackage = new UserTestPackages();
//Update packages sold count & purchase date in test package table
$objUserTestPackage->UpdateTestPackagePurchaseData($data['test_pack_ids']);
//For insert test related data to test_user table
foreach($data['test'] as $test_pack_data) {
$objUserPackages->InsertTestPackagesToTestUser($test_pack_data['pack_id'], $test_pack_data['pack_expiry_date'], $user_id);
}
}
//This function is use for update status inprocess to success and transaction_data_assign flag 1
$user_transactions = $objUserTransactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update, '1');
} else {
// This function is use for update status
$user_transaction_details = $obj_user_transactions->UpdateTransactionStatusByTransactionNo($transaction_no, $user_id, $transaction_status_update);
}
//Email functionality when status update
include_once("transaction_status_update_email.php");
**$reponse_data['success_massage'] = "Transaction status updated successfully";
$reponse_data['title'] = "Transaction";
$reponse_data['href'] = "view_transactions.php?page=".$page."&from_date=".$from_date."&to_date=".$to_date.$query;
$reponse_data['login_error'] = 'no';
$reponse_data = json_encode($reponse_data);
echo $reponse_data;
die();**
}
break;
The code shown in bold font is the success response message. Can you help me in this regard, please? Thanks in advance.
Yo, you asked for help in PHP chat. Hopefully this helps:
So the dialog portion at the bottom needs to change to support colorbox. Firstly, load all your colorbox stuff. Second, you'll need to create your colorbox content dynamically by either grabbing content from an element on the page or building it on the fly.
You might need to debug some of this but here's generally how you do this...
Delete the entire $dialog variable
var $dialog = .....
And change that to something that will look similar to:
var $dialog = $('<div>').addClass('ui-state-success').append($('<p>').addClass('ui-state-error-success').html(dialog_message));
Then you'll need to do something like this:
$.colorbox({html: $dialog});
If you're having trouble seeing the content that is dynamically built inside your colorbox try calling $.colorbox.resize() on the opened callback:
opened: function(){
$.colorbox.resize();
}
If that doesn't work you may also need to pass a innerWidth/innerHeight or width/height property inside the resize method.