Ajax Value Not Transmitting To PHP - php

I have this Star Rating system right. When you click on a star it should pass a value into the function. Then using AJAX it posts it to an external PHP file. The only problem is that when it gets to the PHP file it comes as null or no value.
I will try to echo the $_POST['vote'] variable in an alert box using AJAX and it is blank so it doesn't come back as "NULL" or "0" it's just nothing. I'm not sure where I'm losing the value because I can track it all the way to the send() function. Anyone see a problem?
HTML:
<style type="text/css">
#container{margin: 10px auto;width: 500px;height: 300px;background-color: gray;}
#starContainer{padding-top:20px;margin:0 auto;width:150px;}
.box{height:28px;width:30px;float:left;position:relative;z-index:5;cursor:pointer;}
.star{background-image:url('emptyStar.png');background-repeat:no-repeat;}
.starHover{background-image:url('goldStar.png');background-repeat:no-repeat;}
#voteBar{float:left;height:28px;background-color:#dbd923;position:relative;top:-28px;z-index:1;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.box').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('starHover');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('starHover');
}
);
});
function Cast(vote)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
var json = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.send('vote=' + vote);
}
</script>
</head>
<body>
<div id="container">
<center>
<div id="starContainer">
<div class="box star" onclick="Cast(1)"></div>
<div class="box star" onclick="Cast(2)"></div>
<div class="box star" onclick="Cast(3)"></div>
<div class="box star" onclick="Cast(4)"></div>
<div class="box star" onclick="Cast(5)"></div>
<div id="voteBar"></div>
</div>
</center>
</div>
</body>
</html>
PHP:
<?php
$vote = $_POST['vote'];
$totalVoteValue = 0;
$amtVotes = 1;
$width = (($totalVoteValue + (($vote - $totalVoteValue) / $amtVotes)) / 5) * 150;
echo $width;
?>

xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
adding this may help (before send after open)

You are already using jquery (a very very very old version if i may say..), why not use it's built in ajax handler?
http://api.jquery.com/jQuery.post/
$.post('process.php', {vote: vote}, function(data) {
$('.result').html(data);
});

Related

How to transfer JQuery variable into PHP variable in a modal window without page refresh

I am new to this client variable to server variable transfer process.
Essentially I have a Google maps api function and have a marker on a map to represent a username in a users table (MySQL) of my PHP web app. When I double click on that map marker my Jquery function is popping up a modal and I am able to get the username in an id/name element (chosenUser) in a . However, I now need to be able to access this value in a PHP variable ($chosenUser) without any "submit" or page refresh, so that I can invoke my PHP function - getUserChannelID($chosenUser), and continue with the rest of the logic.
My disconnect is the ability to be able to access that value coming through on the id/name as #chosenUser and transfer it to a PHP variable $chosenUser without a "submit" or page refresh. All the code below is on the same page.
I am reading about the use of AJAX to do this in SF posts but since I quite the infant with AJAX I am getting confused on how exactly this can be done on the same page without a form "submit" or page refresh.
Can you please help correcting the code below so that I can get that value in #chosenUser to the PHP variable $chosenUser?
Here's my code all in the same PHP file.
<?php
require_once("classes/autoload.php");
$db = new Database();
....
?>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid" style="margin: 0 auto;">
<div style="height: 100%; position: relative; top:30px;">
<div id="map" style="height: 100%;"></div>
</div>
<div class="modal fade" id="showChannel" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Channel Preview</h4>
</div>
<div class="modal-body">
<div>
<input type="hidden" id="chosenUser" name="chosenUser" value="">
<!-- This is where I need help. How do I transfer that value I am getting for "chosenUser" above into the PHP variable $chosenUser - ideally the code in the next line would need to be executed -->
<?php $channelId = $db->getUserChannelID($chosenUser); ?>
.....
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script src="multiple_marker/oms.js"></script>
<script type="text/javascript">
var mapMarkers = [];
var infowindow = null;
var infowindowOpen;
var map, oms;
var gm = google.maps;
var markerIcons = new Array();
var gmarkers = [];
function getCoords() {
$.ajax({
url: "markers.php", // this markers.php provides the value of "Locations" array used below
type: "POST",
data: {
foo: "bar"
},
dataType: "json",
success: function (returnedData) {
console.log(returnedData);
if(!spiderify)
moveMarkerMap(returnedData);
//window.setInterval(getCoords, 10000);
window.setTimeout(getCoords, 2000);
}
});
}
function MarkerMap(json) {
var iconBase;
oms.addListener('click', function (marker) {
console.log('clicked');
});
if ((json.Locations.length > 0)) {
for (i = 0; i < json.Locations.length; i++) {
var location = json.Locations[i];
var username = location.username; // I am getting the value of username here
var myLatlng = new gm.LatLng(location.Lat, location.Long);
var marker = new gm.Marker({
position: myLatlng,
map: map,
username: username,
});
var infowindow = new gm.InfoWindow();
var div = document.createElement('DIV');
gm.event.addListener(marker, 'dblclick', (function (marker, div, infowindow) {
return function () {
$('#showChannel').modal('show');
$('#chosenUser').val(marker.username); //passing the value of marker.username to the modal input id/name="chosenUser"
};
})(marker, div, infowindow));
gmarkers[id] = marker;
}
}
window.map = map;
window.oms = omg;
}
gm.event.addDomListener(window, 'load', initialize);
</script>
Well, you can't exactly communicate between PHP and JS in the way you're thinking of. PHP is executed while the page is loading, before any content is displayed, before any javascript is even sent to the client, so it's impossible to do it as you wish.
What you can do is call a PHP script once the page is finished loading, using javascript. You can do this whenever you like, using a delay loop, when clicking a button, any way you can call your javascript function. That way you can send information from javascript to PHP, and when the PHP script finishes running it can report back information to javascript.
You want a variable from js in PHP, there are multiple ways of doing this, such as POST or GET requests. I'll post an example using POST, which is the same thing you'd use to send a form. You'll need to include jQuery for this to work.
JS
var myVar = "my info";
var myVar2 = "my other info";
$.post("myscript.php", {
info1: myVar,
info2: myVar2
}, function(answer) {
// answer will contain whatever the PHP script printed
// in this example answer will be "success"
alert(answer);
} );
PHP
$var1 = $_POST['info1'];
$var2 = $_POST['info2'];
if(!empty($var1) && !empty($var2))
{
echo "success";
}
It's up to you to implement it now.

