Ajax post returns nothing - php

I am trying to send some data with post to a php file but for some reason its not being posted. I receive an empty array in console log from the php file on var_dump.
Here is code I have in these files:
index.php
<button type="button" class="btn btn-warning" id="resetPassword">Reset Password</button>
<script>
$(document).ready(function (e){
$("#resetPassword").click(function(e){
e.preventDefault();
$.ajax({
url: "scripts/process.php",
type: "POST",
data: {name: 'test'},
cache: false,
processData:false,
success: function(data) {
if (data === 'Success') {
new PNotify({
title: 'Success!!!',
text: 'Request completed successfully.',
type: 'success',
styling: 'bootstrap3'
});
$('#exampleModal').modal('hide');
$('#datatable-buttons').DataTable().ajax.reload();
} else {
console.log(data);
new PNotify({
title: 'Error!!!',
text: data,
type: 'error',
styling: 'bootstrap3'
});
//document.getElementById("status").className += " alert-danger";
//$("#status").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
});
</script>
Here is the php file process.php.
var_dump($_POST);
Result in console.log:
array(0) {}
Solution:
Remove processData: false
thanks guys.

Remove processData:false, section and then try again.

Try this
before or after
e.preventDefault();
var formData = $("#yourform_id").serializeArray(); //form data
and replace data with this line datas
data: formData,
remove
processData:false,

What you are using while returning data in process.php file? ECHO or RETURN?
Try ECHO, if it does not work then try RETURN statement. Rest of your code seems OK.
To debug use print_r() on scripts/process.php and check it in browser's console for out put. Also, you can use toSource of javascript to check variable's data

If you try by processData:false ,its need data is raw string
change from
data: {name: 'test'},
into
data: "name=test",

Related

Data is not defined Jquery, PHP

I cant define data in ajax jquery function, where can be problem? I try everything, choose other server, other browser, remove cache, add data manually and always it is undefined...
Server: Laragon
App.js , add-new.php
(function($){
var form = $('#add-form');
form.on('submit',function(){
event.preventDefault();
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
})
.done(function(data){
console.log("Data: " + data);
});
});
}(jQuery))
<?php
die("test");
//include
require('./config.php');
$id = $database->insert('items',[
'text' => $_POST['message']
]);
if($id){
die('success');
}
?>
Response screen:
response screen
I think you have missed success parameter in ajax function.
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function(data) {
console.log("Data => ", data);
}
});
Hope it may work for you.

Ajax post not sending data to PHP file

So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});

Post array to PHP through ajax

I'm trying to post an array through ajax to php file on form submit.
<form action="echo.php" method="post">
<input name="qwerty[]" type="text">
<input name="qwerty[]" type="text">
<input type="submit"/>
</form>
Basically, I use this to post to php file:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data:{today:alt},
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
Above is an example of what I'm trying to do. I've searched, but unable to find the solution to that. How can I post an array through ajax.
You can serialize the form data using data:$('#form').serialize() function and can send it using ajax or you can use JSON data type to send an array.
var Data = $('#yorFormName').serializeArray();
var JSONData = JSON.stringify(convertToJSON(Data));
$.ajax({
url: your_url,
type: "POST",
dataType: "json",
data: JSONData,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.status == 'success') {
// success logic
}
},
error: function () {
var errMsg = "Unexpected Server Error! Please Try again later";
}
});
Hope this will help you.
Instead of bothering how to send what you need, I advise you to use jquery serialize() method:
function getlist(alt) {
$.ajax({
type:'POST',
url: 'markattlist.php',
data: $("form").serialize(),
success: function(data){
$('#helloflist').html(data);
},
error:function (){}
});
}
And check on server-side with
print_r($_POST);
data: JSON.stringify({d:c}),
Encode it as json and decode it on the server:
$data=json_decode($_POST["data"]);

jQuery: $.ajax() won't fire or no response from PHP

I've just started learning jQuery and PHP, and I encountered a problem when I try to use Ajax. Either the $.ajax() function won't fire, or PHP won't return anything, I cannot tell. I must have forgotten something really stupid, I guess...
Here's the code. There's no reply, no alert, nothing.
js:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
done: function(response) {
alert("response");
}
});
});
</script>
PHP:
<?php echo "Something"; ?>
Thanks in advance.
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
done: function(response) {
alert("response");
}
});
supposed to be
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
}).done(function(response) {
alert("response");
});
success , error methods are generally declared in the place where you have written done which are now deprecated
You have your done in the wrong place.
Try this instead:
$.ajax({
url: "get_profile.php",
type: "GET",
data: {}
})
.done(function(response) {
alert("response");
});
You can have alternative option for check is there any error in your ajax call. and you can also do some stuff before getting the response of your ajax call like loading image shows to end users until the response result. for this you can use following code:
$.ajax({
url: "get_profile.php",
type: "GET",
data: {},
beforeSend:function(){
//do something like loading image
},
success:function(response){
alert(response);
},
error:function(e){
alert("something wrong"+e);
}
})

How to run PHP script in the back by a jquery button

I need to run some PHP code from a file when I click a button from jQuery. This is the code I have:
$(document).ready(function(){
$("#btnSubmit").button().click(function(){
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});
It shows the alert of "error". I have the releaseBackEnd.php file in the same directory of the javascript file.
check the response in firebug console .. if u don't have firebug add it to your firefox using this link
https://addons.mozilla.org/en-US/firefox/addon/1843/
Change
$("#btnSubmit").button().click(
to
$("#btnSubmit").click(
and check whether the php page is sending the response or not.
Try getting the error in the error callback function using the XMLHttpRequest.
error(XMLHttpRequest, textStatus) {
}
Try this code...
$(document).ready(function(){
$("#btnSubmit").bind('click',function() {
alert("button 1");
$.ajax({
url: 'releaseBackEnd.php',
type: 'POST',
async: false,
data: {},
dataType: 'xml',
error: function(){
alert('Error');
},
success: function(data){
//check error
alert("success!");
}
});
});
});

Categories