I am trying to use AJAX and Javascript (no jQuery) to update a DIV on my page to display an AJAX request based off of the user submitted response.
I have two questions.
1) How can I alter the AJAX request based off the user submitted response? I would also like to store the response for other AJAX requests on the same page as well. The below code does not seem to return anything to my browser and is not updating the DIV.
function loadXMLDoc(){
var xmlhttp = new XMLHttpRequest(),
userReq = documents.forms["form"]["req"].value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxRequest" + "userReq",true);
xmlhttp.send();
}
2) The AJAX request I'm using returns a JSON object. How do I use Javascript to modify and only display particular values of the returned JSON?
i.e The following JSON is returned from an AJAX call, only update the DIV to show Anna's last name, "Smith".
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
ad 1) userReq is a variable containing a value, if you use it as "userReq" you will get the literal string "userReq" rather than the value of the variable userReq
xmlhttp.open("GET","ajaxRequest?userReq=" + userReq,true);
This will allow your server side script to receive the value of userReq in the request variable named "userReq"
ad 2) JSON is the Javascript object notation, so using JSON in Javascript is quite easy
var myObject = JSON.parse(xmlhttp.responseText);
// get only Anna's last name
document.getElementById("myDiv").innerHTML = myObject.employees[1].lastName;
Related
I am new to JavaScript and and trying to pass a session variable from 'Name' which has a variable already assigned using PHP and pass it into 'cartItem' upon button click.
To my knowledge the current code stores the value of 'Name' into var item then requests HTML to the server to return and update the session variable 'cartItem' with the value stored in var item.
Button and script:
<button id='addToCart' onclick='addToCart'>Add to cart</button>
<script>
function addToCart(){
var item = sessionStorage.getItem('Name');
item = new XMLHttpRequest();
item.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
sessionStorage.setItem('cartItem', item);
}
}
}
</script>
cartItem is then displayed in my navbar using a function which is called across all pages
<span class='item-info'>
<span>" . $_SESSION['cartItem'] . "</span>
</span>
But it does not show. Any advice would be greatly received.
You have created an XMLHttpRequest object but have not opened a URL or sent the request.
Example (not tested):
var name = sessionStorage.getItem('Name');
var item = new XMLHttpRequest();
item.open("GET", "http://www.example.com/endpoint/" + name);
item.send();
After this, the object "item" will contain information such as the response body and HTTP status code.
If I understand correctly, you are using a sessionStorage object to store PHP session variable values on the Javascript / HTML document, correct? If so, then understand that when you try to change a value, you are only changing it on the client side, the server side (or PHP side) remains unaffected).
It looks like you have the right idea with the XMLHttpRequest, but in order to get done what you need to do, you'll need to make a PHP script which the Javascript function will ajax to. Here's a little mockup:
<?php
//NOTE: this does not do any input sanatation
//name of this script is changeVal.php
$keyAr = ["Name","Price","Value","Other"];
if (in_array($_POST['key'],$keyAr) {
$_SESSION[$_POST['key']] = $_POST['val'];
}
I am intentionally using an array in this manner rather than $_SESSION[$_POST['key']] so that a potential hacker can't change the value of ANY session variable.
Once you have the script above, you can make an ajax request onto that script, where key is the name of the var to change and val is the value to change it to.
NOTE: this does not perform any sanatation or protection for the input material. This is just a simple mockup.
I have been trying to get my JSON code from a PHP file which is connected to my database to display on my website using an XMLHttpRequest, but we cant split them and display it.
We are using an php file example.php that does the following:
function jsonFromQuery($result) {
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json[] = $r;
}
} else {
$json = "Table is empty";
}
return json_encode($json);
}
This will display the json code as following on the website if you open the php file:
[{"UserID":"2","Firstname":"Piet","Lastname":"Klaas","Age":"23","Specialization":"Voet","Branch":"Been","Interests":"Hoofd","Hospital":"OLVG","Email":"pietklaas#gmail.com","ProfilePicture":""}]
With this we use the following javascript file to request this php file and stringify and try and display it.
var request = new XMLHttpRequest;
request.open('GET' , 'http://myurl.nl/example.php', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
var obj = JSON.stringify(request);
var firstname = obj.Firstname;
document.writeln(firstname);`
But I get a massive string which includes the type status etc. And don't know how to split this up to display on their own. For example only Firstname = Piet on the page.
When you get the data back from PHP it's already in the form of a string. You need to use JSON.parse() to convert it into an object you can use. Try...
var obj = JSON.parse(request.responseText);
var firstname = obj[0].Firstname;
document.writeln(firstname);`
Note as well that the Json you're getting back is a list of objects: [{...},{...},{...}], so you can't just call .Firstname as you haven't specified which object you care about. Hence the [0] in the example above to pick out the first object.
One other thought... At present if your PHP doesn't find any results it's going to send back something that isn't in the format you're expecting. Consider either wrapping the list in an object with a status...
{
"Success": true,
"Results": [{...}, {...}]
}
Or make the PHP script return a different HTTP code to indicate failure (404 seems appropriate here)
For future reference, JSON.stringify does the opposite - it takes a complex object and converts it into Json
You are parsing the whole XMLHttpRequest object
var obj = JSON.parse(request);
try using just the response body
var obj = JSON.parse(request.responseText);
Hi so I have a project for class that is a mix of PHP, HTML, and javascript/Ajax.
One of the requirements is "Execute program.php on server passing it the N/V pairs following the "?" symbol." How do I do this?
First off.. I don't know what NV pairs are and the reading links we were given say nothing about them.. I Googled "Php nv pairs" and literally nothing relative comes up.
I did an in-class activity that upon clicking a button, the url would update and add stuff after the "?" but of course that same code isn't doing it anymore. My professor is terrible at explaining anything and leaves us to follow his typo instructions that aren't even complete..
Here's the code we were given with his comments trying to explain what to do:
// startgame function
// sart button pressed check fields, if OK send to PHP via get request
function startgame(){
//Create the XMLHttpRequest Object
var xmlhttp;
// error handling
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
http = xmlhttp;
// The PHP server script, called with N/V pair with GET request
// Using get request the NV pairs follow "?"
// execute program.php on server passing it the n/v pairs
// that follow the "?"
var url = "program.php?player1name=";
// for this example, only pass to PHP games played
// "&" separates n/v pairs
// player1name is name of algorithm player 1 is using
player1name = document.JForm.p1name.value;
player2name = document.JForm.p2name.value;
gamesplayed = document.JForm.gamesplayed.value;
sdata = url+player1name+"&gamesplayed="+gamesplayed;
// for a "real" solution, pass more data to PHP about state of game
// send get request to server with n/v pairs of screen data
http.open("GET",sdata, true);
// register with server what function to return data
http.onreadystatechange = handleHttpResponse;
// send request to server
http.send(null);
}
Anything will help, thanks!
NV apis means "Name/Value pairs". Basically, in the terms you will be using them in, it is a key connected to its value with an equal sign. For example: username=johnconde. username is the key and johnconde is the value. An example more closely related to your code would be gamesplayed=20. gamesplayed is the key and 20 is the value.
Name/value pairs are commonly found in query strings and it looks like that's what you need to do with your code. You need to build a query string comprised of name/value pairs containing the values you need for your PHP script to do whatever it is it needs to do. It looks like the code already does this and you just need to build the form necessary for this JavaScript to work.
I've seen many similar issues, but they didn't provide answer for my question.
My Server form JSON string and put it into response:
List<String> list = getSomeList();
JSONArray jsArray = new JSONArray(list);
System.out.println(jsArray);
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
But in my javascript handle function when I alert response, it alert ALL page!
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
alert(response); //alert all page!
var list = JSON.parse(response.toJSON()); //doesn't work!
}
}
Question: how could I separate only jsArray in javascript?
P.S. As I understand, my JSON.parse(response.toJSON()) doesn't work because response contain the whole page?
Disclaimer: I don't know java.
Server-side, the problem is probably that your response is not closed after writing your JSON Array, allowing other (html) text to be written. Try this:
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
response.getWriter().close();
Client-side, responseText is a string, and strings don't have a toJSON() function defined.
var list = JSON.parse(http.responseText);
should suffice.
I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.