Execute ajax function when button is clicked - javascript

I am trying to create a webpage that could check if a url is good or bad. The webpage is simple. There should be only a button on the webpage. Whenever the button is clicked it will check the status of the url. As a test case let's say I am checking for google.com. The problem is how do I connect the ajax function parameter with the html parameter?
Here is what I got so far.
<input type="button" id="home" onclick="validate()" value="Start"/>
<br>
<p>Google Status: %s</p>
<script>
$('#home').click(function(){
var string;
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:asynchronous,
dataType:json,
success: function(result) {
string = 'Working';
}
error: functionfunction(result){
string = 'Failed';
}
});
});
</script>

Update text after ajax response
<input type="button" id="home" onclick="validate()" value="Start"/>
<br>
<p id='status'>Google Status: %s</p><!-- >change<-->
<script>
$('#home').click(function(){
var string;
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:asynchronous,
dataType:json,
success: function(result) {
$("#status").html("Google Status: Working"); // change
}
error: functionfunction(result){
$("#status").html("Google Status: Failed");// change
}
}
);
});
</script>

You need to reference the HTML Controls with JQUery,
And you are missing some commas, look at this fiddle:
https://jsfiddle.net/0g9zbzqr/3/
$('#home').click(function(){
$.ajax({
url:$('#url').val(),
type:'get',
async:false,
success: function(result) {
$("#lblResult").html($('#url').val()+': Working');
},
error: function(result){
$("#lblResult").html($('#url').val()+': Failed');
}
});
});

There were many errors in the ajax call itself, but the main changes I have made are to update the html of the statusText paragraph inside the success and error handlers and removed the onClick event from the button since you are adding the event handler in javascript.
<input type="button" id="home" value="Start"/>
<br>
<p id="statusText">Google Status:</p>
<script>
$('#home').click(function(){
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:true,
dataType:'json',
success: function(result) {
$("#statusText").html("Google Status: Working");
},
error: function(result){
$("#statusText").html("Google Status: Failed");
}
});
});
</script>

Related

jQuery Ajax Submit Post not getting success message back

The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});

Check what is the name of the POST

When I click a button, it is handled by ajax and then post to a PHP page. current problem is the PHP cannot recognize the POST name from the front end. It keep throwing me the else part whichis "NOT OK". Below are the snippet.
PHP part
if (isset($_POST['btn-agree'])){ echo "OK<br />"; } else { echo "NOT OK<br />"; }
END PHP part
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
<form id="agree-form" action="/" method="post" role="form">
<input type="submit" name="btn-agree" id="btn-agree" value="Agree">
</form>
You are not specifying the data to be sent to the server. Use the data parameter and serialize the form.
$(function() {
$("#btn-agree").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postAgreement.php",
data: $('#agree-form').serialize(),
success: function(msg){
//do something
},
error: function(){
//do something
}
});
});
});
EDIT: It looks like .serialize() does not include the submit input type. To test the request method to the script, you can use $_SERVER['REQUEST_METHOD'] and test that it equals "POST". You can also set the data parameter to "btn-agree=Agree".
you forgot the parameter "data" on your ajax.
on isset($_POST['btn-agree']) will always be false because the $_POST['btn-agree'] is not define or set.
check this code or see sample on http://api.jquery.com/jquery.ajax/:
$.ajax({
type: "POST",
data: { btn-agree: $('#btn-agree').val() },
url: "postAgreement.php",
success: function(msg){
//do something
},
error: function(){
//do something
}
});

jquery $.ajax is not working. form post

I want use jquery to sent form data to server,
and I follow this page↓
how do i submit a form using get method in jquery.
But is not working, has no any window alert.
I don't know why....
I already import the jquery script in head(version 1.11.3).
<script src="./static/jquery-1.11.3.js" type="text/javascript"></script>
this is my script.
<script>
function test(){
document.getElementById("form_test").submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
});
}
</script>
this is my form code.
<form id="form_test" class="appnitro" method="post" action="">
<div class="form_description">
<p>test.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="info">info</label>
<div>
<input id="info" name="info" class="setInfo" type="text" maxlength="16" value=""/>
<label id="infoMsg" class="Message"></label><br/>
</div>
</li>
<li class="buttons">
<button type="button" class="mbutton" onclick="test()">submit</button>
</li>
</ul>
</form>
Remove the submit handler from test()
document.getElementById("form_test").submit(function () {
This is not required as the function test is being called when user clicks on the button.
function test() {
var $form = $('#form_test');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
}
I would also suggest you to use jQuery on() to bind event
$('#form_test').on('submit', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
You need to have a form submit event handler registered in the dom ready handler
$(function () {
$("#form_test").submit(function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
})
In your code, you are calling the test method on click of the button, which calls the form elements submit function with a callback
As you used inline js in submit button, no need for submit event handle for this. See code below :
<script>
function test(){
var myForm = document.getElementById("form_test");
$.ajax({
url : $(myForm).attr('action'),
type : $(myForm).attr('method'),
data : $(myForm).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
}

ajax returns error when ajax code is inside button click

Ajax code to hit url works fine when the code is placed inside document.ready() function. But when the same code placed inside button click function inside ready fun() ajax url returns error.
Code:
<script>
$(document).ready(initialize);
function initialize() {
$(".storage").click(function(){
$.ajax({
cache: false,
type: "GET",
async: true,
dataType: "JSON",
url: "urllink",
data: { apiKey: "apikey" },
success: function(results) {
alert(" Disk Array URL hit");
}
error: function(xhr) { alert("Error!") } });
});
}
</script>
<input type="submit" value="LOAD" id="storage" class="storage" >
Try this:
function initialize()
{
$(".storage").click(function()
{
$.ajax({
cache : false,
type : "GET",
async : true,
dataType: "JSON",
url : "urllink",
data : {apiKey: "apikey"},
success : function(results)
{
alert(" Disk Array URL hit");
},
error : function(xhr)
{
alert("Error!")
}
});
});
}
$(document).ready(initialize);
<input type="button" value="LOAD" id="storage" class="storage" >
Input Type submit will submit a form which is not the expected action in this script.. "," was missing after success argument..which was giving syntax error..

Ajax JQuery success function not working

I'm not sure what has gone wrong, but for some reason the success function in Ajax isn't calling the function. I'm asking it to call after the PHP is completed.
For the PHP I have $test = 'Hi'; echo json_encode($test);
Here is my code for the main page:
<?php
session_start();
if(!isset($_SESSION["b2_in"])){
header("Location: b2.php");
}
?>
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").val("");
}
</script>
<say>
<form>
<input type="text" name="message" class="Message" id="message"/>
<input type="submit" name="send" value='Say' id="send"/>
<span id="message" style="font-weight:bold;color:red;"></span>
</form>
</say>
Try this
span is a block element of DOM and hence to set data to it, you need to use $(id).html(data); and not val()
Also you should have different id for each elemnt in the dom, it always pick the first id that it gets in the dom, and in your case it is
<input type="text" name="message" class="Message" id="message"/> so it will change the value of this element
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").html("");
}
</script>

Categories

Resources