I am trying to send AJAX but it is not working. Could someone please clarify what it is I am doing wrong or not doing. Just trying to figure this out.
FIRST PAGE.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="text-center">Button</div>
<input class="form-control" name="cartID" id="cartID" type="hidden" value="<?php echo $order['clientid'] ;?>">
<p id="edit_box"></p>
<script>
$("#scaleButton").click(function() {
var cartID = "hello"
var second = "second";
///////// AJAX //////// AJAX //////////
$.ajax({
type: 'POST',
url: 'testing1234.php',
data: {first:cartID,second:second},
success: function( response ){
alert('yay ajax is done.');
$('#edit_box').html(response);//this is where you populate your response
}//close succss params
});//close ajax
///////// AJAX //////// AJAX //////////
}
</script>
</body>
</html>
SECOND PAGE
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
echo $second;
?>
</body>
</html>
In your case, it's just a syntax issue. You forgot to close the click event with an ending parenthesis. This kind of problem can be easily avoided by using a text editor with linting. There are many out there, like Sublime Text, Atom, etc. Or as suggest in comment, open up developer console in your browser to check for any errors/warning.
Related
I need to get photos using GIPHY API, I have the following function:
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="submit" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>
So, the problem is that $.get() function doesn't respond at all, even always() callback function does not get executed.
When I try this particular URL in the Postman application, I get the response (json object) and I can access the data.images.origianl.url property it is there.
When I try the following line of code in the console :$.get("https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1"); I get the response with the status code 200, so it should work in the main.js file, but in my case it doesn't.
I have two variables url1 and url2 this is because, in my first tries I did not get anything with the url1, but getting the success with the url2. After some time I didn't get anything using two of them.
What is the problem? How can it be that I can get responses from Postman and from the console using the same URLs, but do not get them with actual code?
Thank you for your patience!
This is a common problem, understanding the difference between type button and type submit.
Submit will submit the form. Whereas button will just process the event handlers assigned.
Change
<input type="submit"
to
<input type="button"
function callApi(input) {
var url1 = `https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=${input.value.toLowerCase()}&limit=1`;
var url2 = "https://api.giphy.com/v1/gifs/random?api_key=0zCoIz5c8dbanGyiAHnA0pSUe3bcA9sf&tag=dog&limit=1";
var xhr = $.get(url2);
xhr.done(function(jsonObj) {
alert("Success!");
document.getElementById("genImage").src = jsonObj.data.images.original.url;
}).fail(function() {
alert("erro");
}).always(function() {
alert("...");
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form id="query-form">
<label for="query">KEYWORD</label>
<input name="query" type="text">
<input type="button" id="button" value="GENERATE" onclick="callApi(query)">
</form>
<img id="genImage" src="">
</body>
</html>
This question already has answers here:
Update div with jQuery ajax response html
(3 answers)
Closed 3 years ago.
How can I echo the response of a php script on my current page when I click on a button? I know how I can run a php script without leaving the page. The problem is that the response (echo) is not shown on the page where the user is. My current solution is to call the current site from a form and handle the response like that but is it possible to do that without refreshing the page?
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<form class="form" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button" value="send">
</form>
</body>
</html>
Normally I would use Javascript for tasks like that but in this case I have to use php. I also tried to make a JS post request against a php file but this solution felt not "clean".
You can use Ajax form submit script using PHP like.
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div class="alert-msg"></div>
<form class="form" id="myForm" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button submit-btn" value="send">
</form>
// you can use add this script in body tag
<script type="text/javascript">
// ------- Mail Send ajax
$(document).ready(function() {
var form = $('#myForm'); // contact form
var submit = $('.submit-btn'); // submit button
var alert = $('.alert-msg'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'index.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.attr("style", "display: none !important");; // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
</script>
</body>
</html>
The only way to get a response from PHP (or anything else that executes on the server) is to make an HTTP request to it.
If you don't want to leave the current page then your options are:
Set target="_blank" in the form to open the response in a new tab or window
Add an iframe to the document and set target="name_of_iframe" to open the response in the iframe
Make the HTTP request with JavaScript and display the response using DOM manipulation. This technique is known as Ajax and the Internet is awash with tutorials on it.
You can use the Ajax for this.
Add jquery library in your code and than write below ajax code:
$('body').on('click', '.button',function(){
$.ajax({
type: 'POST',
url: 'post.php',
})
.done(function (response) {
$('.message').html(response);
});
return false;
});
In post.php file write below code:
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
Using Jquery and its ajax function and without form :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" class="textfield" name="message" id="message">
<button id="btn_callajax">Envoyer</button>
<p id="getajaxresponse"></p>
<script>
$document).ready(function(){
$("#btn_callajax").click(function(){
var my_msg = $("#message").val();
$.ajax({
url : 'getajaxcall_respback.php',
type : 'POST',
data : 'my_msg='+my_msg,
dataType : 'html',
success : function(htmlresponse, statut){
$("#getajaxresponse").html(htmlresponse);
},
error : function(responses, statut, error){
}
});
});
});</script>
In the getajaxcall_respback.php file :
if( isset($_POST['my_msg'])
{
$mesg = $_POST['my_msg'];
//get your database request ?
echo "send your html code back to your index.php";
}
I'm new to JS and i want to receive the value from a variable in JS, send it by post (or ajax) to a PHP file, and see the text display. The thing is i've been trying different ways to do it but i always get a undefined index in php.
My code is below
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checked=$("#switch").attr("checked");
if(checked)
{
$("switch").removeAttr("checked");
console.log("estado apagado switch 1");
var estados="1";
$.post("accion.php", {estado: "david"});
}else
{
$("#switch").attr("checked","checked");
console.log("estado encendido switch 1");
var estados="2";
$.post("accion.php", {estado: "david 2"});
}
});
</script>
</body>
</html>
accion.php
<?php
$est = $_POST['estado'];
echo $est;
if ($est=="david") {
echo "no mameees";
}else{
echo "no mameees no se puso ";
}
?>
Someone has any idea ?
$("#switch").change(function () {
var checked=$("#switch").prop("checked");
if(checked)
{
console.log(checked);
}else{
console.log(checked);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Switch <input type="checkbox" name="switch" id="switch" >
Use prop instead of attr to find checkbox is checked or not.
You can let php check if the checkbox was checked or not in a success callback from $.post:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PRUEBA AJAX JS PHP HTML</title>
</head>
<body>
<H1>prueba</H1>
<input type="checkbox" name="switch" id="switch" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#switch").change(function ()
{
var checkbox = $("#switch");
$.post("accion.php", {estado: checkbox.val()}, function(data){
$("h1").html(data);
});
});
</script>
</body>
</html>
accion.php
<?php
$checkbox = isset($_POST['estado']) && $_POST['estado'] == 'on'; // 'on' is the default checkbox value when you don't specify it in html
if ($checkbox) {
echo "it's been checked";
}else{
echo "it wasn't checked";
}
?>
PS: when working with ajax ( check out $.post options) i recommend using dataType: 'json' and your php should respond with a valid JSON, you have json_encode for that.
use
var checked = $('#switch').is(':checked');
instead of
var checked=$("#switch").attr("checked");
i need a little info on google recaptcha. I want to grab the value of "g-recaptcha-response" that compares in the captcha.php file i inserted below in my jquery file and then send it to the captcha.php file using jquery $.post() method. I apologize if this is duplicate but i really cannot find someone with my same problem ;)
THE HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="handle_spam.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div class="g-recaptcha" data-sitekey="6Lf8LxIUAAAAALg93pw24l53KTeqrIwl7kUY-opk"></div>
<button id="go">Register</button>
</body>
</html>
THE PHP
<?php
$captcha=$_POST['g-recaptcha-response'];
echo $captcha;
if(!$captcha){
echo 'You must verify yourself';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Lf8LxIUAAAAACB9iqeOermR-rPOW0zcWRfoetBO&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'abort_all';
}else
{
echo 'success';
}
?>
THE JS
$(document).ready(function(){
$('#go').click(function(){
send=$('')
$.post('captcha.php',function(data){
alert(data);
});
});
});
Use this
<div class="g-recaptcha" data-callback="captchaCallback" data-sitekey="...">
and provide the function:
function captchaCallback(response) {
alert(response);
}
I am using getJSON to send a request to server and fetch response. When I send an string of text like 'firstname=x' to the server, it works fine, but when I use '$('#input').val()' as input data to the server, it returns nothing as response.
Here is the jquery code
<!DOCTYPE html>
<html>
<head>
<title>Request in getJSON</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(){
var req=$('#query').val();
var data='firstname=req';
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready
</script>
</head>
<body>
<h1> Enter Name </h1>
<input type='text' id='query' />
<input type="button" id="button" value="submit" />
<div id="results"></div>
</body>
</html>
Hope you can help me
Thank you
Try with this one:
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
var data={firstname : $('#query').val()}; //<--------try like this
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready