I use ajax on my html page to load data from MySql db w.o. reload and send email notification on some event, after selecting on html page - ajax calls script.php that made request to db and return result, it works perfect; and in same time I use function that shows and hides ajax loader image until query is executed, but it calls my php script twice so that each time it sends email twice
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
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","../getuser.php?q="+str,true);
xmlhttp.send();
}
// ajax loader image
function getuser(str){
$.ajax({
url: "http://site.com/getuser.php?q="+str,
beforeSend: function (XMLHttpRequest)
{
$("#loading").show();
}
})
.done(function ( data ) {
$("#txtHint").html(data);
$("#loading").hide();
});
}
$(document).ready(function(){
$("select[name='users']").change(function () {
getuser($("option:selected", this).val());
});
});
</script>
how to improve this code to call php script just one time?
HTML
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a user:</option>
<option value="1">User1</option>
<option value="2">User2</option>
</select>
</form>
<div style="display:none" id="loading">
<p><img src="../loader.gif" /></p>
</div>
<br>
<div id="txtHint"><b>User info will be listed here.</b></div>
remove onchange event from:
<select name="users" onchange="showUser(this.value)">
What are you using showUser for? This seems to be enough;
function getuser(str) {
$.ajax({
url: "/getuser.php?q=" + str, // No need to include the domain here
beforeSend: function (jqXHR) {
$("#loading").show();
}
}).done(function(data) {
$("#txtHint").html(data);
$("#loading").hide();
});
}
$(document).ready(function() {
$("select[name='users']").change(function() {
getuser($(this).val());
});
});
Related
I need to add some data to a page using AJAX. I have written the following code for the purpose. The problem is that the call is not returning any data.
The PHP file is just for test purposes as of now. Obviously, some actually functionality will be added to it.
Javascript:
<script type="text/javascript">
function addprod(prodid) {
var xmlHttp;
if (prodid="") {
document.getelementbyID("newprod").innerhtml="";
return;
}
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else{
xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readystate==4 && xmlHttp.status==200){
document.getelementbyID("newprod").innerhtml=xmlHttp.responseText;
}
}
xmlHttp.open("GET","add_row.php?q="+prodid,true);
xmlHttp.send();
}
</script>
HTML:
<span id="newprod"></span>
<form>
<input type="text" name="addprodbyid" class="form-control" placeholder="Enter Product ID" onkeyup="addprod(this.value)" />
</form>
add_row.php:
<?php
$prod_id=$_REQUEST['q'];
echo $prod_id;
?>
I tried checking with Firebug. The AJAX call is working, but no data is being sent to the PHP file. The URL that gets called everytime is add_row.php?q=.
mistakenly assign inside if condition
if (prodid = "") {
document.getelementbyID("newprod").innerhtml="";
return;
}
correct is
if (prodid == "") {
document.getelementbyID("newprod").innerhtml="";
return;
}
Why not with jquery simple
function addprod(prodid) {
$.ajax({
url: "add_row.php",
type: "post",
data: {'q':prodid},
success: function(data){
$("#newprod").html(data);
},
error:function(){
$("#newprod").html('There is error while submit');
}
});
}
add_row.php:
$prod_id=$_POST['q'];
echo $prod_id;
If
xmlHttp.readystate
is not a type, then correct it as (s => S)
xmlHttp.readyState
If you still curious about why your variant may not work: first of all, move your onreadystatechange function below xmlhttp.send(). Also try to change onreadystatechange a little
xmlHttp.open("GET","add_row.php?q="+prodid,true);
xmlHttp.send();
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState != 4) return
if (xmlHttp.status == 200) {
document.getelementbyID("newprod").innerhtml=xmlHttp.responseText;
}
}
It's seems no change from your variant, but that is the one that helped me one day.
I've a multiple select on my code with the onchange function ajax call,when the value is passed through the ajax it gets data from database and plot the chart by highcharts script,my problem is javascript is not worrking on ajax call,please suggest anything best,thanks in advance
source.php
<script>
function something(str)
{
if (str=="")
{
document.getElementById("div1").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("div1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","destination.php?q="+str,true);
xmlhttp.send();
} </script>
<body>
<select multiple="multiple" onchange="something(this.value);">
<option>value1</option>
......
<option>valuen</option></select>
<div id="div1"></div>
destination.php
on here (destination page) get data from the database using the requested value from ajax
<?php
include("config.php");
$var=$_REQUEST['str'];
$query=mysql_query("select * from table where column=$var");
while($row=mysql_fetch_array($query))
{
$value[]=$row['data'];
}
<script>
<!--- here my highcharts script for ploting graph by the above fetching value from database --!>
</script>
?>
I'm having a problem validating a field in a form with a Submit button when the form is sitting on a php file that uses AJAX to pull in up on the current main page.
Here's a fiddle of the validation code and the simple form not using AJAX:
http://jsfiddle.net/mwrfW/
That simple example works fine.
Now if I leave the JS in index.php but put the form on ajax_form.php I get a problem:
On index.php:
<script>
$(document).ready(function () {
$("#contactform").validate({
rules: {
name: {
required: true,
minlength: 3
},
},
submitHandler: function () {
alert('valid form submission');
return false;
}
});
});
</script>
On ajax_form.php (where I echo out the html):
echo '<form id="contactform">
A:<input id="name" type="text" name="name" />
<br/>
<input id="btn" type="submit" />
</form>';
So with that two file setup, validation isn't triggering.
Interestingly, if I bring the Submit button over to index.php and ditch the submitHandler it works as long as I add a little extra code to make the submit button work outside of the form: for example: on index.php:
$(document).ready(function() {
$("#contactform").validate({
name: {
required: true,
minlength: 3
},
})
$('#btn').click(function() {
$("#contactform").valid();
});
});
<input id="btn" type="submit" />
On ajax_form.php (where I echo out just the field's html):
echo '<form id="contactform">
<input id="name" type="text" name="name" />
</form>';
So here's the overall question:
What is the proper way to have the validation js on the index page, while the form/field/submitbutton all reside on the ajax_form.php?
I'm not sure if I'm using the submitHandler correctly or not with this setup.
Just in case it's needed, here's the AJAX code that's calling ajax_form.php (fyi, the form always pulls up fine with this, so I don't think there's a problem with this part of the code):
//Edit Case
function editCase(str) {
if (str=="") {
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","ajax_form.php?q="+str,true);
xmlhttp.send();
$(document).ready(function(){
$('.overlay').show();
$('.button').show();
});
}
The form element must be loaded in the DOM before the jQuery validate function can be attached to it. So I expect I'd either move the form to the index.php file and hide it until needed, or move the jQuery validation code to the editCase function, or put the jQ validation code in a function and attach that function to the form in the editCase function.
Here's an example of the last option:
function contactform_validation() {
$("#contactform").validate({
rules: {
name: {
required: true,
minlength: 3
},
},
submitHandler: function () {
alert('valid form submission');
form.submit();
},
invalidHandler: function () {
alert('INvalid form submission');
return false;
}
});
}
function editCase(str) {
if (str=="") {
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;
contactform_validation(); // <--- THIS IS NEW
}
}
xmlhttp.open("GET","ajax_form.php?q="+str,true);
xmlhttp.send();
$(document).ready(function(){
$('.overlay').show();
$('.button').show();
});
}
You are using JQuery, so you can use load() function like this:
$('#txtHint').load("ajax_form.php?q="+str , null, function (){
//and here in your callback function, you can attach all behaviors to your form, for example:
$("#contactform").validate({
name: {
required: true,
minlength: 3
},
})
$('#btn').click(function() {
$("#contactform").valid();
});
});
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.
im having a problem after i select one option
<select name="opcoes" onchange="showInfo(this.value)">
<option value="1">one</option>
<option value="2">two</option>
</select>
I send a option value through this
function showInfo(str)
{
if (str=="")
{
document.getElementById("fields").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("fields").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/php/search/getRow.php?id="+str,true);
xmlhttp.send();
}
That gives my getRow.php the ID to show from the Database a table with inputs so a person can change their values, now i have two fields that need jQuery-UI autocomplete so i have this javascript but its not working.
This is the generated code from the getRow.php
<input type="text" name="editname" id="namesearch" value="one">
<input type="text" name="editname" id="modelsearch" value="wfmq015">
This is my autocomplete...
$(function() {
//autocomplete
$("#namesearch").autocomplete({
source: "/js/namer.php",
minLength: 0
});
$("#modelsearch").autocomplete({
source: "/js/modeler.php",
minLength: 1
});
});
I think my problem is that the javascript is notcatching the id's in time since it was an ajax request... can anyone help me out?
The Javascript's are placed in the main page that calls the ajax to get some more elements into it...
Yikes. Looks like you wrote your own AJAX call. Let's use jQuery for this instead. Save yourself some major headache
function showInfo(str) {
$.get("/php/search/getRow.php?id=" + str, function(html) {
$("#fields").html(html);
});
}
Now, to your second question, the problem is you're using the AJAX to load your fields but are instantiating the autocomplete when the page is loaded. So I would put those into a function and add that to your AJAX callback
function loadAuto() {
$("#namesearch").autocomplete({
source: "/js/namer.php",
minLength: 0
});
$("#modelsearch").autocomplete({
source: "/js/modeler.php",
minLength: 1
});
}
function showInfo(str) {
$.get("/php/search/getRow.php?id=" + str, function(html) {
$("#fields").html(html);
loadAuto();
});
}