Pass DOM element values to PHP using AJAX - php

I'm trying to use AJAX, HTML and PHP all together to provide a seamless experience to the user. I'm having trouble passing the variable to the PHP form right now. It's a little complicated the way I went about it, I'm not sure if there is an easier way as this is my first experiment with AJAX.
To explain in detail:
<div class="block" id="articles"></div>
I have this division which loads the details and loads the article. Inside of this division I'm trying to allow the user to add comments relating to the article.
function viewDets(str) {
if(str == "") {
document.getElementById("articles").innerHTML = "";
return;
}
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) {
document.getElementById("articles").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "viewDets.php?q=" + str, true);
xmlhttp.send();
}
Using this is passes the variable to viewDets which then adds another container:
while($row = mysql_fetch_array($result)) {
$count++;
$taskComments = $row['Annotation'];
$userName = $row['Username'];
$timeStamp = $row['Time'];
echo "Comments";
echo "<p class=\"meta\">$count. $taskComments ($userName) -- $timeStamp</p>";
}
echo "</div></div></div></div></div></div>
<form name=\"inputCom\" method=\"get\">
<div class=\"four column\">
<div class=\"column_content\" id=\"commentInsert\">
<label>Enter Comment</label>
<input type=\"text\" id=\"comment\"value=\"\"></input>
<input type=\"hidden\" id=\"Uname\" value=\"$user\"></input>
<input type=\"hidden\" id = \"taskID\" name=\"taskID\" value=\"$q\" />
<button type=\"button\" id = \"commentSub\" onClick=\"insertComm(comment, Uname, taskID)\" />Enter Comment</button>
</div>
</div>
</form>";
The name of this division is commentInsert and I've set up the AJAX so that on click, it should push the variables to a PHP function that inserts into my database for comments.
The issue that I'm running into is that I can't get the comment to pass to that PHP function.
function insertComm(str, uname, id) {
insertC();
if(str == "") {
document.getElementById("commentInsert").innerHTML = "";
return;
}
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) {
document.getElementById("commentInsert").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "subCom.php?q=" + str, true);
xmlhttp.send();
};
I have been playing around with this function by trying to call things like document.getElementByID and calling that function as insertC(); but with or without the insertC() function I am still having issue passing the 3 variables in the Javascript function to the PHP function, I tried it with just one variable and I still have trouble getting it to pass.
Any help would be greatly appreciated. Sorry for the long post.

I think your problem is onClick=\"insertComm(comment, Uname, taskID)\" assumes that these 3 variables are automatically set based on id. They are not.
Instead, you need to read them from the DOM, for example:
var str = document.getElementById("comment").value;
var uname = document.getElementById("Uname").value;
var id = document.getElementById("taskID").value;
If you add these to the start of insertComm, then you won't need to bother passing in the arguments.
If you want your PHP script to have access to all 3 of these, you'll need to pass in uname and id as well as str when sending your request to subCom.php. Note: it's best practice to encode these parameters using encodeURIComponent, in case the user inserts unexpected characters (like &) which may mess up your request.

... onClick=\"insertComm(comment, Uname, taskID)\" ...
When the button is clicked, comment, Uname and taskID are resolved by document because you're using inline code; although this really shouldn't be relied upon, it works like this:
comment = document.getElementById('comment');
// etc
As such, your function insertComm() is called with DOM elements instead of actual strings. To use them inside your function you would use comment.value for instance:
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str.value), true);
Also note that I'm using encodeURIComponent() to prevent malformed URL's caused by spaces in the string value for example.
However, it would be considered better if you would pass the identifiers in the HTML like this:
... onClick=\"insertComm('comment', 'Uname', 'taskID')\" ...
And inside your insertComm():
var str = document.getElementById(comment).value;
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str), true);

Related

Live update php variable and simultaneously, show the value in a textbox

