ajax submit form why it cannot echo $_POST - javascript

I'm test using ajax submit form (submit to myself page "new1.php")
The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.
here is new1.php page
<?php
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform" action="new1.php" method="post">
Firstname : <input type="text" name="firstname"> <br>
Lastname : <input type="text" name="lastname"> <br>
<input type="submit" value="Submit">
</form>
<script>
// this is the id of the form
$("#myform").submit(function(e) {
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data)
{
alert('yeah'); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>

In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.
Example:
PHP code:
if($_POST)
{
$result['firstname'] = $_POST['firstname'];
$result['lastname'] = $_POST['lastname'];
echo json_encode($result);
die(); // Use die here to stop processing the code further
}
JS code:
$("#myform").submit(function (e) {
$.ajax({
type : "POST",
url : 'new1.php',
dataType : 'json', // Notice json here
data : $("#myform").serialize(), // serializes the form's elements.
success : function (data) {
alert('yeah'); // show response from the php script.
// make changed here
$('input[name="firstname"]').text(data.firstname);
$('input[name="lastname"]').text(data.lastname);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

When you use form as a serialize you have to retrieve like this.
Edit your ajax like this :
data: { formData: $("#myform").serialize()},
Then you can retrieve like this in your controller:
parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;

Make some changes in javascript here:
success: function(data)
{
$('#response').html(data); // show response from the php script.
}
And in html code make a div with id response
<div id="response"></div>

Change from
alert('yeah'); // show response from the php script.
to
alert(data); // show response from the php script.

the value firstname, lastname will not display because you called the new1.php via ajax and the data (firstname, lastname and the page code) is returned to java script variable (data) you need to inject the data to your document
Try this
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data) {
document.documentElement.innerHTML = data;
}
});

Related

How to pass variable from php for() to ajax when clicking a button?

when clicking (.refresh)button、how would you pass $data_name to ajax which you'll get by for() in body field of php script?
I would like to pass the variable for selecting data from database.
2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added
$dataname= $_POST['dataname'];
In for() I'm getting data from DB and showing data tables, DATA A~C.
When clicking the button for each data, I would want to get the new data from data base.
I was able to get it, just writting "A" for Ajax, but I would want to pass variable for many tables.
[enter image description here][1]
[1]: https://i.stack.imgur.com/zpJ7B.png
<head>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
//more code
},
error: function(data) {
//more code
}
});
</script>
</head>
<body>
<?php
//more code for(){  getting $data_name(A、B、C)here >
echo <<<EOD
<button class='refresh'>REFRESH DATA</button>
<table class='show'></table>
EOD;
?>
</body>
You can use a different PHP to return the JSON or the same.
So if you want to use the same script you basically want to send a JSON with the data when your PHP script gets a POST.
So you have to check:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request comes from Javascript doing POST
// Query Database and return a JSON with the field "data_name"
} else {
// Render your form like now you're doing now, the request com from the browser loading the page
}
//select.php
<?php
$data= $_POST["data_name"];
echo json_encode( $data);
?>
<script>
$(document).ready(function(){
$('.refresh').click(function(){
$.ajax({
// 通信先ファイル名
url: "select.php",
type: "POST",
data: ({"data_name": $data_name}),
success: function(data) {
// getting $data_name(A、B、C)here
},
error: function(data) {
//more code
}
});
</script>

post in ajax with php get me undefined index

i want to send/pass data from the client to server by (ajax to php) but when i try this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
console.log(w);
}
});
</script>
<?php
echo $_POST['data'];
?>
in my browser i got success print out which mean that the javascript code is working fine i guess , by in php i got Undefined index
p.s my file name is loo.php all the code is in the same file
edit: i have tried to separate my files like this:
my loo.php file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'test.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
my test.php file:
<?php
echo $_POST['data'];
?>
still got undefined index
p.s. i navigate Manual to test.php file after i run loo.php file
You get this error because when loading the page the POST request has not yet been sent. So show the submitted data only if it exists, otherwise, show the JavaScript code.
<?php
if (isset($_POST['data'])) {
die($_POST['data']);
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: {data: 'some data'},
success: function (response, w) {
console.log(w);
}
});
</script>
Try this.
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['data'];
?>
Try this
Html file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_value"></div>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
$("#data_value").html(response);
}
});
});
PHP file (loo.php)
<?php
print_r($_POST);
?>
try to change the handler this way:
if(isset($_POST['data'])){
function return_data() {
die(json_encode($_POST['data'])));
}
return_data();
}
Answer after you edit the question:
$_POST is the array sent by the HTTP Post request. so if the request to the page named test.php or whatever is not HTTP POST Request the $_POST array will be empty. but the $_GET array may have some data if you sent them.
and navigation to a page is a get request to that page unless you used a form with method="post".
so what you are doing with ajax call is correct. but navigating to test.php manually without a form with post method is not gonna fill the $_POST array.
because when you make the Ajax call, it is done, it just makes the post-call correctly and everything is ok but when you navigate to that page it is a get request and it won't fill the $_POST array.
to do so, you don't need ajax at all. you can have this form
<form method="POST" action="test.php">
<input type="text" name="data" value="some data" />
<input type="submit" value="submit" />
</form>
so either you use ajax and handle whatever you want to handle in the ajax success method. or use form and send the request to the page and handle it there.
the answer to the question before the edit
If they are in the same file it won't work like that, because when the file loads the $_POST['data'] is not exists at all, and after you run the ajax call, it exists within that call, not in your browser window.
so you can check if $_POST['data'] exists so you are sending it from ajax call so you can return it and use it inside your ajax success function.
conclusion:
you cannot put them in the same file and expect ajax will load before the actual php.
it will first load the whole file then it will run the ajax.
the undefined index is from the server before you even see the HTML page.
A solution could be:
File with your html and ajax functions index.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: 'post',
url: 'loo.php',
data: { data: 'some data' },
success: function(response,w) {
// use the response here
console.log(w);
}
});
</script>
and another with your logic loo.php
<?php
header("Content-Type: text/plain"); // if you want to return a plain text
// if you want to return json it could be header('Content-type: application/json');
echo isset($_POST['data'])? $_POST['data']: ''
?>

