Get multipe response using AJAX and PHP - 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.

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..

Pass DOM element values to PHP using AJAX

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

Sending Javascript Object to PHP via Ajax

I'm learning Ajax by failure and have hit a wall:
I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.
I have a function that is called when the user clicks the 'save' button. The function is as follows:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
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('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
My question is:
What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?
furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?
Thanks in advance.
If your array has more then 1 dimension or is an associative array you should use JSON.
Json turns a complete array structure into a string.
This string can easily send to your php application and turned back into a php array.
More information on json: http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
In php you can decode the string with json_decode:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&' to the query string each time.
furthermore, should I try using JSON?
You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.
And if so, how could I send a JSON object via ajax?
There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).
I found this question useful for Javascript enthusiasts.
Sending a javascript Object, be it js array or js object, you must stringify the setup before putting it to the server for decode & processing.
Stringifying a js object:
Based on your function:
case of Javascript Array object
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
case of Javascript Object object
let my_obj = {
name: "Daniel",
age: 23,
location: "Nigeria"
}
my_obj = JSON.stringify(my_obj);
Ones on point you can push this to the server, as per use case, u're working with AJAX GET method in sending your stringified object to the server.
Here is the full code:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById('message').innerHTML = this.responseText;
// if your returned response is in json, please, do ensure to parse the response before displaying
// like this JSON.parse(this.responseText)
}
}
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
var url = "create_amenities.php?my_json=" + my_array;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here are what i noticed out of your codes:
You don't need to call xmlhttp inside of xmlhttp object again, all you need is the this
I included the my_json parameter that holds the array object you are sending to the server.
Now, here in the server, you will need to catch the object and convert it to php readable object.
$my_json = $_GET['my_json'];
$my_json = json_decode($my_json);
Now, you can do whatever you wish it, because it has now become a full php array.
Example to pick the first array option:
$first = $my_json[0];
echo json_encode($first) // hahaha, you echoed it for AJAX to display
// i used to json_encode() to convert from php object to a js readable object
First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.
The best approach to your actual problem would be to submit your array as cgi parameters.
If the checkboxes are in a form, you need to do very little - simply submit the form,
<form><input type=checkbox ...><input type=checkbox ...>
$.post("test.php", $("#testform").serialize());
See http://api.jquery.com/jQuery.post/ for more details on how to do that.
Your list will turn up as an array in PHP.
Or to augment your own example with something very simple, do this:
url = url + '?checkboxes=' + checkboxes.join(',');
Now just split it inside PHP and you've got it back!

Passing PHP variables back to JavaScript variables on original page as Ajax

I have some Ajax which passes a javascript variable to getfirstvals.php which then does its thing with the DB and echos out a table of values depending on the javascript variable I input. I now want to pass back these PHP variables which are being echoed, back to the original page that the javascript is being sent from in order to convert them into javascript variables to do calculations on. I'm not sure how to do this.
Below is how it works so far.
A range "slider" to select the values:
echo "<input id='slider' type='range'
min=\"$vartime[0]\" max=\"$timemax\" value=\"$vartime[0]\" step='any' />
<span id='range'> </span>"
......
selectslider.onchange=function changecolour(){
showValue(selectslider.value)
.....
<script type="text/javascript">
function showValue(str) {
if (str == "") {
document.getElementById("datatable").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("datatable").innerHTML = xmlhttp.responseText;
}
}
if (floorchoice!=0 && floorchoice!=1){
if (floorchoice==2)
{
xmlhttp.open("GET", "getfirstvals.php?q=" + str, true);
xmlhttp.send();
......
This sends "q" to getfirstvals.php which finds values matching q in th DB and echoes out all values in the same row as it. In this way, as q changes the echoed values change. As I mentioned above, I would like these values not only to be echoed, but to be passed back to javascript variables on the original page which can then be used for calculations. Below is what I mean by the values being echoed:
echo "<td>" . $FFlrOpenPlanTemp . "&#8451</td>";
echo "<td>" . $FFlrPCRoomTemp . "&#8451</td>";
echo "<td>" . $FFlrStudyRm6Temp . "&#8451</td>";
echo "<td>" . $FFlrStudyRm8Temp . "&#8451</td>";
Take a look at JSON. PHP has a function: json_encode which will take a PHP data object (ie array, but doesn't have to be an array) and encode it in javascript object notion.
In your JS you can then evaluate (tip: do not use eval, modern browsers have json parsers) to get the JSON data into Javascript object.
Example
If I have the following array in PHP:
$array = array( "test1" => 1, "test2" => 2, 3, array( 4, 5, 6 ));
And I json_encode that array, I wind up with the following string:
{"test1":1,"test2":2,"0":3,"1":[4,5,6]}
This is what you return back to JS (aka, echo out). You can parse this via the native parsing function JSON.parse in Javascript:
var obj = JSON.parse(phpReturnStr);
Voila. You have an object in JS passed in from PHP.
First, you could use a Javascript library to make it simpler and cross-browser. Then, I'd suggest you to pass your variables from PHP to JS with json_encode(). Just take a minute to see how jQuery.getJSON works, and it will be a child's play.

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