I am trying populate a form from a mysqli database when an option is selected from a drop down. I am trying to do this with an ajax 'get' call to a PHP page. The PHP page does the SQL query and returns the results, then I do a json_encode of the data. This puts the JSON into an array. Then the ajax function attempts to parse the JSON. However this is where the problem lies. The JSON data comes in as an array and the JSON.parse(xhr.response) fails to parse.
[{"id":"12","accountnum":"2148","name":"Blah","address":"123 Dan Hwy","city":"ANY Town","state":"IA","zip":"11111","phonenumber":"555-555-5555","brand":"Dan","create_date":"2021-06-14 15:47:36"}]
//////////////////////////////////////////////////
<script>
const selectElement = document.querySelector('.accountnum');
selectElement.addEventListener('change', (event) =>{
const result = document.querySelector('.result');
var eventResponse = `${event.target.value}`;
result.textContent = 'the account num is ' +eventResponse;
loadAccounts(eventResponse);
});
</script>
///////////////////////////////////////
function loadAccounts(eventResponse){
var xhr = new XMLHttpRequest();
var url = "users.php";
var geturl = xhr.open('GET', url+"?accountnum="+eventResponse, true);
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE) {
if(this.status == 200){
console.log(xhr.response);
var accounts = JSON.parse(xhr.response);
console.log(accounts.id);
console.log(accounts.name);
var output = '';
for(var i in accounts){
output += '<div class="form-group">' +
'<label for="accountname">AccountNum*</label>' +
'<input type="text" class="form-control" id="accountnum" name="accountnum" value= '+accounts[i].accountnum+ '>' +
'</div>'
}
document.getElementById('accounts').innerHTML = output;
}
}
}
xhr.send()
}
</script>
////////////////////////////////////////////////
<?php
$accountnum = $_GET['accountnum'];
$query = "SELECT * FROM accounts WHERE accountnum = $accountnum";
$result = mysqli_query($conn, $query);
$accounts = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($accounts);
?>
Your response is an array, not an object. Try reassigning the accounts variable like accounts = accounts[0];. Or make your php script extract the first element from the result set and json encode it loke echo $accounts[0] ?? null;
Related
Suppose I am retrieving the data(in json form) from the first.php and second.php(coding in php). I want to assign this json data in the array of the jQuery array. let the array is var total = [index1,index2] the first json data coming from the first.php will assign to the first index of the total and the second json data coming from second.php assign to the second index of the total. how will I do this. I have tried the following code. I am the bigner so if there is any mistake then sorry. for replying me thank you.
jquery
var total = ['index1','index2'];
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "first.php";
var asynchronous = true;
ajax.open(method,url,asynchronous);
//sending ajax request.
ajax.send();
//receiving response from the first.php
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(this.responseText);
for(var a=0; a<data.length; a++){
total['index1']=data[a];
}
}
}console.log(total['index1']); //i want the output here
var url="second.php";
ajax.open(method,url,asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data1 = JSON.parse(this.responseText);
for(var a=0; a<data1.length; a++){
total['index2']=data1[a];
}
}
}
first.php
include 'connection.php';
$data = array();
$query=mysqli_query($con,"select * from tabel_name ORDER BY id ASC");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
$data[] =$row;
};
echo json_encode($data);
}
second.php
include 'connection.php';
$data = array();
$query=mysqli_query($con,"select * from tabel_name ORDER BY id ASC");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
$data[] =$row;
};
echo json_encode($data);
}
I just wan to assign the first json array to index1 and show in console.log and second json array to the index2.
I found the problem. You use "this" in onreadystatechange callback, but "this" don't design your "ajax" variable.
I have renamed your "ajax" variable in "ajax1" and I have created a second "ajax2".
Please try this code :
var total = {index1: [], index2: []};
var ajax1 = new XMLHttpRequest();
var method = "GET";
var url = "first.php";
var asynchronous = true;
ajax1.open(method,url,asynchronous);
//receiving response from the first.php
ajax1.onreadystatechange = function(){
if(ajax1.readyState== 4 && ajax1.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(ajax1.responseText);
for(var a=0; a<data.length; a++){
total['index1'].push(data[a]);
}
console.log('=== index1 ===');
console.log(total['index1']); //i want the output here
}
}
//sending ajax request.
ajax1.send();
var ajax2 = new XMLHttpRequest();
var url="second.php";
ajax2.open(method,url,asynchronous);
ajax2.onreadystatechange = function(){
if(ajax2.readyState== 4 && ajax2.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data1 = JSON.parse(ajax2.responseText);
for(var a=0; a<data1.length; a++){
total['index2'].push(data1[a]);
}
console.log('=== index2 ===');
console.log(total['index2']); //i want the output here
}
}
ajax2.send();
You use a wrong property "lenght". A correct property is "length" in your "for" statements.
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(this.responseText);
for(var a=0; a<data.length; a++){
total['index1']=data[a];
}
// Here, server has returned response
console.log(total['index1']); //i want the output here
}
}
// Here, server has not yet returned response
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?
Simple question guys , i have AJAX that pickup all data from page and it suppose to open new php page to update MySQL database , its only updating last row of data , BUT when i use alert from javascript just to check all data i got he does update whole table ... is there any chance that AJAX is not working fast enough or something?
here is my code
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var MatchID = '';
var HomeTeam = '';
var AwayTeam = '';
var TipID = '';
var arrayMaxValues = 3;
var myArray = new Array(3);
var i = 0;
$('#teams_table input[type=text]').each(function () {
myArray[i] = $(this).val();
if (!!myArray[2])
{
MatchID = myArray[0];
HomeTeam = myArray[1];
AwayTeam = myArray[2];
if (HomeTeam > AwayTeam) {
TipID = 1;
}
else if (HomeTeam == AwayTeam) {
TipID = 2;
}
else if (HomeTeam < AwayTeam) {
TipID = 3;
}
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' +
TipID + '&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, true);
http.send(null);
myArray = new Array(3);
i=0;
}
else
{
i++;
}
});
It is kinda odd to me when i use
alert('MatchID = ' + MatchID + ' HomeTeamScore = ' + HomeTeam + ',
AwayTeamScore = ' + AwayTeam)
Inside of AJAX code i get whole table updated , without it just last row
And my php page
<?php
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$HomeScore = $_GET['HomeTeam'];
$AwayScore = $_GET['AwayTeam'];
$query="update probatip1.matches set ResultTipID=".$tipID.",HomeTeamScore = "
.$HomeScore.",AwayTeamScore= ".$AwayScore." where MatchID =".$matchID;
$UpdateGame= mysql_query($query) or die(mysql_error());
mysql_close()
?>
Try encoding the data. i.e:
MatchID = encodeURIComponent(myArray[0]);
HomeTeam = encodeURIComponent(myArray[1]);
AwayTeam = encodeURIComponent(myArray[2]);
in php use
function escapedata($data) {
if(get_magic_quotes_gpc()) {
$data= stripslashes($data);
}
return mysql_real_escape_string($data);
}
to escape your data before updating the table. i.e:
$query="update probatip1.matches set ResultTipID=".escapedata($tipID).",HomeTeamScore = ".escapedata($HomeScore).",AwayTeamScore= ".escapedata($AwayScore)." where MatchID =".escapedata($matchID);
Hope this works.
Not really a direct answer, just something that you can base your answer from. What the code does is to submit a whole object using the $.post method in jquery which takes in 2 parameters and a callback function which is executed once the request is done.Not really sure by: open new php page to update MySQL database but I assume that you're simply using that page to update the database and not actually open it.
<script src="js/jquery.min.js"></script>
<script>
var obj = {
'teams' : [
{'name' : 'teamA', 'grade' : 'A'},
{'name' : 'teamB', 'grade' : 'B'}
]
};
$.post('access.php', {'obj' : obj}, function(data){
var d = JSON.parse(data);
for(var x in d){
console.log(d[x].name);
}
});
</script>
access.php:
<?php
$post = $_POST['obj']['teams'];
$array = [];
foreach($post as $row){
$name = $row['name'];
$grade = $row['grade'];
$array[] = ['name'=>$name, 'grade'=>$grade];
}
echo json_encode($array);
?>
So you only have to modify the php page, and put your database query inside the loop. This way you won't need to perform so many ajax request by putting it inside $.each
Then utilize $.each to build the object that you're going to submit via ajax through $.post method:
var obj = {};
$().each(function(index){
var myArray[i] = $(this).val();
var MatchID = myArray[0];
var HomeTeam = myArray[1];
var AwayTeam = myArray[2];
obj[index] = [];
obj[index]['match_id'] = MatchID;
});
The problem is with your logic in the way you are sending requests to php file to update the MYSQL. Actually you are running the ajax request in a loop and the loop is too fast that kills the previous update request.
Solution
You can compose an array and send it to the php outside the loop. That will work for you.
Guys with your help i managed to fix my problem
http.open('get', 'adminUpdate.php?MatchID=' + MatchID + '&TipID=' + TipID +
'&HomeTeam=' + HomeTeam + '&AwayTeam=' + AwayTeam, false);
http.send(null);
var response = http.responseText;
So basicly with this line i told http request not to go for next line of code until update in table is not completed , when http has done his job then it moves on next line of code.
Thank you for help
updated
i'm having 2 pages. An index page connected to a js file. This js file containing ajax code fetching data from database.
this is my js file
$(document).ready(function() {
// getting links from db andshow sub_menu div //
$(".menu_item").mouseover(function(){
$(this).addClass("selected").children().slideDown(500,function(){
var id = $(".selected").attr("id");
var ajax= false;
ajax = new XMLHttpRequest();
var qst = "?id="+id;
ajax.open("GET","ajax/get_sub_cats.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
$(".sub_menu[title="+id+"]").html(ajax.responseText);
}
}
ajax.send(null);
});
});
// hiding sub_menu div //
$(".menu_item").mouseout(function(){
$(this).removeClass("selected").children(".sub_menu").slideUp(500);
});
// keeping sub_menu div visible on mouse over //
$(".sub_menu").mouseover(function() {
$(this).stop();
});
// clicking sub menu link in the menu //
$(document).delegate("a#subCatLink","click",function(){
alert("test");
});
// document ready end
});
and this is get_sub_cats php file used to fetch links from db
<?php
require('../_req/base.php');
$id = $_REQUEST['id'];
$getSubcatsQ = "select * from sub_cats where Main_Cat_ID = '$id'";
$getSubcatsR = mysql_query($getSubcatsQ);
$numrows = mysql_num_rows($getSubcatsR);
while($row = mysql_fetch_array($getSubcatsR)){
?>
<a id="subCatLink" href="products.php?id=<?php echo $row['Sub_Cat_ID']; ?>"><?php echo $row['Sub_Cat_Name']; ?></a><br />
<?php
}
mysql_close($connect);
?>
clicking links coming from the other php file using ajax is not working at all
Sorry, maybe this will help, maybe not. But...
Why don't you use something like this:
jQuery
$(".menu_item").mouseover(function(){
var id = $(".selected").attr("id");
var qst = "?id="+id;
var html = '';
$.getJSON('ajax/get_sub_cats.php'+qst, function(data){
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<a id="subCatLink'+data[i].Sub_Cat_ID+'" href="products.php?id='+data[i].Sub_Cat_ID+'">'+data[i].Sub_Cat_Name+'</a>';
}
$(".sub_menu[id="+id+"]").html(html);
});
});
PHP
require('../_req/base.php');
$return = array();
$id = $_REQUEST['id'];
$sql = "select * from sub_cats where Main_Cat_ID = '$id'";
$result = mysql_query($sql);
while($ln = mysql_fetch_array($result)){
$return[] = $ln;
}
echo json_encode($return);
ok try this
$(document).delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
});
That should, as a test, show the href for every link on your page. If that works, put all the links you want to show in a div. Then call it with
$('#divID').delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
})
I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?
Here are my code pages. First is the trimmed down version of the form calling the JavaScript.
<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
<table align='left'>
<tr>
<td class='reporttd'>Vendor</td>
<td>
<select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
<option value='' selected='selected'></option>
<?php echo $vendorOptionList; ?>
</select>
</td>
</tr>
<tr>
<td class='reporttd'>Service Code</td>
<td class='reporttd'>
<select name='selServiceCode' id='selServiceCode'>
<option value='' selected='selected'></option>
</select>
</td>
</tr>
</table>
</div>
</div>
</form>
JavaScript page
//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlhttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new Activexobject(xmlHttpVersions[i]);
}
catch(e) {}
}
}
if (!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
//Call page to get all service codes for a vendor.
function getServiceCode(){
if (xmlHttp){
try{
var vCode = document.getElementById("selVendorCode").value;
var parms = "vCode=" + vCode;
//Call Transaction_AJAX.php to pass back an XML.
xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e){
alert("Can't connect to server:\n" + e.toString());
}
}
}
//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
handleServerResponse();
}
catch(e){
alert("Error reading the response: " + e.toString());
}
}
else{
alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
}
}
}
//Handles response from the server
function handleServerResponse(){
var xmlResponse = xmlHttp.responseXML;
if (!xmlResponse || !xmlResponse.documentElement){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == "parsererror"){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "root" || !xmlRoot.firstChild){
throw("Invalid XML structure:\n" + xmlHttp.responseText);
}
//Get response and load it into drop down
responseText = xmlRoot;
var sel = document.getElementById("selServiceCode");
sel.options.length = 0;
var opt = document.createElement("option");
document.getElementById("selServiceCode").options.add(opt);
for(var i=0; i < responseText.childElementCount; i++){
var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
sel.options[sel.options.length] = newOpt;
}
}
The PHP page creating the XML file
<?php
header('content-type:text/xml; charset=utf-8');
include("../includes/DBConn.php");
$vCode = $_GET['vCode'];
///Setup cursers and proc command
$curs = OCI_New_Cursor($c);
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");
OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);
//execute statment and cursors
oci_execute($stmt);
oci_execute($curs);
//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) {
//Add node for each row
$occ = $dom->createElement("cell");
$occ = $root->appendChild($occ);
//Id Value
$id = "value";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
//Id text
$id = "text";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();
//Echo XML back to Transaction_Update.js
echo $xmlString;
?>
Here is how you do it in jQuery
1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
In your javascript
$("#stateDropDown").change(function(){
var stateId=$("#stateDropDown").val();
$.ajax({
url: 'getcities.php?stateid='+stateId,
success: function(data) {
$("cityDropDown").html(data);
}
});
});
Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.
The above code will do the follolwing
1) When the value of state dropdown changes, it executes the inside code.
2 ) Reade the selected item value and store it in a variable called stateId.
3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid
4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.
5) setting the received response (data) as the inner html of the city dropdown.
Assuming the getcities.php page will return some output like this
<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>
jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.
http://www.jquery.com
You can change your for loop in handleServerResponse to the following to fix this issue:
for(var i=0; i < responseText.childNodes.length; i++){
var node = responseText.childNodes[i];
var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
var newOpt = new Option(text,value);
sel.options[sel.options.length] = newOpt;
}