I feel like I'm probably about 90% of the way there, and just need some help with that last 10%. I've looked at a number of different examples, and tried to piece together a solution, but haven't figured it out, so I'm looking for some guidance.
I have a small html page, with a little javascript, and a short .php that is adding the received data to a database.
I can see that the code is getting into the ajax function, and then into the insert function. But it's not actually doing the insert. I suspect that it's never sending the data off to the php file, but I don't know that for sure.
Here's the html code:
<html>
<head>
<script type ="text/javascript" language="javascript">
function ajaxFunction(){
var ajaxRequest;
alert("enter ajax"); //just a testing line
try{
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
alert("enter insert"); //just for testing
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {"type": type, "vintner": vintner,};
$.ajax({
url: "bottleAdd.php",
type: "POST",
data: "myData",
success: function(data, status, xhr)
{
$("$bottleAdd").html(data);
$("type").val();
$("vintner").val();
}
});
}
</script>
<title>Simple Add</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="addBottle">
<table>
<tr>
<td>Type: <input type="text" id="type" /></td>
<td>Vintner: <input type="text" id="vintner" /></td>
</tr>
<tr>
<td><button onClick="ajaxFunction()">Save Bottle Now</button></td>
</tr>
</table>
</div>
<div id="responseDiv">Response will appear here</div>
</body>
</html>
And here's the php
<?php
require_once 'login.php';
$conn = mysqli_connect($db_hostname, $db_username, $db_password, $db_database) or die("Connection failed: " . mysqli_connect_error());
$wineType = $_POST['type'];
$vintner = $_POST['vintner'];
$sql = "INSERT INTO bottleSimple (winetype, vintner)"
. " values ('$wineType', '$vintner')";
if (mysqli_query($conn, $sql)) {
echo "Successfully Inserted";
} else {
echo "Insertion Failed<br />";
echo $sql;
}
?>
I know there are some things to do in the php (prevent sql injection for example). But right now, I'm less concerned about that, and more about just figuring out how to get this to run correctly.
Any help would be appreciated.
Thank you.
You mixed plain JS AJAX with jQuery's ajax wrapper.
Change your code to the following:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Simple Add</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type ="text/javascript" language="javascript">
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {"type": type, "vintner": vintner};
$.ajax({
url: "bottleAdd.php",
type: "POST",
data: myData,
success: function(data) {
$("#responseDiv").html(data);
}
});
</script>
</head>
The rest is without a change.
That way you will use jQuery AJAX.
By the way, it is a good practice to place meta tags a the beginning of your head tag, because tag like the charset will cause the browser to start reading your page again from the beginning.
You mixed two invoke methods of XHR - the native method and jQuery method.
If You go for native method with creating native xhr objct, You should operate only with the ajaxRequest variable which keeps the native XHR object. The solution is remove the code staring with
$.ajax
and, after define the onstatechange event, add Your request params, and finnaly send your xhr. So:
function ajaxFunction() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState === 4) {
var data = ajaxRequest.responseText;
console.log(data);
// do something with response data...
}
}
var type = 'atype';
var vintner = 'avintner';
var formData = new FormData();
formData.append("type", type);
formData.append("vintner", vintner);
ajaxRequest.open('POST', 'bottleAdd.php', true);
ajaxRequest.send(formData);
}
should work.
Try this: you may wrong use this code "mydata" it change to mydata..
for see result look in console.
function ajaxFunction() {
var ajaxRequest;
alert("enter ajax"); //just a testing line
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
alert("enter insert"); //just for testing
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {
"type": type,
"vintner": vintner,
};
$.ajax({
url: "http://stackoverflow.com/index.php",
type: "POST",
data: myData,
success: function(data, status, xhr) {
$("$bottleAdd").html(data);
$("type").val();
$("vintner").val();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<title>Simple Add</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="addBottle">
<table>
<tr>
<td>Type:
<input type="text" id="type" />
</td>
<td>Vintner:
<input type="text" id="vintner" />
</td>
</tr>
<tr>
<td>
<button onClick="ajaxFunction()">Save Bottle Now</button>
</td>
</tr>
</table>
</div>
<div id="responseDiv">Response will appear here</div>
</body>
</html>
Related
So i'd like to auto check the boxes based on the data from my database, whenever i click a table row. I'm currently using an AJAX script for this table row click, however, i can't figure out how to bring over the php variable value onto my main file's php variable and replace the value, from my other php file where i'm performing the AJAX php codes.
this is my main file's check box.
<input type="checkbox" name="skincareinuse[]" value="Lotion" <?php if(in_array("Lotion",$skincareinuse)) { ?> checked="checked" <?php } ?>/>Lotion<br>
this is my other php file where my AJAX script is drawing values from. I've done an explode and stored them in a php variable.
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
The problem is that in the php file where my AJAX script is drawing values from, the variable $skincareinuse could not be updated into $skincareinuse on my main php file.
Let's say even if i am able to use JSON to bring the value over, how do i go about storing it since JSON is being encoded into javascript?
Sorry if I didn't explain it right, please help!
#Iceman, is it possible to run .ajax function in an ajax script?
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
var xmlhttp;
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;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
$.ajax({
url: "BAConsultRecordsAJAX.php"
})
.done(function(data) {
console.log(data);
selectTestAnswer(data.key + "[]", data.value)
})
.fail(function() {
alert("error");
})
}
}
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
EXAMPLE:
$('#mybutton').click(function() {
$.ajax({
//sample json, replace with your data
url: "http://echo.jsontest.com/key/skincareinuse/value/Lotion"
})
//if data retrieval was successfull
.done(function(data) {
console.log(data);
//got data as json from server. NOw lets update the page(DOM).
selectTestAnswer(data.key + "[]", data.value)
})
//if data retrieval was a failure
.fail(function() {
alert("error");
})
});
//a simple function that if called with say with skincareinuse[] and Lotion marks the corresponding checkbox.
var selectTestAnswer = function(chkbox, value) {
$("[name='" + chkbox + "']").each(function() {
if ($(this).val() == value)
$(this).attr('checked', true);
else
if ($(this).attr('checked') == true)
$(this).attr('checked', false);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Lotion" />Lotion
<br>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Talcum" />Talcum
<br>
<script>
</script>
<br>
<br>
<button id="mybutton">RUN AJAX</button>
<br>
<br>this ajax calls this url : "http://echo.jsontest.com/key/skincareinuse/value/Lotion" returns this sample json:
<pre>
{
"value": "Lotion",
"key": "skincareinuse"
}
</pre>
</body>
</html>
I have demo-ed an example where the ajax reads the data from the server (here a test url) then update (ie. check the boxes) correspondingly.
This an example on how to do updation from AJAX. I suggest you read on how AJAX works.
I have an ajax call. This script is working fine when I put it in one file with the form that will be loaded with the script.
$(document).ready(function () {
$("#uploadbutton").click(function () {
var referenceNumber = document.getElementById('referenceNumber').value;
$.ajax({
type: "POST",
url: "selectReferenceOrder.php",
data: 'referenceNumber='+referenceNumber,
cache: false,
//data: $('form').serialize(),
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
alert('referenceNumber');
}
});
});
});
However, when I try to put it in an external file, it doesn't give me anything.
The script of this ajax is functioned as the script that will post the form into the php file.
Reference: <input type="text" id="referenceNumber" />
<input type="button" id="uploadbutton" value="SEARCH"/>
I have tried many ways of doing this, but it still doesn't work:
<input type="submit" value="SEARCH" onclick="collectActed()" />
function collectActed () {
var referenceNumber = document.getElementById('referenceNumber').value;
$.ajax({
type: "POST",
url: "selectReferenceOrder.php",
data: 'referenceNumber='+referenceNumber,
cache: false,
success:function(html) {
document.getElementById('outputReference').innerHTML = html;
}
});
}
Please, help.
Following code works well:
<html>
<head>
<title>Ajax Search</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function searchFor(suchbegriff) {
var xmlHttp = null;
// Mozilla, Opera, Safari sowie Internet Explorer 7
if (typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) {
// Internet Explorer 6 und älter
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = null;
}
}
}
// If object has been created
if (xmlHttp) {
var url = "search.php";
var params = "search=" + search;
xmlHttp.open("POST", url, true);
//Headerinformatio for POST request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
// Zurückgeliefertes Ergebnis wird in den DIV "ergebnis" geschrieben
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
};
xmlHttp.send(params);
}
}
</script>
<script>
$(document).ready(function(){
$("input").click(function(){
$("div").load("search.php");
});
});
</script>
</head>
<body>
<input type="text" onkeyup="searchFor(this.value);"/>
<div id="search"></div>
</body>
</html>
I need help with an ajax call, but I'm a newbie with ajax and I'm not sure as to how to do it.
I have the following PHP code (phonecall.php):
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql="SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$callArray[] = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
print "<div id=\"call\">";
print_r($callArray);
print "</div>"
}
mysqli_close($con);
?>
I want to make a page update in real time automatically anytime something new is posted to the table.
Here is my non-working page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
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;
}
}
}
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('call');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
setInterval(function() { //Broken
ajaxRequest.open(); //Not sure what to put here.
}, 1000);
}
//-->
</script>
</body>
</html>
Your ajaxRequest.open() method takes 3 parameters, as per the XMLHttpRequest specification:
The method of the request (POST, GET, etc)
The file you're sending your request to
Whether or not the request will be asyncronous.
So:
ajaxRequest().open('GET','yourfile.php',true);
Would build an asynchronous GET request to yourfile.php.
You're also missing the ajaxRequest().send(), which would actually send your request to the server.
There's plenty to know about this so I suggest googling it, since you seem to be lacking on the basics.
I'm learning AJAX and XML this days. Recently I have ran into a stupid problem.
I try to build a simple program that will show me in a <div> all that I input into an input box.
For some reason when I try to use the .responseXML property my program won't run. Note that when I use the .responseText everything works fine.
my html code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<h3> the chuff bucket </h3>
<body onload="process()">
<input type="text" id="userInput"/>
<div id="underInput"></div>
</body>
</html>
my php code:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food=$_GET['food'];
echo $food;
echo '</response>';
?>
my js code:
// JavaScript Document
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
} else {
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cant create object");
}else{
return xmlHttp;
}
}
function process(){
var x = xmlHttp.readyState
if(xmlHttp.readyState==0||xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value)
xmlHttp.open("GET","foodstore.php?food=" + food , true);
x=xmlHttp.readyState;
xmlHttp.onreadystatechange= handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var xmlResponse= xmlHttp.responseXML;
root = xmlResponse.documentElement;
alert(root.firstchild);
//message= root.firstChild.data;
document.getElementById("underInput").innerHTML= '<span style="color:blue">' + xmlResponse + '</span>';
setTimeout('process()', 1000);
}else{
alert('not working');
}
}
}
Thanks to the helpers.
Did you tried with jQuery ? It may be easier to do. You can specify the data type
function ajaxJQueryRequest(url,afterReqFunction){
var request = $.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: "xml"
});
request.done(function(msg) {
afterReqFunction(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Ok I think I found the bug.
I entered the url of the php file (that sending the response to the html) and got the following error:
"This page contains the following errors:
error on line 2 at column 6: XML declaration allowed only at the start of the document"
after I deleted the blank space at the top of my php I received a new error, after I fixed the new error everything worked like a charm... thanks a lot!!
Hi all I have to connect to an external server to retrieve data.
They told me to use their script and I have to modify something because it was wrong. Now I ahve a problem when I try to lunch my request.
Return me an error into my internet explorer console
SCRIPT10: The data required for the completion of this operation are
not yet available.
This is my javascript page, the problem I think is because the query doesn't finish in time to print my result. How can I print the result when they are ready and don't return me error?
I have try to comment all my request and leave only the method "open" but the error return me every time. Why??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
var req = null ;
function sendRequest(){
var urlStr="www.test.it";
var xmlString="";
xmlString+="<?xml version='1.0' encoding='UTF-8'?><some xml>";
createHTTPRequestObject();
var resp = getResponseText(urlStr+"?"+xmlString,null);
var xmlDoc;
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.loadXML(resp);
alert(xmlDoc.xml);
}
function createHTTPRequestObject(){
req=null ;
var pXmlreq = false ;
if (window.XMLHttpRequest) {
pXmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try{
pXmlreq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
try{
pXmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2) {
}
}
}
req = pXmlreq ;
}
function getResponseText(action,query,method,async,contenttype){
if(method==null){
method="POST";
}
if(async==null){
async="true";
}
if(contenttype==null){
contenttype = "application/x-www-form-urlencoded";
}
req.open(method,action, async);
req.setRequestHeader("Content-Type", contenttype);
if(query){
req.send(query);
}else{
req.send();
}
return req.responseText ;
}
</script>
</head>
<body>
<input type="button" name="Request" value="Request" onclick="sendRequest();"/>
<div id="content" />
</body>
</html>
You are trying to read the responseText before it is ready. Looks like you are treating a asynchronous call as synchronous. That would be the issue.