Unable to pass a variable through an ajax request - php

I'am trying to pass a parameter using ajax to another php page and view the passed parameter in there. But its only redirecting page.parameter is not passed
This is my form.Used to get name through input field
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
This is the ajax code I'am using pass my parameter to ajax.php page.
$("#regform").submit(function(e) {
e.preventDefault();
var form = $(this);
//var url = form.attr('action');
var senddata = {"fname": $('#fname').val()};
console.log(senddata);
$.ajax({
type: "post",
contentType: "application/json",
url: "ajax.php",
dataType: 'json',
data: JSON.stringify(senddata),
success: function(data) {
console.log(data);
}
});

Check this.it is working.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<form id="regform" method="post" action="">
<div>
First Name:
<input type="text" name="fname" id="fname" />
<input type="submit" class="color" name="loginBtn" id="loginBtn" value="register" />
</div>
</form>
<script>
$("#regform").submit(function(e) {
e.preventDefault();
var senddata = $('#fname').val();
console.log(senddata);
$.ajax({
type: "post",
url: "ajax.php",
dataType: 'json',
data: {fname:senddata},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP
<?php
echo ($_POST['fname']);
?>

Related

Server response is printed on the browser but not returned to success function in ajax

I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser
<body>
<script>
$(document).ready(function() {
$.ajax({
url: $("#form").attr("action"),
type: "POST",
data: $("#form").serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<form action="a.php" method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
</body>
my php code
<?php
echo 'hii';
?>
Can you Replace AJAX script below mentioned.
<form method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
$("#form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: 'a.php',
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});

print ajax response with php

I cannot get the alert to work after sending the data in ajax? Could anyone tell me what I'm doing wrong?
My form:
<body>
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
// AJAX SEND POST DATA
$('form').on('submit', function() {
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
dataType: 'json',
data: $(self).serialize(),
success: function() {
alert("blabla");
}
});
});
</script>
This is my submit2.php file.
<?php echo "bla"; ?>
There is no problem with your HTML or JQuery code. The problem is with submit2.php file. Your AJAX function is looking for a JSON response. Return a JSON response from submit2.php
submit2.php
echo json_encode(array("message"=>"Here is the message"));
Your code should be like this:
HTML
<form action="" id="form1" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id="submit1" value="Submit">
</form>
jQuery
$("#form1").submit(function(e){
e.preventDefault();
var self = this;
$.ajax({
type: 'post',
url: 'submit2.php',
// dataType: 'json', unless you're expecting json object as server response, remove this
data: $(self).serialize(),
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
submit2.php
<?php
if(isset($_POST['firstname']) && isset($_POST['lastname'])){
echo $_POST['firstname'] . " " . $_POST['lastname'];
}
?>

jQuery ajax back to $_POST instead of REQUEST payload

I remember I using the jQuery ajax post last year and i could simply get the post data by typing $_POST['param']. Today I am using it again for a project so I loaded the latest jQuery lib and used the following code:
<script type="text/javascript">
$(document).on('submit', '.ajaxform', function(e){
e.preventDefault();
var datastring = $(this).serialize();
$.ajax({
type: "POST",
data: datastring,
contentType: "application/json; charset={CHARSET}",
dataType: "json",
beforeSend: function(){
console.log($(this).serialize());
},
success: function(data){
alert('yes');
},
error: function(errMsg){
alert('error');
}
});
});
</script>
<form action="" id="register" name="register" class="ajaxform" method="post" enctype="multipart/form-data">
<input type="text" name="username" value="" />
<input type="password" name="password" value="" />
<input type="hidden" name="action" value="register" />
<input type="hidden" name="{TOKENID}" value="{TOKEN}" />
<input type="submit" value="Register" />
</form>
After I submit, I can't get the input field value by typing $_POST['username'].
I checked the inspect element, and I noticed that something is different.
Request URL:http://project0/member.php
Request Method:POST
Status Code:200 OK
...
...
Content-Type:application/json; charset=UTF-8
...
...
Request payload:
username=asd&password=asd&action=register&29cd5e5ca1=73050db390872eb7c3fc564206b961c59a6363d6
Is that why i can't get the POST data by simply typing $_POST['param']? How do I go back to POST data and not the payload?
Except:
contentType: "application/json; charset={CHARSET}"
Use(default value of content type):
contentType: "application/x-www-form-urlencoded; charset=UTF-8"

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>

Post form with Ajax and jQuery

Start learning Ajax (and jQuery), I encounter the issue with post form data, which I could not resolve myself.
First, here is the simple example where I collect data, post it, and displayed it on a new page:
<!-- index.html -->
<form id="myForm" action="test.php" method="post">
<input type="checkbox" id="ch1" name="Ch1" value="1">Check Box 1 <br />
<input type="checkbox" id="ch2" name="Ch2" value="2">Check Box 2 <br />
<input type="submit" id="myButton" />
</form>
<?php
// test.php
print_r($_POST);
?>
Then I tried with Ajax and jQuery. I slightly modified the form pasted above:
<!-- index.html -->
<form id="myForm">
<input type="checkbox" id="ch1" name="Ch1" value="1">Check Box 1 <br />
<input type="checkbox" id="ch2" name="Ch2" value="2">Check Box 2 <br />
<input type="button" id="myButton" value="Submit"/>
</form>
And here is the jQuery function:
// script.js
$(document).ready(function () {
$("#myButton").click(function () {
$.ajax({
cache: false,
type: 'POST',
url: 'test.php',
data: $("#myForm").serialize()
});
});
});
My question is, how to reimplement the jQuery function to echo the result in the test.php tab? I crawled the many resources, but i didn't find any solution.
Thanks in advance for any pointer.
Best, Andrej
You're going to need a success callback, which I'll assume will be some HTML...
$(document).ready(function(){
$("#myButton").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'test.php',
data: $("#myForm").serialize(),
success: function(response) {
$("#someElement").html(response);
}
});
});
});
Try this.
$(document).ready(function(){
$("#myButton").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'test.php',
data: $("#myForm").serialize(),
success: function(data){
alert(data);
}
});
});
});
I believe you're looking for the success in the .ajax options parameter.
$.ajax({
...
success: function(d){
alert(d);
}
});

Categories