This is my table row click function in the file, 'BAConsult.php'. On click, showconsultationdata function will run.
$(document).ready(function(){ //table row click
}).on('click','.consultclick tr',function(e){
if(e.target.tagName === "TD"){
$(".consultclick tr").removeClass("highlight");
$(e.target).parent().addClass("highlight");
}
var dateconsulted = $(this).attr('value');
alert(dateconsulted);
showconsultationdata(dateconsulted);
});
This is my ajax script
function showconsultationdata(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Here is another php file called 'BAConsultRecordsAJAX.php' where i placed the ajax of the showconsultationdata.
session_start();
require('Config/Setup.php');
$q = $_GET['q'];
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareremarks=$row['skincareremarks'];
$skinconditionremarks=$row['skinconditionremarks'];
}
On table row click, $skincareremarks and $skinconditionremarks should be updated. And these values will show up in the textboxes in the 'BAConsult.php' page. How can i do this?
So, i followed #Jeff's method by using JSON. However, I realised that the xmlhttp.responseText wasn't only showing my JSON encoded code, but also my javascript which was why the JSON.parse method was unable run properly. I then did the following:
In my BAConsultRecordsAJAX.php file, i did this.
echo "<div id='test1'>";
echo json_encode(array('first'=>$skincareremarks,'second'=>$skinconditionremarks));
echo "</div>";
I gave this output a div called 'test1'.
Then, in my main file's AJAX script, i did this.
var a = JSON.parse($(xmlhttp.responseText).filter('#test1').html());
document.getElementById("test").value=a.first;
So basically, it filters out the rest of the xhtmlhttp.responseText outputs, and selects only the contents in the div where id='test1'.
Hope this helps those who have this problem too..

Get multipe response using AJAX and PHP