keep failing to send values to PHP with Ajax

code lovers!
i want to send a value of input box to PHP and check the value on the PHP file. when the page is loaded. but i keep failing no matter what i try in various ways.
basically i want to send the value of this input box to PHP.
Current Counte : <input type="text" name="currentCount" id="currentCount" value="6">
<span> result </span>
and these are what i have tried so far but nothing really worked.
<script>
$( document ).ready(function() {
var currentCount = $("#currentCount").val();
console.log(currentCount);
$.post("counteSever.php", {currentCount2: currentCount},
function(result){
$("span").html(result);
});
});
</script>
Second One
<script>
$( document ).ready(function() {
var currentCount = $("#currentCount").val();
console.log(currentCount);
$.ajax({
url: 'counteSever.php',
type: 'POST',
data: {"currentCount2": currentCount},
dataType: 'JSON',
})
.done(function() {
console.log(currentCount + " Done");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
and Third one
$.ajax({
type: 'POST',
url: 'counteSever.php',
data : { "currentCount2" : currentCount},
dataType: 'JSON',
success: function(response){
$('span').text(name);
alert(response.data);
}
});
and my simple PHP file to check if the value is sent or not.
<?php
$current = $_POST['currentCount2'];
echo $current;
?>
Seriously don't know what's the problem, i don't have any problem to check the value on client-side, but it doesn't seem to send the value to PHP cos i keep having "Undefined index: currentCount2 " error.
if i don't have any problem with the ajax function? Thanks!
As i understood your question you want to send the value of input field to PHP file and receive it back and display in <span> tag.
So here are few minor changes you need to make. see my example below.
IN AJAX SUCCESS FUNCTION ,you can use these 3 ways to bind result to the <span> tag
1)$('span').text(response);
2)$('span').append(response);
3) $('span').html(response);
You will know the difference between them when to use those in these example
This is HTML file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
Current Counte : <input type="text" name="currentCount" id="currentCount" value="6">
<br>
<span> result </span>
<script>
$(document).ready(function(){
var currentCount = $("#currentCount").val();
$.ajax({
type: 'POST',
url: 'counteSever.php',
dataType:'json',
data : {currentCount2 : currentCount},
success: function(response){
console.log(response);
$('span').append(response);
}
});
});
</script>
</body>
</html>
This is php File counteSever.php
<?php
$current = $_POST['currentCount2'];
echo $current;
?>
And here is the result image :
#james, Put the ajax code in bottom of your html file. You r using document.ready(). It will work:)

php ajax form submit ..nothing happens

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?
I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine
Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

How to pass data to PHP page through AJAX and then display that page in another's DIV?

I have 2 pages with which I am working with: test1.php and test2.php. test1.php contains 2 <DIV> tags, one named "SubmitDiv" and the other named "DisplayDiv". In SubmitDiv, there is a check box and a submit button. When the check box is checked and the submit button is clicked, I would like it to display test2.php in the DisplayDiv div tag. I have figured that much already.
However, now I want test2.php to receive data from test1.php and process that data. In this case, it is receiving the checkbox's name, "chk" and will be printing that with an echo command. This is where I am a bit stumped as to how to go about this. After searching a bit for an answer, this is what I have written so far:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
function sendQuery() {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function() {
$('#DisplayDiv').load('test2.php');
}
});
return false;
}
</script>
<body>
<form id="SubmitForm" action="" method="post">
<div id="SubmitDiv" style="background-color:black;color:white;">
<input type="checkbox" id="chk" name="chk" form="SubmitForm" value="chk">CHECK</input><br>
<button name="submit" id="submit" type="submit" form="SubmitForm" onclick="return sendQuery();">Submit</button>
</div>
</form>
<div id="DisplayDiv"></div>
</body>
</html>
test2.php:
<html>
<meta charset="utf-8">
<?php
$chk = $_POST['chk'];
echo $chk;
?>
</html>
When the submit button is clicked, however, all it does is refresh the page, rather than display the test2.php in the DisplayDiv like it's supposed to. Any ideas on how to pass the data to test2.php and then also display it within the DisplayDiv section?
Instead of .load function use the following
success: function(response) {
$('#DisplayDiv').html(response);
}
If you want to use e.preventDefault(); you must pass the event to the function
function sendQuery(e) {
e.preventDefault();
//...
}
Otherwise I assume your form is simply submitted on click.
You must first remove e.preventDefault(); in the sendQuery function because that is failing to return false onclick.
Then change your AJAX call to as follows:
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function(data) {
$("#DisplayDiv").html(data);
}
});
This works:
$.ajax({
type: 'GET',
url: 'data.php',
data: {
"id": 123,
"name": "abc",
"email": "abc#gmail.com"
},
success: function (ccc) {
alert(ccc);
$("#result").html(ccc);
}
});
Include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
data.php
echo $id = $_GET['id'];
echo $name = $_GET['name'];
echo $email = $_GET['email'];

Categories

Resources