I have problem with the code further down.
In html file:
<form id='changeAccountForm' action='usermenu.php' method='post'>
Name:<input type="text" name="name"/>
Surname:<input type="text" name="surname"/>
Password:<input type="password" name="password"/>
Phone:<input type="text" name="phone"/>
Paid mail:<input type="text" name="paidMail"/>
Payment method:<input type="radio" name="paymentMethod" value="0"/>paypal
<input type="radio" name="paymentMethod" value="1"/>payza
<div id="changeAccountInformation" >change</div>
</form>
In Javascript file I use Javascript and jQuery. I use javascript with ajax and the function called:
function ajaxInit(){
var ajaxRequest;
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;
}
}
}
return ajaxRequest;
}//end function ajaxInit
function updateUserDataWithAjax(){
var ajaxRequest = ajaxInit();
// Create a function that will receive data
// sent from the server and will update
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
// find all form elements and add the responseText to placeholder attribute
var childNodes = $("#changeAccountForm").children(),i,j=0;
var inputAjaxRequest = ajaxRequest.responseText;
//inputAjaxRequest = inputAjaxRequest.plit(",");//ERROR:
for(i=0; i<childNodes.length; i++)
if(childNodes[i]!= "input"){
childNodes[i].setAttribute("placeholder",inputAjaxRequest[j++]);
}
}
}
var namesArray = "userId,password,name,phone,";
namesArray+= "surname,paidMail,payMethod,";
namesArray+= "score";
namesArray = namesArray.split(',');
//gets all the childnodes and find these with attribute
var childNodes = $("#changeAccountForm").children(),values,names,i;
var queryString = '';
var first = true;
for(i=0; i<childNodes.length; i++)
for(j=0;j<namesArray.length;j++)
if(childNodes[i].getAttribute("name")==namesArray[j]){
values = childNodes[i].value;
names = childNodes[i].getAttribute("name");
if (first){
queryString += names+"="+values;
first = false;
}else
queryString += "&"+names+"="+values;
}
ajaxRequest.open("POST", "usermenu.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString .length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
//and i call this function
$(document).ready( function(){
$("#changeAccountInformation").click(function(){
var user = updateUserDataWithAjax();
});
});
In php file:
when i use the method post something going wrong and prints Undefined index: [key value name] in. The response text from ajax is an array with the name of html file.
include "userMenu.html";
isset($_POST['name']);
echo $_POST['name'];
Any information will be appreciated, thank you.
Related
Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console
To clarify my question, how can I retrieve a global variable from an AJAX JSON request
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class="src">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>
<div id="Name">Sachin</div>
</td>
<td>
<div id="Country">India</div>
</td>
</tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</div>
The best way to approach this is by using what's called a callback function. A callback function is a function that is invoked when specific event takes place. In your case that event is the data being retrieved from your JSON endpoint (URL).
The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. If you want to make that data also accessible globally, part of the callback function can update your global variable.
In the updated code below we first declare a global variable globalJSON that holds our data. Before you receive any data (i.e. before you click the button) the value of globalJSON.data will be null. Once the data is received the callback function updateView() is called with the received data. Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (i.e. updating the required HTML elements).
You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked.
// declare your global variable that will get updated once we receive data
var globalJSON = {
data: null
}
// this gets executed the moment you load the page - notice the value is null
console.log(globalJSON.data);
// this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function
function updateView(data) {
// this will update the value of our global variable
globalJSON.data = data;
// this is the rest of the logic that you want executed with the received data
document.getElementById("Name").innerHTML = data.name;
document.getElementById("Country").innerHTML = data.country;
// this will show that the global variable was in fact updated
console.log(globalJSON.data);
}
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
updateView(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText);
But you won't have any way of knowing when it's defined outside of the event handler. However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value.
full code:
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(JSON.parse(http_request.responseText));
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
Declare a variable at first like var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ). access the variable in your function. A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. As a result you got an error something like that
Blocked loading mixed active content "http://www.tutorialspoint.com/json/data.json"
So change the url also to https://www.tutorialspoint.com/json/data.json.
Then you can parse the result as you want.
<title>tutorialspoint.com JSON</title>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON();">Update Details </button>
</div>
<script>
function loadJSON(){
var jsonObj= '';
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
console.log(jsonObj);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
I've searched everywhere but can't find an answer to this problem.
I'm writing a little ajax script but can't get the correct value of the POST request.
This is the code so far:
<textarea id="message" name="message" style="width:100%;"></textarea>
<input value="SEND" style="border-radius: 5px 5px 5px 5px;" type = 'button' onclick = 'ajaxFunction()'/>
<script type="text/javascript"> <!--
//Browser Support Code
function ajaxFunction(){
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 and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('chbox');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var message = document.getElementById('message').value;
var queryString = message ;
ajaxRequest.open("POST", 'chatdata.php', true);
//ajaxRequest.send(null);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send('queryString');
}
</script>
<?php
$message1 = $_REQUEST['message'];
echo $message;
?>
when i use print_r($message); to see the content of the POST value
this is what i get Array ( [queryString] => ). It has no values.
What could be wrong with my code?
(I would have used jQuery but i'm not well grounded in it yet.)
I fixed some bugs and code start works:
1.
<p id="chbox"></p> <!-- ajaxDisplay need this -->
2.
ajaxRequest.send("message="+queryString); //queryString is variable so without quotes
3.
var_dump($message1); //there was message without 1
Here's how you would do it in jQuery - much simpler:
$('#mybutt').click(function(){
var txt = $('#message').val();
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: 'ta=' + txt,
success: function(d){
if (d.length) alert(d);
}
});
}); //END mybutt.click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="message" name="message" style="width:100%;"></textarea>
<input id="mybutt" value="SEND" style="border-radius: 5px 5px 5px 5px;" type='button' />
my_ajax_processor_file.php
<?php
$txt = $_POST['ta'];
$out = 'You sent: ' .$txt;
echo $out;
Here are a bunch of free 5-min video tuts for jQuery
The trouble is with query string. You should put ajaxRequest.send(queryString) instead of ajaxRequest.send('queryString');. Don't use query string just use the name of the variable. It should work!
I have a problem with my ajax call, ive been searching here and cant find a answer to.
here is what happened the script worked great one second then when i logged in to use it again it just shows me my main index page any time i put http:// inside the text area here is the code.
function is_valid_url()
var ajaxRequest;
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 ajaxDisplay = document.getElementById('output');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var text = document.getElementById("text").value;
var queryString = "?text=" + text;
ajaxRequest.open("GET", "textscraper.php" + queryString, true);
ajaxRequest.send(null);
}
here is the html
<textarea id="text" onkeyup="is_valid_url()" placeholder="What do you think?" class="posttext">
</textarea>
any help is appreciated.
the following javascript function only seems to work when i have the final confirm() statement which I had originally in there for debugging purposes. when i take it out, delete_row.php doesn't seem to run. also, and perhaps as a hint/side-note, when i do have the confirm statement in there, it works on all browsers except for safari...
function deleterow(form) {
if (!confirm("Are you sure you want to delete?")) return false;
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
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;
}
}
}
var ajaxRequest; // The variable that makes Ajax possible!
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
confirm('Delete successful!');
}
UPDATE SOLVED
i was checking the status of the ajaxRequest through the following js script change
ajaxRequest.onreadystatechange = function(){ // Create a function that will receive data sent from the server
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
else{
alert('An error has occurred making the request');
return false;
}
}
and noticed i was getting a status of 0 back from the server. some googling around helped me realize that the error lied in how i was defining the buttons which were calling these functions.
original code was:
<div style='float:left; margin-right:10px;'><input type="submit" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
fix is:
<div style='float:left; margin-right:10px;'><input type="button" onClick="deleterow(document.myForm)" VALUE="Delete ROWs"></div>
(submit type has to be changed to button type)
delete_row.php doesn't seem to run have you verified this, can you add an alert to if(ajaxRequest.readyState == 4){ I tried your JS though without the form stuff and it seems to work fine, http://jsfiddle.net/6gjy6/ Do you get any JS errors in Google Chromes console? Have you tried doing a basic "GET" request on the browser with the appripriate url ie delete_row.php" + queryString, and seeing how the server responds instead of the AJAX call.
try this:
var queryString = "?ID=";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += "-";
}
}
queryString = queryString.slice(0, -1);
var ajaxRequest;
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){
alert("received: " + ajaxRequest.responseText);
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "delete_row.php" + queryString, true);
ajaxRequest.send(null);
I'm fairly sure you're supposed to set the onreadystatechange event after calling open, otherwise the handler is cleared.
keep your confirm() statement there while at the top of your js put
window.alert = null ;
and try
k let me check
I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>