POST data to redirect page fail - php

I was totally confused by the following situation...
situation
post data from a.php to b.php and redirect to b.php...but fail
CODE
- a.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
url: 'b.php',
dataType: 'html',
type: 'POST',
data: {
value: $('#value').val()
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
console.log(response);
window.location.href = "b.php";
}
});
});
});
</script>
</head>
<body>
value: <input type="text" id="value">
</body>
</html>
CODE
- b.php
<?php
echo $_REQUEST['value'];
?>
a.php can get the right response from b.php without redirect function. However, once I include the statement window.location.href = "b.php";, a.php will redirect to b.php but without printing anything.
Why is this situation happening?
Is there any solution to fix this?
Thanks!

you can't pass data between to pages in this way. Posting data to b.php and redirecting to it - are two different requests.
if you want to pass data via redirecting - use GET params:
window.location.href = "b.php?value="+$('#value').val();
Also form submission directly to b.php can help you.
<form action="b.php" method="post">
<input name="value" />
<input type="submit" />
</form>

You just need a <form> so that whenever you click on submit button your all form data will be transferred to b.php (YOU WILL AUTOMATICALLY BE REDIRECTED TO b.php page) and you can there access $_POST['value']. That's very simple. No need to do $.ajax call.
<form id="myFrm" name="myFrm" method="post" action="b.php">
value: <input type="text" id="value" name="value">
<input type="submit" id="submit" name="submit" value="submit">
</form>

Your ajax code is working. It is calling the url b.php and printing the value to output. However, the result is not what you expect.
When you made the ajax call and send the data in the form, the evaluation of b.php will be in response when ajax request is successful. Try to make the following change :
From
window.location.href = "b.php";
to
alert(response);
You will see what you send in the input in a message box. Follow your code adapted. Note I added a button to make the call:
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
url: 'ajax.php',
dataType: 'html',
type: 'POST',
data: {
value: $('#value').val()
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
alert(response);
console.log(response);
//window.location.href = "b.php";
}
});
});
});
</script>
</head>
<body>
value: <input type="text" id="value">
<input type=button id="submit" value=go>
</body>
</html>
ajax.php
<?php
echo $_REQUEST['value'];
?>
This is the ajax approach. But if you need only pass the value in the form to b.php, you do not need ajax. Just create a form and use b.php as it action like this:
index.php
<html>
<head>
</head>
<body>
<form method="POST" action="b.php">
value: <input type="text" id="value" name="value">
<input type=submit value=go>
</form>
</body>
</html>
b.php
<?php
echo $_REQUEST['value'];
?>
Note the changes I made in your html.

Try this one, i think this will help you.
Here i create two pages.
one is a.php and another page is b.php
a.php
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var abc='';
$('#submit').click(function() {
var abc=$('#abc').val();
$.ajax({
url: 'b.php',
dataType: 'html',
type: 'POST',
data: {
value: abc
},
error: function(xhr) {
console.log('ajax went wrong!');
},
success: function(response) {
console.log(response);
var stateObj = { foo: "b" };
history.pushState(stateObj, "page 2", "b.php?value="+response);
$('#hid').hide();
$('#res').html(response);
}
});
});
});
</script>
<html>
<body>
<div id="hid">
Value: <input type="text" id="abc" /> <input type="button" id="submit" value="Get Value" /><br>
</div>
<div id="res"></div>
</body>
</html>
b.php
<?php
echo $_REQUEST['value'];
?>

use
$_post['value'] instead of $_request['value']

Related

What is error in code below while submitting AJAX from handeled by PHP?

