php and js-ajax acting funny (explanation inside) - php

I am having trouble with this ajax. The return is funny. The switch seems to always evaluate as though #about is true. And include the rest of the switch statement in the #page variable. For instance my PHP code prints this (as well as the #about that it is supposed to) the code at the bottom should clarify what I mean.
To recap it echoes everything past the first $page ='
on my page I see this below what it is supposed to echo
';
break;
case '#register' :
$page = 'k';
break;
case '#contact' :
$page = 'a';
break;
case '#a' :
$page = ' b';
break;
case '#b' :
$page = '<p> c</p>';
break;
default;
echo "def";
}
echo $page;
Not to mention it wont even work for #contact, or #a, #b...etc. I am not sure why. Regardless of the url passed it appears as though #about is called with what it returns (even though it returns about and more).
I would really appreciate some help! Thank you
Here is my code:
the js =]
$(document).ready(function () {
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content
$('#content').hide();
console.log(this.href);
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
console.log("k");
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
the php =]
switch($_GET['page']) {
case '#about' :
$page = ' HTML stack overflow formats it, anyways';
break;
case '#register' :
$page = 'k';
break;
case '#contact' :
$page = 'a';
break;
case '#a' :
$page = ' b';
break;
case '#b' :
$page = '<p> c</p>';
break;
default;
echo "def";
}
echo $page;
thank you again!

Also in the php file, try putting this on top of the script:
header("Content-Type: text/html");

Related

How to use cookie in ajax file

I have code that uses ajax in order to pull and print data from DB.
ajax run PHP file that does that. This file read data from the cookie and use it, but because I'm using ajax and run file "away" from the website I don't think it can call to cookies...
how can I read cookie inside the ajax file?
AJAX FILE
switch ($_COOKIE['user_lang'])
{
case "ES":
$langDir = SPANISH
break;
case "EN":
$langDir = ENGLISH
break;
}
You can try it .
function readCookie(cname) {
var name = cname+"=";
var cookies = decodeURIComponent(document.cookie).split(';');
var cval = [];
for(var i=0; i < cookies.length; i++) {
if (cookies[i].trim().indexOf(name) == 0) {
cval = cookies[i].trim().split("=");
}
}
return (cval.length > 0) ? cval[1] : "";
}
switch (readCookie(['user_lang']))
{
case "ES":
$langDir = SPANISH
break;
case "EN":
$langDir = ENGLISH
break;
}

Adding icon to product added in cart PHP/Jquery

I am trying to add a checkmark to the products that have been added to cart.
I am using ajax to return.
But i know i am doing wrong.
I got a bit lost.
I made with php first,and it works,but only displays when i refresh the page.
My php code...
if(isset($_SESSION['product'][$id])){
$added='<a href="" class="badge-corner" product_id="'.$id.'" >
<span class="fa fa-check"></span></a>';
}else{
$added='';
}
I want to use ajax to display the checkmark.
This is where i get my product id and store them to session.
My add to cart function and item counter code..(cart_function2.php)
<?php header('Content-Type: application/json');
session_start();
if (isset($_GET['action'])) {
$action = $_GET['action'];
$prod = $_GET['prod_id'];
$result="";
switch ($action) {
case 'add':
$result = add_prod($prod);
break;
default:
$result = ['result'=>'error'];
break;
}
}
// Calculate subtotal here
$result['totals'] = new stdClass;
$total_in_cart=count($_SESSION['product']);
$_SESSION['products']=$total_in_cart;
if(isset($_SESSION['product'][$prod])){
$added='</span>';
}else{
$added='';
}
$result['added'] = $added;
$result['items'] = $total_in_cart;
echo json_encode($result);
function add_prod($prod){
//add function
$_SESSION['product'][$prod] = 1;
$_SESSION['products']++;
return ['result'=>'success'];
}
?>
And this is the script in my gallery...
$('.actions').click(function(e){
e.preventDefault(e);
var action = $(this).attr('data-action'); //gets button id
var id = $(this).attr('product_id');
console.log("triggered action " + action + " for product " + id);
$.ajax({
url: 'cart_functions2.php',
type : 'GET',
data: {action:action,prod_id:id},
dataType: 'json'
}).done(function(data) {
console.log("ajax call returned the following: " + JSON.stringify(data));
if (data.result == "success") {
$("#items").html(data.items);
$(".show").html(data.added) + id;
//some debugging script
i am trying to display in here
<div class="show">'.$added.'</div>
When i click add product, all my products gets checked at once.
Why?
Please help me,i'm still a noob at jquery.

How to change frame to div and load content into div

Is there any way to convert an iframe with all attributes it contains into a div or php.
<iframe src='left_nav.php' name='left_nav' class="daemon" scrolling="auto" frameborder='0' height='100%' width="100%"></iframe>
If I use the php include function to call the left_nav.php file:
<?php include left_nav.php; ?>
How to load content which was loading in the frame into the div.
In main.title file (other file)
function toencounter(rawdata) {
document.getElementById('EncounterHistory').selectedIndex=0;
if(rawdata=='') {
return false;
} else if (rawdata=='New Encounter') {
top.window.parent.left_nav.loadFrame2('nen1','RBot','forms/newpatient/new.php? autoloaded=1&calenc=')
return true;
} else if (rawdata=='Past Encounter List') {
top.window.parent.left_nav.loadFrame2('pel1','RBot','patient_file/history/encounters.php')
return true;
}
var parts = rawdata.split("~");
var enc = parts[0];
var datestr = parts[1];
var f = top.window.parent.left_nav.document.forms[0];
frame = 'RBot';
if (!f.cb_bot.checked) {
frame = 'RTop';
}
parent.left_nav.setEncounter(datestr, enc, frame);
top.frames[frame].location.href = '../patient_file/encounter/encounter_top.php?set_encounter=' + enc;
}
In left_nav file
setEncounter(edate, eid, frname) {
if (eid == active_encounter) return;
if (!eid) edate = '<?php xl('None','e'); ?>';
var str = '<b>' + edate + '</b>';
setDivContent('current_encounter', str);
active_encounter = eid;
encounter_locked=isEncounterLocked(active_encounter);
reloadEncounter(frname);
syncRadios();
var encounter_block = $(parent.Title.document.getElementById('current_encounter_block'));
var encounter = $(parent.Title.document.getElementById('current_encounter'));
var estr = ' <b>' + edate + ' (' + eid + ')</b>';
encounter.html( estr );
encounter_block.show();
}
function loadCurrentEncounterFromTitle() {
top.restoreSession();
top.frames[ parent.left_nav.getEncounterTargetFrame('enc') ].location='../patient_file/encounter/encounter_top.php';
}
This is a JS script to loadFrame2
function loadFrame2(fname, frame, url) {
var usage = fname.substring(3);
if (active_pid == 0 && usage > '0') {
alert('<?php xl('You must first select or add a visitor.','e') ?>');
return false;
}
if (active_encounter == 0 && usage > '1') {
alert('<?php xl('You must first select or create an encounter.','e') ?>');
return false;
}
if (encounter_locked && usage > '1') {
alert('<?php echo xls('This encounter is locked. No new forms can be added.') ?>');
return false;
}
var f = document.forms[0];
top.restoreSession();
var i = url.indexOf('{PID}');
if (i >= 0) url = url.substring(0,i) + active_pid + url.substring(i+5);
if(f.sel_frame)
{
var fi = f.sel_frame.selectedIndex;
if (fi == 1) frame = 'RTop'; else if (fi == 2) frame = 'RBot';
}
if (!f.cb_bot.checked) frame = 'RTop';
top.frames[frame].location = '<?php echo "$web_root/interface/" ?>' + url;
if (frame == 'RTop') topName = fname;
return false;
}
Since you want to load content of an other file (left_nav.php) into a div rather than into an iframe, you can use multiple ways to do that.
1) JS:
Create a div container which will hold your content:
<div id="left_nav"></div>
Now, you can use jQuery to load the content easily:
onClick="loadContent('path/to/file/left_nav.php')"
This would be your loadContent function:
function loadContent(path){
$("#left_nav").load(path);
}
2) PHP:
You could also use PHP (pass a parameter to the URL you are currently on yourfile.php?m=left_nav). Then you can include the file, with a controller (MVC principle -> if you want to learn more about it):
<?php
if($_GET["m"] == "left_nav")
include("left_nav.php");
?>
EDIT:
It seems like you need a little mix of both. Instead of your iframe you need to insert a div and load the content at the same time:
<div id="left_nav"><?php include("left_nav.php"); ?></div>
This should be equivalent to creating the iframe. Now, when you change the src of the iframe in your JS scripts, instead of using this line:
top.window.parent.left_nav.loadFrame2('pel1','RBot','patient_file/history/encounters.php');
try changing the content of the div as I stated previously at 1), but you should only need the loadContent function.

Php Sessions and Ajax

Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
my blogFunction.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:here
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
The problem that lies here, is, I click my button once at my site
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not.
Add session_start(); to blogFunction.php
Here's the properly working code...
index.php
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
blogFunction.php
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps!
You need to call session_start () in your blogFunction.php file. It has to be called before any output to the brower. Probably best case would be to call it first in the script.
I think that you should first unset $_SESSION['views'] and than write again.
function blogreturn(){
$temp = $_SESSION['views'];
unset($_SESSION['views']);
$_SESSION['views'] = $temp + 1;
echo "THIS number is:" .$_SESSION['views'];
}

need help to send variable from javascript to PHP

i try to send some data from html to process page. i want to do this use javascript.
the javascript is:
$('#search').click(function(){
var param = serialize({
action:"searchmodelqp",
jhead:"aaData",
month:$("#search_month").val(),
year:$("#search_year").val(),
export:"excel"
});
$('#link2excel' ).replaceWith("<div id='link2excel'><a href='shows_merchan.php?" + param + "' target='_blank'>Export result as Excel file</a></div>");
});
and i send it to this:
if(getVar('export')=='excel'){
$expexcel = 'excel';
} else {
$expexcel=0;
}
switch(getVar('action')){
case 'searchmodelqp':
modelqp(getVar('jhead'),getVar('month'),getVar('year'),getVar('export'));
break;
}
function modelqp($jsonhead,$month, $year,$export){
$Month = mysql_real_escape_string($month);
$Year = mysql_real_escape_string($year);
switch($jsonhead){
case 'aaData':
//i put mysql query here
break;
}
if($export==0) {
//do something
} else {
//do something
}
how do i do to make it clear?because i have no result for this(script do nothing).
change your data as below
data:action="searchmodelqp&jhead="aaData"&month=$("#search_month").val()&year=$("#search_year").val()&export="excel"
i change at this part:
var param = jQuery.param({action:"searchmodelqp",jhead:"aaData",month:$("#search_month").val(),year:$("#search_year").val(),export:"excel"});

Categories