Is it possible to get multiple responses using AJAX and PHP?
The event triggered by a select box and when it changes value (onchange) it calls the JavaScript function and get xmlhttp.responseText.
But on responseText we can only change one value/innerHtml based on id.
I want to change 2 or more HTML using AJAX. Is it possible?
Here is my AJAX function:
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) {
document.getElementById("txtStockQTY"+baris).value = "Validating..";
}
else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtStockQTY"+baris).value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxGetStock.php?id="+id, true);
xmlhttp.send();`
And ajaxGetStock follows:
$idbarang = $_GET['id'];
include "../connect.php";
$resultSetStockType = mysql_query("SELECT STOCK_QTY,STOCK_QTYUNIT,STOCK_SIZE,STOCK_SIZE2 FROM TSTOCK WHERE STOCK_ID = $idbarang",$con);
if($resultSetStockType and mysql_num_rows($resultSetStockType) > 0) {
while($rowSetStockType = mysql_fetch_array($resultSetStockType)) {
echo $rowSetStockType['STOCK_QTY']." ".$rowSetStockType['STOCK_QTYUNIT'];
}
}
else {
echo "--- stok tidak ditemukan ---";
}
I want to get several return values from my AJAX and assign it to several inputs of type text.
Return JSON like this in php:
return json_encode([
'firstValue ' => 'my first value',
'secondValue' => 'my second value'
]);
Then in JS:
var data = JSON.parse(xmlhttp.responseText);
document.getElementById("txtStockQTY"+baris).value = data.firstValue;
Note: I hate jQuery except for one thing: ajax calls. I advise you to use it in order to avoid all these lines of code that makes the code hard to read :)
Instead of echoing the results straight from the database, you need to store them in an array and echo the JSON encoded array.
$array = array();
while($rowSetStockType = mysql_fetch_array($resultSetStockType)){
$tempval = $rowSetStockType['STOCK_QTY']." ".$rowSetStockType['STOCK_QTYUNIT'];
$array.push($tempval);
}
//When its done processing all the returned values, echo json_encoded array.
echo json_encode($array);
you will then have access to the array from javascript.
There are several ways to solve this problem, i'll try to explain some of them.
Return HTML elements
Return HTML code with inputs from your AJAX code and add them to a div with the use of innerHTML instead of .value like you are doing now.
Return JSON
Return the code as a JSON object with json_encode and use JavaScript JSON functions to populate your inputs. Alan Tan already provided you with an example while I'm typing this.

ajax callback function is empty

It's my first time on StackOverflow, please forgive me if I forget some important information or if my question sounds stupid!
I am building a web site which generates a list once the user writes a word and hits the "Send" button. Php is responsible for extracting the required data and returning it to the web page as a list.
My problem is that I then want to pass this data in a js function. I have read a lot of answers on StackOverflow concerning this, and it sounded like a callback function is what I needed. However, my js function keeps telling me that my node is null; it seems the data returned from ajax is not accounted for.
Here are some parts of my code:
<script>
var xmlhttp;
function loadXMLDoc(cfunc){
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var us = document.getElementById("user").value;
var ur = document.getElementById("wiki").value;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET","contributions_old.php?user="+us+"&wiki="+ur+"",true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
var parser = new DOMParser ();
var responseDoc = parser.parseFromString (xmlhttp.responseText, "text/html");
var text1 = responseDoc.getElementById('old1').value;
var text2 = responseDoc.getElementById('new1').value;
var dmp = new diff_match_patch();
dmp.Diff_Timeout = 0;
// No warmup loop since it risks triggering an 'unresponsive script' dialog
// in client-side JavaScript
var ms_start = (new Date()).getTime();
var d = dmp.diff_main(text1, text2, false);
var ms_end = (new Date()).getTime();
var ds = dmp.diff_prettyHtml(d);
document.getElementById('outputdiv').innerHTML = ds + '<BR>Time: ' + (ms_end - ms_start) / 1000 + 's';
}
});
}
</script>
It's of course the Send button that calls myFunction() at the bottom of my web page, once the user has entered a word.
I have also verified that my web page, once the list has been generated, has the divs with "new1" and "old1" as ids (they are generated through my php code).
Any help would be really appreciated! I feel like I've tried everything!
Thank you! :)
Highly recommend using jQuery or some other lib for this.
var url = "contributions_old.php?user=" + $("#user").val() + "&wiki=" + $("#wiki").val();
$.get(url);

Executing javascript script after ajax-loaded a page - doesn't work

I'm trying to get a page with AJAX, but when I get that page and it includes Javascript code - it doesn't execute it.
Why?
Simple code in my ajax page:
<script type="text/javascript">
alert("Hello");
</script>
...and it doesn't execute it. I'm trying to use Google Maps API and add markers with AJAX, so whenever I add one I execute a AJAX page that gets the new marker, stores it in a database and should add the marker "dynamically" to the map.
But since I can't execute a single javascript function this way, what do I do?
Is my functions that I've defined on the page beforehand protected or private?
** UPDATED WITH AJAX FUNCTION **
function ajaxExecute(id, link, query)
{
if (query != null)
{
query = query.replace("amp;", "");
}
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)
{
if (id != null)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
}
if (query == null)
{
xmlhttp.open("GET",link,true);
}
else
{
if (query.substr(0, 1) != "?")
{
xmlhttp.open("GET",link+"?"+query,true);
}
else
{
xmlhttp.open("GET",link+query,true);
}
}
xmlhttp.send();
}
** Solution by Deukalion **
var content = xmlhttp.responseText;
if (id != null)
{
document.getElementById(id).innerHTML=content;
var script = content.match("<script[^>]*>[^<]*</script>");
if (script != null)
{
script = script.toString().replace('<script type="text/javascript">', '');
script = script.replace('</script>', '');
eval(script);
}
}
and on certain events, I had to within the script addevent listeners instead of just making a "select onchange='executeFunctionNotIncludedInAjaxFile();'" I had to addEventListener("change", functionName, false) for this. In the script that is being evaluated.
When you update your page by doing something like setting a container's innerHTML to some updated content, the browser simply will not run the scripts in it. You can locate the <script> tags, get their innerHTML (IE may prefer innerTEXT), and then eval() the scripts yourself (which is pretty much what jQuery does, though it finds the scripts with a regex before updating the DOM).
Use this function:
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
then do parseScript(xmlhttp.responseText); when you're replacing/adding content.
In case some other people stumble upon this old thread, there is one issue with the accepted answer by Deukalion, there is one issue that may have been overlooked: as written, the script only looks for the first script tag. If multiple script tags exist, all others are overlooked.
A few minor tweaks would resolve the issue. Change one line from:
var script = content.match("<script[^>]*>[^<]*</script>");
To:
var script = content.match(/<script[^>]*>[^<]*<\/script>/g);
And another from:
script = script.toString().replace('<script type="text/javascript">', '');
To:
script = script.join("").replace(/<script type="text\/javascript">/g, '');
Now it will gather all the <script> code and execute them in the order found on the page. Otherwise it was an excellent solution.
After the AJAX request, you can make an "on success" function which can take the returned html and do something with it. Then something will be executed.
If there was a code example, then I could provide a code solution to the situation. But using just standard xmlhttprequest, the following could be done:
xhr = new XMLHttpRequest();
xhr.open("GET","ajax_info.txt",true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
}
xhr.send();
​

How to pass a javascript object array to php using POST

Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.

Categories