How to Refresh (Update) an HTML Page For New Data After the Submit Button is Pressed

I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.

Nivo Slider dose not load the Ajax response from PHP file

I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.

Uncaught ReferenceError: getWidget is not defined

I'm trying to call a function in index.php but I get this error Uncaught ReferenceError: getWidget is not defined. When I call the function in the widget.php it works. How can I get the function getWidget(); to work in index.php?
I also get this warning in index.php
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost/widget.php".
and this error in widget.php
Uncaught SyntaxError: Unexpected token <
Here is index.php and widget.php
index.php
<script type='text/javascript' src='widget.php'></script>
Launch Widget
widget.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="/scripts/jquery-1.7.1.min.js"></script>
<link href="/css/bootstrap/css/bootstrap.css" rel="stylesheet">
<script type='text/javascript' src='/css/bootstrap/js/bootstrap.min.js'></script>
<script type='text/javascript' src='/css/bootstrap/js/bootstrap-transition.js'></script>
</head>
<script type="text/javascript">
var http = getHTTPObject();
function doauth() {
setTimeout("doauth();", 15000);
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
iframe.src = "api.php";
http.open("GET", "api.php");
document.body.appendChild(iframe);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.responseText != '') {
rslt = http.responseText;
document.getElementById('gw_content').innerHTML = rslt;
first_time = '';
}
// http.onreadystatechange = function(){};
// http.abort();
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function getWidget() {
$('#myModal').modal('show');
}
</script>
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<b style="color: #000;">Modal</b>
</div>
<div class="modal-body">
<h4>Modal</h4>
<p>Instructions...</p><br />
<div id="gw_content">
<body onload="doauth();" />
<img src="wheel-throb.gif">
</div>
</div>
</div>
<button type="button" onclick="getWidget();">Open</button>
There are a few areas of concerns, such as linking a .php extension into a script src attribute, that's causing one of your error message in index.php to appear.
However, to resolve the issue of getWidget not being defined, I would remove the <script> block from widget.php into a separate .js file (ie, yourfile.js) and access it in your index.php file like so,
<script type='text/javascript' src='yourfile.js'></script>
Launch Widget
Also, within widget.php are there any PHP code inside that file? If not, then you should rename it to a .html or .htm extension for clarity.

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

Categories