I have a simple script, in ajax, and I want to capture the return and process it according to the value:
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == "not available") {
document.write("not available");
}
}
At the same time, I tried this, which worked:
if (xmlhttp.readyState==4) {
document.write(xmlhttp.responseText);
}
What wrong am I doing?
Thank you for your reply. This is my current domain availability checking script which works great:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#dtype').change(function() {
var opt = $('#domain').val();
$.ajax({
type: "POST",
url: "testwhois.php",
data: 'd=' + opt,
success:function(data){
$('#txtHint'). html(data);
}
});
});
});
</script>
</head>
<body>
<form> Domain name : <input type="text" name="domain" id="domain"> <input type="radio" name="dtype" id="dtype" value="new">New <input type="radio" name="dtype" value="transfer">Transfer <span id="txtHint"></span> </form>
</body>
</html>
However, I want to have two things in it:
a preloader image (I have it) while the script is working in the place of 'txtHint' where the answer will be displayed.
The answer is returned in the format of "not available" or available". I want to make the 'domain' field blank, when the answer is returned as "not available" with the html codes.
Thanks again.
Forgive me if you know this already, but in case you don't:
Ajax posts data to an external php file, which processes the data it receives, and sends back an answer. It looks like this:
FILE #1:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Sel').change(function() {
var opt = $(this).val();
var someelse = 'Hello';
var more_stuff = 'Goodbye';
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});
});
});
</script>
</head>
<body>
<select id = "Sel">
<option value ="Song1">default value</option>
<option value ="Song2">Break on through</option>
<option value ="Song3">Time</option>
<option value ="Song4">Money</option>
<option value="Song5">Saucerful of Secrets</option>
</select>
FILE #2: receiving_file.php
<?php
$recd = $_POST['selected_opt'];
echo 'You chose: ' . $recd;
The above example works. If you copy/paste it into two files, you will see AJAX in action. Of course, the server side scripting is in PHP, so your server needs to handle that. If necessary, download XAMPP and install it on your local computer. Place these two files in the htdocs folder and, in the browser address bar, type:
http://localhost/whatever_you_called_the_first_page.php
As you can see, it is much simpler to write AJAX code using jQuery. All that is needed is the jQuery library (usually in the header tags, as in code example above), and the AJAX code block.
Here are some other examples to study:
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Related
can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you
in my website, I have a singn_up-form and use the Google-Api to give the user some suggestions. The API requests the location of the user once in Internet-Explorer. But if I try Firefox, the requests are looped until I click "Standort immer Freigeben" - it means "always accept".
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{ types: ['geocode'] });
}
The code is loaded at document.ready and contains more code, but this snippet also reproduces the error.
Does anyone has some ideas?
Try this :
put the apis in your <head></head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
put this in your body tag:
<label for="autocomplete">Please Insert an address:</label>
<br>
<input id="autocomplete" type="text" size="100">
put this in your onload function:
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
this is my code :
var input = document.getElementById('autocomplete');
new google.maps.places.Autocomplete(input);
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="autocomplete">Please Insert an address:</label><br>
<input id="autocomplete" type="text" size="100">
</body>
</html>
You might have kept some onfocus attribute as given in Google Maps API Example
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
OR
If you don't require keeping bounds for places suggestions, you may want to remove it
OR
If you need to set bounds for suggestions keep some condition to not call location consent every time, if user gives permission.
Please keep your condition in geolocate() function
Issue is happening only in Mozilla FireFox
What you want to do is this:
function handlePermission() {
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
geoBtn.style.display = 'inline';
}
});
}
then put handlePermission(); after your callback function receives permission
I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server
I am having trouble working the finishing touches out with this. I am still fairly new to ajax and json, but here's what i have so far. I am trying to take an array(s) from a php file and load them into a select dropdown (#input) via ajax/json. I think i'm pretty close, but i'm not sure where i'm messing up. Please help
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
if ($("#numbers").val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = <?php echo json_encode($array); ?>;
for (i=0;i<numbers.length;i++){
$('#input').append("<select>" + numbers[i] +
"</select>");
}
},
});
}
});
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
</div>
<div id="content">
<div class="main">
<div id="formwrapper">
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="input"></select>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my PHP (login.php)
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
In your script, you aren't doing anything with the data that is returned from the AJAX call. I suspect that is because you don't understand how AJAX works. I'll try to explain it without going into super deep detail.
When you make an AJAX call to a URL, you are making an HTTP request, just like when you type http://www.google.com into your web browser. In response, the server at the other end of that URL sends you an HTTP response with some data.
In the case of your AJAX, you are requesting the response of login.php, which, I will assume, is the PHP you added to your question above. In the success function, you get a result. That result is everything that was output by login.php.
So,
$(document).ready(function() {
$("#numbers").change(function(e) {
if ($(this).val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = result; //result is equal to your array from the php. You don't put PHP here.
$('#input option').remove(); //Remove any existing options.
for (i=0;i<numbers.length;i++){
$('#input').append("<option>" + numbers[i] + "</option>");
}
}
});
}
});
});
If login.php is NOT the PHP you added above, then I'm not going to be able to help you until you tell me what file that is from.
Also, notice that we wrapped the AJAX call into a change event on the #numbers select box. That way, when the select box's value changes, it will call this AJAX, and select the numbers.
Thanks for the assist tymeJV.
can one help on how can i submit the form to search page script on index page and return the results of search script on specific DIV id search_results we out going to the search.php or refresh the index page using AJAX onClick
Am not good in Ajax but i try my best to come out with the following code which does what am looking for but is loading the page we out clicking anything i need a user to trigger the event when he/she enters what they are looking for? Any answer or suggestion is greatly appreciate
<script language="javascript" src="js/jquery-8.js"></script>
<script language="javascript">
var grbData = $.ajax({
type : "GET",
url : "search_m.php",
data : "q=",
success: function (html) {
$("#more-info").html(html);
}
});
</script>
<div id="more-info"></div>
I wish the above code to use this following htm form
<form method="get" style="width:230px; margin:0 auto;" id="find">
<input type="image" src="images/searchthis.png" id="search_btn">
<input type="text" id="search_toggle" name="q" placeHolder="type to start searching">
</form>
Add a click event to the search_btn element.
$('#search_btn').click(function(e) {
e.preventDefault();
$.ajax({
type : "GET",
url : "search_m.php",
data : $('#search_toggle').val(),
success: function (html) {
$("#more-info").html(html);
}
});
HTH.