sending js variables to php page - not working - php

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; \"

Related

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?

showing result of file call by ajax request into different div

On button click I submit the form and post some data to data.php.
The result Of data.php I show in some div on index.php
index.php:
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
//alert(text3);
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.responseText.resultOne;
xmlhttp.responseText.resultTwo;
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
deURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
Data.php looks like this:
<?php
//sent has value "http://www.paulgraham.com/herd.html"
$url=$_POST['sent'];
$text1=$_POST['text1'];
$text2=$_POST['text2'];
$text3=$_POST['text3'];
//Some processing
echo $restult1; // I want to show this on <div1> on main page index.php
//Some processsing
echo $result2; // I want to show this on <div2> on main page index.php
?>
HOW can I show result1 and result2 on different div on index.php?
<?php
//sent has value "http://www.paulgraham.com/herd.html"
$url=$_POST['sent'];
$text1=$_POST['text1'];
$text2=$_POST['text2'];
$text3=$_POST['text3'];
//Some processing
$resultArray = array("resultOne" => $result1,"resultTwo" => $result2);
echo json_encode($resultArray);
?>
So you will get a response object from php page.
And now you can access it values like bellow in Js
In Javascript
xmlhttp.responseText.resultOne;
xmlhttp.responseText.resultTwo;
Now you can set for two divs
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
Maybe you could echo a script where you assign the value of result1 to div1 and result2 to div2.
For example if you use jquery you could do something like this:
echo "<script> $("#div1").innerHTML(".$result1");</script>"

Parsing Javascript Variable into php query

I am newbie in php and still learn javascript function.
I have a problem with, include javascript variable into php query.
I want to create transaction code according count of part code which have different type. then i must get value with count.
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
<?php
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = "<script>v;</script>"");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
The result like that 1/CPU/JKT/2013
I call that function with button onClick="getCode()" no submit.
Anyone can help me.
You can't do it by the way you tried.There are two better ways to do it
Use Ajax.
Use Cookies
The best way here is to use Ajax. Here, iam using javascript and ajax.And i am creating a new file to create response(say newfile.php) Try this,
function getCode(){
var v =document.forms["form1"]["part_code"].value;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
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)
{
var getPartCode=xmlhttp.responseText; //Getting the response from php file
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
}
}
xmlhttp.open("GET","newFile.php?q="+v,true); //Sending request to newfile.php
xmlhttp.send();
}
</script>
newfile.php
<?php
$value = $_GET["q"]; //getting the value sent through tthe ajax request
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$value'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
echo $code_part['count'];
}
?>
Best Method is Ajax
Otherwise Use Cookies
For Eg:
<script type="text/javascript">
document.cookie = "cookieName=cookieValue";
</script>
<?php
$phpVar = $_COOKIE['cookieName'];
echo $phpVar;
?>
Your code
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
document.cookie = "cookieName="+v;
<?php
$phpVar = $_COOKIE['cookieName'];
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$phpVar'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
Updated
Check this
function getCode(){
var v = 12;
document.cookie = "cookieName="+v;
var getPartCode = <?php echo $_COOKIE['cookieName']; ?>
alert(getPartCode);
}

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 );

Trying to return php data from ajax

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";

Categories