Trying to return php data from ajax - php

Im a little new to Ajax, and Ive been trying figure out what part im doing wrong. I have results being pulled from a database and thrown into xml. While im looping through the xml I'm trying execute a php file while sending it the ID number from the xml results and then return the 'echo' from the php file. Im not sure if im totally off or just missing one part, but the results come back 'undefined'.
Here is the php file that Im trying to get echoed out and show up.
echo rating_bar($id);
function rating_bar($id) {
//other code, but $static_rater is what gets echoed
$static_rater = "";
$static_rater .= '<div id="ratingblock" class="ratingblock">';
$static_rater .= '<div id="unit_long'.$id.'">';
$static_rater .= '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
$static_rater .= '<li class="current-rating" style="width:'.$rating_width.'px;"></li>';
$static_rater .= '</ul>';
$static_rater .= '<p class="static">Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>';
$static_rater .= '</div>';
$static_rater .= '</div>';
//return join("\n", $static_rater);
echo $static_rater;exit;
}
And this is the .js code that im trying to get to return the results.
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var bounds = new google.maps.LatLngBounds();
var markers = xml.documentElement.getElementsByTagName("marker");
// alert("downloadUrl callback, length="+markers.length);
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
if (!id) id = "id "+i;
var name = markers[i].getAttribute("name");
if (!name) name = "name "+i;
var address = markers[i].getAttribute("address");
if (!address) address = "address";
var citystate = markers[i].getAttribute("citystate");
if (!citystate) citystate = "city, ST";
var phone = markers[i].getAttribute("phone");
if (!phone) phone = "phone number";
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(point);
var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow
var url = "starrating/_drawrating.php?id=" + id + "";
//var contentString = ajaxLoad(url, parseResults, true);
//var contentString = downloadUrl(url, "POST", "text=" + text, completed);
var contentString = AJAX('starrating/_drawrating.php','id='+id,
function(data) {
var htm = $("#ratingblock").html(data);
alert(htm);
}
);
var description = "<br><br>description" + id + " <br><b>" + name + "</b> <br/>" + address + "<br/>" + citystate + "<br/>" + phone; //html inside InfoWindow
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
animation: google.maps.Animation.DROP
});
bindInfoWindow(marker, map, infoBubble, html, description, contentString);
}
});
function AJAX(url, data, callback)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
EDIT: Ok so ive been playing around with this and updated my code above. Now when I run this using firebug I can see the post and the response is this:
<div id="ratingblock" class="ratingblock"><div id="unit_long10"><ul id="unit_ul10" class="unit-rating" style="width:150px;"><li class="current-rating" style="width:0px;"></li></ul><p class="static">Rating: <strong> 0.0</strong>/5 (0 votes cast)</p></div></div>
But the alert just says [object Object] and the infowindow says [object Object]. So i know its calling and returning the data, and ive searched and tried just about everything I can think of to get the above section to appear correctly inside the infowindow. Any thoughts?
EDIT #2
Im trying a new approach below.
var contentString = $.ajax({
type:"POST",
url: "starrating/_drawrating.php",
dataType: "html",
data:"id="+id,
success: function(data){
var $response=$(data);
$response.find('ratingblock').html();
console.log($response);
}
});
The console comes back with "Object[div#ratingblock.ratingblock]" but the results still say [object Object]. Any ideas what im missing?

The A in AJAX stands for asynchronous, meaning that the JS will not wait for the PHP data to come back. So you cannot simply assign the result of your AJAX call to a variable, you have to register a function that will be called once some data comes back. This is what your currently empty function(result) {} callback is for.
It's sort of like asking someone to fetch something, and carrying on in the meantime rather than standing frozen to the spot until they get back. The callback function, in this slightly dodgy analogy, is a note of what you intend to do when they get back.

