jQuery ajax back to $_POST instead of REQUEST payload - php

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"

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

Unable to pass a variable through an ajax request

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']);
?>

Multiple forms in in a page - load error messages via ajax

I having multiple forms in a single page submitting via jQuery ajax. All forms use same class names. Also i am using malsup jquery plugin for form submission.
I can successfully pass the data to a php file but the error message is reflecting on all forms div.message. I don't want to have different form ids because i need to have all ids in the jquery then.
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
jQuery part
<script>
$(document).ready(function() {
$('.myform').on('submit', function(event) {
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
$('div.message').append('<div>'+message+'</span>');
}
}
});
});
});
</script>
How can i append the error message to the submitted form's div.message correctly?
Any help will greatly appreciated.
I think you can get the msg div before post .
$(document).ready(function() {
$('.myform').on('submit', function(event) {
msgDiv=($this).children('div.message');//before post get the msg div first
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
msgDiv.append('<div>'+message+'</span>');
}
}
});
});
});
</script>

How to use the .serialize() method to send form values to PHP via an AJAX request

I'm using the .serialize() method to serialise my form's values and send them to my PHP script in an AJAX request.
My form:
<form name="myform" action="" method="post" class="form">
<input type="text" name="one" value="" />
<input type="text" name="two" value="" />
<input type="text" name="three" value="" />
<input type="submit" name="submit" value="Submit" />
</form>
My AJAX request:
$( '.form' ).on( 'submit', function( e ) {
$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'json',
data: {
'action': $action,
'querystr': $( this ).serialize()
}...
In my PHP script, I expected to be able to do something like this $one = $_REQUEST['one'] but when I do that the value of $one is null.
Why doesn't $_REQUEST['one'] contain the value of my form's input field?
On php end
$params = array();
parse_str($_POST['querystr'], $params);
echo $params['one'];
It's all in your ajax call. In the 'data' property , you declare the post fields that are sent to PHP. So in your code:
$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'json',
data: {
'action': $action,
'querystr': $( this ).serialize()
}
You declare
$_POST['action']
, and
$_POST['querystr'].
Thats why $_POST['one'] is null - because it's not sent/defined etc.

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