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>
Related
I am integrating my site ajax to load content without reloading the page. Everything works fine but are of this style url http: // mysite / #.
I wish that were generated url to reload the page to remain in the same place, I could use also have a new URL for the likes of facebook. Any idea what could be wrong? I leave the code:
function nuevoAjax() {
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 Cargar(url) {
var center = document.getElementById('center');
ajax = nuevoAjax();
ajax.open("GET", url, true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
center.innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
And the button:
<img src="<?php $_SERVER['DOCUMENT_ROOT']?>/image/road.jpg" width="60" height="34"/>
This is the div that loads dynamic content
<div class="center"></div>
New EDIT:
<sript src:"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$("#loadContent").on("click",function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
type: 'GET',
data: {"anydata":"anydatavalue"},
success : function(reponse){
$("#center").html(reponse);
}
});
});
</script>
The button:
<li>BIO</li>
This is a code to do the task that you want in jquery ajax
include jquery file in the head of your page like this
<sript src:"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script
assign a id to your anchor tag
<img src="<?php $_SERVER['DOCUMENT_ROOT']?>/image/road.jpg" id="loadContent" width="60" height="34"/>
Jquery Ajax bind with click event
<script>
$("#loadContent").on("click",function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
type: 'GET',
data: {"anydata":"anydatavalue"},
success : function(reponse){
$("#center").html(reponse);
}
});
});
</script>
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>
So I would like to submit the form using Javascript, and with the form I would like to send also one Javascript array.
So far I have this which is not working (I don't get the modified URL and I get the one specified in the action property of the form):
<script>
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
document.getElementById("submit_form").submit(function(event) {
event.preventDefault();
var url = 'submit.php?id_delete='+unique_id_to_delete.toString();
window.location.href = url;
});
} else {
alert('Ok, next time!');
}
}
</script>
Form:
<form id="submit_form" method="post" action="submit.php" enctype="multipart/form-data">
<input type="button" onclick="submit_form();" value="Submit"/>
</form>
Form submit using javascript
function submit_form()
{
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)
{
//response after success
//xmlhttp.responseText
}
}
xmlhttp.open("GET","YOUR URL WITH PARAMS",true);
xmlhttp.send();
}
Heh.. ok I tried this which I think is not what you thought..
<script>
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
var data1 = JSON.stringify(unique_id_to_delete);
$.ajax({ type: "POST", data: {value1:data1}, url: "submit.php", success: function() {
} });
} else {
alert('Ok, next time!');
}
}
</script>
script:
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
var url = 'submit.php?id_delete='+unique_id_to_delete.toString();
alert(url);
window.location.href = url;
} else {
alert('Ok, next time!');
}
}
Form:
<form id="submit_form" method="post" enctype="multipart/form-data">
<input type="button" onclick="submit_form();" value="Submit"/>
</form>
Your form will never but submitted as your are simply redirecting the window location, thus creating a GET rather then a POST as intended.
You could do:
function submit_form() {
var unique_id_to_delete = [1,2,3,4,5,6];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
$.ajax({
url: "submit.php",
type: "POST",
data: unique_id_to_delete,
});
} else {
alert('Ok, next time!');
}
}
And not need a form:
<input type="button" onclick="submit_form();" value="Submit"/>
I haven't used PHP in a while, but at the other end you need to use json_decode
I have following form and javascript which is not activated on submit. I can not understand where is the problem so that the javascript is not fired by pressing the button. The script is included in the html of course and the path is correct.
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
var size = document.getElementById("selectedProductSize");
req = initRequest();
req.open("POST", url, true);
//req.onreadystatechange = callback;
req.send("selectedProductRef="+productReference.value+"&selectedProductSize="+size.value);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
Here's a nice blog post on why to move away from using inline javascript.
You might want to consider using jQuery as a way to facilitate going to a more event-driven scripting approach. It also makes async requests pretty straight-forward with its $.ajax() method.
Here's your addProductToCart() in jQuery format:
$('body').on('click', '#addToCart', ({
var url = "/addToCart";
$.ajax({
type: "POST",
url: url,
data: '{selectedProductRef: "'+ $('#selectedProductRef').val() + '", selectedProductSize:"' + $('#selectedProductSize').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
productReferenceValue =productReference ;
var size = document.getElementById("selectedProductSize");
sizeValue=size .value;
rm = initRequest();
rm.open("POST", url, true);
//req.onreadystatechange = callback;
rm.send("selectedProductRef="+productReferenceValue +"&selectedProductSize="+size.sizeValue);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
<!-- language: lang-html -->
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
<!-- end snippet -->
A little change in your code instead of req = initRequest(); just call initRequest()
var size = document.getElementById("selectedProductSize");
initRequest();
req.open("POST", url, true);
initRequest() does not return any value.
We are using http://jscolor.com (JavaScript Color picker) without any problem normally. But when we create the input element by AJAX, it don't work correctly and jscolor.js can not detect class (color) of the input, while the input show correctly. What we should do?
The HTML code is:
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Our PHP response to ajax is:echo "<input class=\"color\" type=\"text\" value=\"66ff00\">";
I think, when you create new DOM element after documentload, you should bind the event's after where you create that's element.
UPDATED PART OF ANSWER
See this html and script:
<div id="container"></div>
$(document).ready(function () {
// if you add the event for element that currenlty not exist on
// page, and later may be created, the even cannot fired
$('#elem').click(function () {
alert('You are clicked on input!');
});
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem');
});
}
});
});
But the correct way is to add event after where DOM element is created, as you see below:
$(document).ready(function () {
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem')
.click(function () { // you should bind your events here
alert('You are clicked on input!');
});
});
}
});
});
UPDATED PART 2
you should initialize the new jscolor instance, for example use this code
new jscolor.color($('.color'), {});
after you created your own element.
UPDATED PART 3
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").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("txtHint").innerHTML = xmlhttp.responseText;
/* YOU SHOULD INITIALIZE THE NEW JSCOLOR INSTANCE HERE */
var myPicker = new jscolor.color(document.getElementById('myField1'), {})
myPicker.fromString('99FF33') //
/**/
}
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Please mark it as answer if it helped you.