I have a file called try.php where there is code below having all javascript, PHP and html file in itself.
<?php
if(isset($_POST["submit"])){
echo "hello";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form method="POST" id="myForm">
<input name="name" type="text" placeholder="Your Name">
<input name="email" type="text" placeholder="email">
<input name="submit" type="submit" value="Submit">
<div id="display"></div>
</form>
<script>
$(document).ready(function(){
$("#myForm").submit(function(event) {
event.preventDefault(); //prevent default action
window.history.back();
var form_Data = $(this).serialize();
$.ajax({
type: "POST",
url: "try.php",
data: form_data,
cache: false,
success:function(response){
alert(response);
}
});
});
});
</script>
</body>
</html>
The target of above code is just to submit form without reloading the page simply using AJAX and the form data should be handled by php here just echo "hello". The above code works fine it submits and php handles all properly but page is reloading. What should be the change in code?
Try this as javascript code
$(document).ready(function(){
$("#myForm").click(function(event) {
event.preventDefault(); //prevent default action
var form_Data = $(this).serialize();
$.ajax({
type: "POST",
url: "try.php",
data: form_Data,
cache: false,
success:function(){
alert("hello");
}
});
});
});

ajax not working .No alert shown after submission

I am trying to insert a name into my database. There is a form asking to enter name.There is also a submit button.on clicking the submit button no alert is show.I am new to ajax.
this is index.php.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
</script>
</head>
<body>
<form action="" method="post">
Name:
<input type="text" name="name" id="name" />
<br />
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
This is ajax.php
<html>
<body>
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("freeze",$query);
$name='l';//$_POST['name'];
mysql_query("insert into tt values('','$name')");
?>
</body>
</html>
Be careful with url's in ajax. Your url is 'ajax.php', this is a relative url, so, if your page is at url http://localhost.com/index.html (for example), ajax will fire a post to http://localhost.com/index.html/ajax.php (and that's probably wrong). Try use absolute url, for that, add '/' at begin of url, then ajax will be fired against http://localhost.com/ajax.php.
Your ajax code should look like code below:
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
The submit event is triggered on the form, not the submit button. So
$("#submit").submit(function() {
will not ever be triggered, because #submit selects the button, not the form. You need to give an ID to the form:
<form id="myform">
then use
$("#myform").submit(function() {
You also need to use event.preventDefault() or return null in the event handler, to prevent the form from being submitted normally when the function returns.

Send input value to php using ajax with result printed to div

I'm trying to send an input value to a php script and have the returned value posted to a div, using ajax, but I can't seem to get this right. Any help/suggestions would be appreciated. Thanks!!
This is what I have by now, but console says: "Failed to load resource: the server responded with a status of 404 (Not Found)".
test1.php:
<script>
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$(document).ready(function(){$("#content").load("test2.php");});
}
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit">
</form>
<div id="content"></div>
test2.php:
<?php
$string=$_POST['id1'];
require_once('connect.php');
$inf = "SELECT * FROM `comments` WHERE date='$string'";
$info = mysql_query($inf);
while($info2 = mysql_fetch_object($info)) {echo $info2->username.$info2->date;}
?>
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
<div id="content"></div>
When you submit the ajax request, you're already submitting your content to test2.php, so you don't need to load it again. In the success function, you can append the result to the div from the callback.
$(document).on('click','#submit',function(e) {
e.preventDefault();
$.post('test2.php',{url: $('#id1').val()},function(data){
$("#content").html(data);
}
});
});
404 (Not Found) Error is for page not found. Please make sure that file test2.php is exist in same folder. Check url.
Also you can copy the URL from console and paste it in the browser URL to check the url correct or incorrect.
jQuery
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
HTML
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
You could try this:
<script>
$('#submitBtn').on('click',function(){
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$("#content").html(data);
}
});
return false;
});
</script>
<form name="input">
<input type="text" id="id1">
<input id="submitBtn" type="submit">
</form>
<div id="content"></div>

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<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>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

jquery-ajax: pass values from a textfield to a php variable (same a file)

jquery-ajax: pass values from a textfield to php file and show the value
i made a variation of the link above this time using only one file and no div tag.
test.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function(result){
window.location.reload(true);
}
});
window.location.reload(true);
});
});
</script>
</head>
<body>
<input type="text" id="inputtext">
<input type="button" id="submit" value="send">
<?PHP
if(isset($_POST['dataString'])){
$searchquery = trim($_POST['dataString']);
print "Hello " . $searchquery;
}
?>
</body>
</html>
value from dataString won't show. why?
Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it.
Try this
In test.php:
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "anothepage.php",
data: dataString,
success: function(result){
$('#result').html(result).
}
});
return false; //so the browser doesn't actually reload the page
});
And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css.
<form method="POST" action="">
<input type="text" id="inputtext" value="" name="inputtext">
<input type="submit" id="submit" value="send" name="submit">
</form>
<div id="result"> <!-- result from ajax call will be written here --> </div>
In anotherpage.php:
if(isset($_POST['inputtext'])){
$searchquery = trim($_POST['inputtext']);
echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we?
}
When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results.
You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input.
If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code.
<?php
if( isset($_POST['dataString']))
{
echo 'Hello ' . trim( $_POST['dataString']);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing jQuery AJAX</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function( data){
alert( data);
}
});
});
});
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" id="inputtext" />
<input type="button" id="submit" value="send" />
</form>
</body>
</html>

Categories