i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.
Related
I have an index.php page that I want to receive information from a user in a textArea, and, upon hitting save, the variable should be posted to another page called changePage.inc.php. Once the post variable has been set onto the other page, the changePage.inc.php should redirect away from the original index.php to a page called secondPage.php.
variable in jquery on index.php -> same variable as a post on changePage.inc.php
-> user is redirected off of index.php to secondPage.php, as instructed by changePage.inc.php
File named index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message});
window.location.href = "includes/changePage.inc.php";
}
};
changeText();
send();
});
});
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
File name changePage.inc.php
<?php
session_start();
if(isset($_POST['message'])){
header("Location: ../secondPage.php");
}
exit();
File named secondPage.php
<?php
echo 'Hello World';
?>
With the code as it is right now, it gets to changePage.inc.php, but not secondPage.php. I believe that the post variable is either not being set at all, or being set too late (maybe this is because of a race condition).
I have asked this question before and thought that an answer using function(data) within the $.post() method to create an object with $.parseJSON(data) was going to work. But upon running the code, errors were generated, so now I am asking it again. This is the previous attempt: POST variable from jquery redirecting but is not set
Redirect to secondPage.php in the Javascript, not PHP. And do it in the callback function of $.post so it waits for the script to complete.
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message}, function() {
window.location.href = "includes/secondPage.php";
});
}
};
But much simpler would be to just add message as an input in the form, and let the form submit normally.
$("#saveForm").submit(function() {
$("#message").val("You wrote: " + $("#text").val());
}
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<input type="hidden" name="message" id="message">
<button type="submit" id="saveButton">Save!</button>
</form>
Don't leave the page just after triggering an AJAX request, wait for the result using the callback.
$.post("includes/changePage.inc.php", {message: message}, function (data) {
// here you see 'Hello World' in your browser console
console.log(data);
// here you don't see anything in your browser window because it is no POST
window.location.href = "includes/changePage.inc.php";
});
But why to trigger an ajax request and redirect to the same page afterwards...
Maybe this is what's intended (second try):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
// NO: event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
changeText();
// Check for text as message can't be empty here
if (!$('#text').val()){
// preventDefault() here if text is empty
event.preventDefault();
}
});
});
</script>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<!-- put textarea inside your form, and write tags in lowercase -->
<textarea id="text"></textarea>
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
I'm a newbie to Jquery , my question is simple , I'm trying to pass data using Jquery Post method, I have read a lot , but I can't figure it out:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="TestAd" id="TestAd">
<iframe data-aa='58593' src='https://ad.a-ads.com/58593?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true' frameborder='0'></iframe>
</div>
<button>Send request</button>
<br>
<?php
if(!empty($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var height = $('.TestAd').height();
$("button").click(function()
{
if (height==0)
{
$.post("", {block:true});
}
}
</script>
</body>
</html>
The script is a simple AdBlocker checker, thanks for your help
<form method="post">
<input type="hidden" value="true" name="block">
<input type="submit" value="Send request">
</form>
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
if you want to redirect it to the same page why dont you use simple form tag to pass the block value.By default it will redirect it on the same page
Change your PHP to this:
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
And Change your jQuery to this:
<script>
var height = $('.TestAd').height();
$("button").click(function () {
if (height == 0) {
$.post("somepage.php",{block: true}, function (data) {
// data is the response
// do something with it here
alert(data);
});
}
}
</script>
Here are the docs for $.post(), essentially, the way you had it, ignores the response. You have to pass the anonymous function (function (data) {}) callback as the 3rd argument to be able to work with the response.
From the docs:
Examples:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post( "test.php", { name: "John", time: "2pm" } );
The html code:
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript"
src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(msg) {
alert(msg);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
</head>
<body>
<div id="info1">
Put the textbox input value into this block.
</div>
<br />
<form id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit"
id="submit" value="Submit Form" />
</form>
</body>
</html>
The php code:
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo json_encode($result);;
When I entered the text, it cannot display the same text above the input box. Maybe there have some wrong code, but I cannot find it, please help><
Reframed your code. Checkout,
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$("form[id='form1']").on('submit', function(ev){
ev.preventDefault();
var th = $(this);
var data = th.serialize();
var action = th.attr('action');
$.post(action, data).done(function(response){
$("#info1").html(response.msg);
});
});
});
</script>
</head>
<body>
<div id="info1">
<!--Put the textbox input value into this block.-->
</div>
<br />
<form action="ex2_5.php" id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit" id="submit" value="Submit Form" />
</form>
</body>
</html>
ex2_5.php
<?php
$result = array();
if (!empty($_POST['form1']))
$result['msg'] = "<h1>".$_POST['form1']."</h1> is added";
else
$result['msg'] = "<h1>Field is empty!!</h1>";
header('Content-type: application/json');
echo json_encode($result);
Bugs:
1) ;; double semicolon
2) $_POST['form1'] in your PHP file
3) Wrong index using in JS while returning
Debugging:
Open console (Right click -> Inspect element -> Console tab) and checkout for errors
Solution 1:
Specify content type for ajax response as application/json. Otherwise the response will be a string not as json.
// Specify content type header as application/json
header('Content-type: application/json');
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo #json_encode($result);
Solution 2:
If header is not application/json then parse string into object using JSON.parse function.
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(data) {
var data = JSON.parse(data);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>
I am unable to send POST request to my php file using AJAX. I have two files, the first one is index.php and second isVerificationStatusAPIV2.php. Contents of index.php are:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Phone Verification by Dial2Verify API V2 ( www.dial2verify.com )</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var attempt=1;
var transactionToken="";
$(document).ready(function(){
$("#enter_number").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
});
function initiateDial2Verify() {
showCodeForm(1);
GetVerificationImage();
}
function showCodeForm(code) {
$("#dial2verify").fadeIn();
$("#enter_number").fadeOut();
$("#waiting_msg").text("Waiting for missed call from "+$("#phone_number").val());
}
function GetVerificationImage() {
$.post("GetImageAPIV2.php", { phone_number : $("#phone_number").val() },
function(data) { updateImage(data.img,data.transactionToken); }, "json");
}
function updateImage(img, vtransactionToken) {
$("#Image").html("Please give a missed call to <br><img src=\""+img+"\"/>");
transactionToken = vtransactionToken;
PollStart("0");
}
function CheckStatus()
{
$.post("VerificationStatusAPIV2.php", { transactionToken : transactionToken },
function(data) { PollStart(data.status); }, "json");
}
function PollStart(vStatus)
{
attempt =attempt+1;
if ( attempt >= 90 ) { TimeoutCheck(); }
else
if (vStatus === "0") {
$("#status").html("Please give a missed call in <b><i>"+(90-attempt) +"</i></b> seconds.");
setTimeout(CheckStatus, 1000);
}
else if (vStatus === "1")
{
success();
}
else
TimeoutCheck();
}
function Err() {
$("#status").html("Error!<br>Sorry something went wrong, Please cross check your telephone number.");
}
function success() {
$("#status").text("Congrats !!! Phone Number Verified!");
}
function TimeoutCheck() {
$("#status").text("Verification Failed!");
}
</script>
</head>
<body>
<form id="enter_number">
<p>Enter your phone number:</p>
<p><input type="text" name="phone_number" id="phone_number" /></p>
<p><input type="submit" name="submit" value="Verify" /></p>
</form>
<div id="dial2verify" style="display: none;">
<p id="waiting_msg"></p>
<p id="Image">Loading ..</strong></p>
<p id="status">Loading ..</strong></p>
</div>
</body>
</html>
In function CheckStatus() I am sending a post request using AJAX to file VerificationStatusAPIV2.php but it isn't making any post request. can someone tell what's wrong in that?
Update I just saw that "status" in "data.status" in func CheckStatus() is in yellow color while others in blue color. maybe thats the problem?
In your code snipped the only place you have CheckStatus exept for the function itselft is this line ... setTimeout(CheckStatus, 1000); so if this is the function call it'S should be like this : setTimeout(CheckStatus(), 1000);
This may be your problem.
Try changing
<input type="submit" name="submit" value="Verify" />
to
<input type="submit" id="btn_enter" name="submit" value="Verify" />
and in the js:
$("#btn_enter").submit(function(e) {
e.preventDefault();
initiateDial2Verify();
});
you were pointing your submit function to the HTML form's ID
var request=$.ajax({
method:"POST",
url:"VerificationStatusAPIV2.php",
data:{ transactionToken : transactionToken },
dataType:"json"
});
request.success(function(data){
PollStart(data.status);
});