You're sending part of your data in the url and part in the post body, put both parts in the post body. i.e.
AJAX('starrating/_drawrating.php','id='+id,

$static_rater is an array you can't use the concatenation operator with it.
$static_rater[] = "\n".'<div class="ratingblock">';
$static_rater[] = '<div id="unit_long'.$id.'">';
$static_rater[] = '<ul id="unit_ul'.$id.'" class="unit-rating" style="width:'.$rating_unitwidth*$units.'px;">';
$static_rater[] = '<li class="current-rating" style="width:'.$rating_width.'px;">Currently '.$rating2.'/'.$units.'</li>';
$static_rater[] = '</ul>';
$static_rater[] = '<p class="static">'.$id.'. Rating: <strong> '.$rating1.'</strong>/'.$units.' ('.$count.' '.$tense.' cast)</p>';
$static_rater[] = '</div>';
$static_rater[] = '</div>'."\n\n";

Related

How to store in a php variable data from innerHTML when happens

I have a websocket script that looks in blockchain to a specific address if someone sends btc. If the payment is done, the script will output with javascript innerHTML a message. Is there a way I can make to run a php script if this happens? Script below
<script>
var btcs = new WebSocket("wss:ws.blockchain.info/inv");
btcs.onopen = function(){
btcs.send(JSON.stringify({"op":"addr_sub", "addr":<?php echo json_encode($new_address, JSON_HEX_TAG); ?>}));
};
btcs.onmessage = function(onmsg) {
var response = JSON.parse(onmsg.data);
var getOuts = response.x.out;
var countOuts = getOuts.length;
for(i=0; i<countOuts; i++){
var outAdd = response.x.out(i).addr;
var address = <?php echo json_encode($new_address, JSON_HEX_TAG); ?>;
if(outAdd == address){
var amount = response.x.out(i).value;
var recAmount = amount / 100000000;
document.getElementByid("websocket").innerHTML = "Payment recieved: " + recAmount + "BTC <br>;
};
};
};
</script>
<p id="websocket">Monitoring transaction...</p>

AJAX code doesnt reload

Been trying to follow a tutorial:
https://www.udemy.com/json-ajax-data-transfer-to-mysql-database-using-php/
There is a video in section 4: lecture 20
script.js
var output = document.getElementById('output');
output.innerHTML = "";
function submitData(fdata){
var xhttp = new XMLHttpRequest();
xhttp.onload = function(){ console.log(xhttp.responseText);
jData();}
xhttp.open(fdata.method,fdata.action,true);
xhttp.send(new FormData(fdata));
//console.log(fdata.method);
return false;
}
function jData(){
var ajaxhttp = new XMLHttpRequest();
var url ="json.php";
ajaxhttp.open("GET", url, true);
ajaxhttp.setRequestHeader("content-type","application/json");
ajaxhttp.onreadystatechange = function(){
if(ajaxhttp.readyState == 4 && ajaxhttp.status == 200){
var jcontent = JSON.parse(ajaxhttp.responseText);
for (var myObj in jcontent){
output.innerHTML += '<div>' + jcontent[myObj].firstName + ' ' + jcontent[myObj].lastName +
' ' + jcontent[myObj].age + '</div>';
}
console.log(jcontent);
}
}
ajaxhttp.send();
}
I'm not so sure how I am suppose to put the other codes here since it requires a sql command but if ever someone could look at this code. The code is suppose to display the data and every time I insert a new data. It's suppose to display the new data at the bottom however the code does it displays all the data over and over again.
Can someone explain why this is happening?

Alternative to innerHTML for IE select box

I have a problem that is php data not showing in select box. innerhtml not working in Internet Explorer. long_description_detail_list data not showing in select box.please help me
first page:
<div id="long_description_detail_list" style="display:none;">
<option value="0">Select..</option>
<?php
include_once('Model/Language.php');
$r = new Language();
$a = $r->Select();
for($i = 0; $i < count($a); $i++)
{
print '<option value="'.$a[$i][0].'">'.$a[$i][1].'</option>';
}
?>
</div>
<script language="javascript" type="text/javascript">
//Browser Support Code
function create_long_description_detail_div(){
if(count_table_long_description_detail() >=3) {
alert("You can not add more than 3 long_description Details");
}
else {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var blank_long_description_detail = ajaxRequest.responseText;
document.getElementById('long_description_detail_counter').value ++;
$('#my-all-long_description_details-here').append(blank_long_description_detail);
set_new_height_of_step_2('inc');
var long_description_list_counter = document.getElementById('long_description_detail_counter').value;
var long_description_detail_list = document.getElementById('long_description_detail_list').innerHTML;
document.getElementById('llanguage[' + long_description_list_counter + ']').innerHTML = long_description_detail_list;
}
}
var long_description_detail_counter = document.getElementById('long_description_detail_counter').value;
var queryString = "?long_description_detail_counter=" + long_description_detail_counter;
ajaxRequest.open("GET", "Views/User/long_description/add_long_descriptions_detail.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
data not showing here in second page named add_long_descriptions_detail.php:
<select id="llanguage[<?php echo $counter; ?>]" name="llanguage[<?php echo $counter; ?>]" class="txtBox">
<option value="0">Select..</option>
</select>
IE doesn’t support updating the elements of a <select> with innerHTML, but what you can do is use the DOM, which is always the right way to go about things anyways.
Make your server-side script return a JSON array of options; it’ll make everything a lot easier.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
// Parse the response
var options = eval('(' + ajaxRequest.responseText + ')');
// Get the box; I have no clue what this is
var box = document.getElementById('llanguage[' + long_description_list_counter + ']');
// Clear any current elements
while(box.childNodes.length > 0) {
box.removeChild(box.firstChild);
}
// Add new ones
for(var i = 0; i < options.length; i++) {
var newOption = document.createElement('option');
newOption.value = options[i].value;
newOption.appendChild(document.createTextNode(options[i].text));
}
}
};
(This is a little trimmed-down from your original code, but I’m sure you can fit it in.)
It’s also probably a good idea to use an old-IE-compatible JSON parser instead of eval.
The JSON should look like this:
[
{ "text": "Some text", "value": "some-value" }
]
You can use json_encode to produce it conveniently from a PHP array.

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

sending js variables to php page - not working

This is what my javascript looks like:
print "<script>function newpage(){
xmlhttp=new XMLHttpRequest();
var PageToSendTo = 'select_db.php?';
var MyVariable = 'variableData';
var VariablePlaceholder = 'variableName=';
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable + '&tweet_id='" . $id_num;
print "xmlhttp.open('GET', UrlToSend);
xmlhttp.send();
}</script>";
(it is in a php file hence the print statement)
This is what my form submission looks like: (again in a php statement)
print "<form action=\"select_db.php\" onSubmit=\"return newpage()\">";
The function newpage is not working.. I expected the variables to be sent over in the URL but the resulting URL is just select_db.php?
help, please.
You are missing the initial <script> tag...
print "<script>function newpage(){
xmlhttp=new XMLHttpRequest();
var PageToSendTo = 'select_db.php?';
var MyVariable = 'variableData';
var VariablePlaceholder = 'variableName=';
var UrlToSend = PageToSendTo + VariablePlaceholder + VariablePlaceholder + '$tweet_id='" . $id_num;
print "xmlhttp.open('GET', UrlToSend);
xmlhttp.send();
}</script>";
does that solve your problem ?
try this onSubmit=\"newpage(); return false; \"

Categories