Passing data using Jquery Post method to the same page - php

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" } );

Related

Ajax Not Executed

I am beginner to ajax world and trying to call contents from php page using $.ajax() function and the code couldn't executed. the html page i used:
<!DOCTYPE html>
<html>
<head>
<title>AJAX</title>
</head>
<body>
<div >
<input type="text" name="search" id="search">
<br>
<br>
<h2 id="result"></h2>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>
the JQuery code i used in the script.js:
$(document).ready(function() {
$('#search').keyup(function () {
var search = $('#search').val();
$.ajax({
url:'search.php',
//the page to which the request will go to
data:{search: search},
type: 'POST',
success:function(data) {
if(!data.error){
$('#result').html(data);//the h2 we want to echo it uing the ajax
}
}
});
});
});
the search.php page contain:
$search = $_POST['search'];
echo $search;
the code not executed. What should I do.
I see some issue in your response from PHP code and in ajax side success code.
You are not sending in response JSON format so data.error is meaningless.
so in your success callback code should be like this.
success:function(data) {
$('#result').html(data);//the h2 we want to echo it uing the ajax
}
Follow jQuery Ajax Document :
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0
type: 'POST'
But you are using 2.0 so i think this will work :
method: 'POST'
jQuery Documents

why i cannot pass json data to another PHP file?

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.

Ajax text to PHP duplicates text and button when passing value

I am working on a bit of ajax that gets the value from a text input and passes it into a php variable. I have got the following code doing what I want, however it duplicates the text input and the button when it passes the value into php and I can't work out why, any ideas:
<html><head><title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function callAjaxAddition() {
arguments0 = $("input[name='arg1']").val();
$.ajax({
type: "POST",
url: "refresh.php",
data: {arguments: arguments0},
success: function(data) {
$("#answer").html(data);
}
});
return false;
}
</script>
</head>
<body><div id="exampleForm">
<input name="arg1" /><div id="answer"></div>
<br />
<button onClick="callAjaxAddition()">Click Me to Add</button>
</div>
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
var_dump($a);
}
?>
</body></html>
You are sending request to a php file that has html code in it. So it renders current html, it has text box in it. And you are putting it in answer div. That's why it is duplicating. If you make a request to refresh.php, it response whole page not only echo $a; part. Create aseparate page like service.php and
service.php:
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
}
?>
Use service.php in your ajax call

HTML to jQuery to PHP, then from PHP to jQuery to HTML

Ok, I have this code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function get() {
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
}
</script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" href="javascript: get()">haller</a>
<div id="age">See your name</div>
</body>
</html>
Here's what I want: get the id of an anchor tag from the anchor tag that has been clicked by the user via jQuery and then past that to a PHP file. The PHP file will then echo the id name of the anchor tag that was clicked by the user back to the jQuery which will then display the output into the specified element.
Here's the PHP file:
<?
$name=$_POST['name'];
if ($name==NULL)
{
echo "No text";
}
else
{
echo $name;
}
?>
Bind your event like this, since you are using jQuery
$('a').click(function(){
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#age').html(output).show();
});
});
And remove the javascript from the href
<a id="grabe" href="#">haller</a>
<a id="kane" href="#">haller 2</a>
$('#grabe').click(function() {
$('#age').load('yourphp.php', {'name':$(this).prop('id')});
});
You can use $(this) to access almost anything about "what brought you here" in the code. You'll also need a listener for the event. In this way too brief example below, I have it listening for any clicks to <span class="edit_area"> spans.
<script>
$(document).ready(function(){
$('span.edit_area').click( function(){
var fieldname = $(this).attr('id');
...
});
});
I dont know why you want to send an id to a server and then receive that id back again from the ajax call as it is already there in your client script. Anyway this is the code.
This code will does this functionalirty for all a tag with a class called"crazyLink" and show the data received from the server page in a div with id anotherCrazyDiv
HTML
<a class="crazyLink" href="#">I am crazy</a>
<a class="crazyLink" href="#">I am crazy2</a>
<div id="anotherCrazyDiv"></div>
Script
$(function(){
$(".crazyLink").click(function(){
var id=$(this).attr("id");
$.post("data.php", { name : id } ,function(data){
$("#anotherCrazyDiv").html(data);
});
return false; // to prevent normal navigation if there is a valid href value
});
});
Keep in mind that, in your scenario, the value in id variable and value in data variable (after getting response from ajax call ) are same.
you may want to separate your javascript from your html. it makes things easier. it should probably look something like this.
HTML
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"> </script>
<script type="text/javascript" src="javascript/somescript.js"></script>
</head>
<body>
<input type="text" id="name"/>
<a id="grabe" class="someclass">haller</a>
<div id="age">See your name</div>
</body>
</html>
javascript
$(document).ready(function() {
$('.someclass').click(function() {
$('#age').load(
url: 'tt.php',
data: { name: $(this).attr('id')}
);
});
});

submit form using Jquery Ajax Form Plugin and php?

this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>

Categories