jquery not calling ajax handler - javascript

This should be a really simple fix, but I am pulling my hair out.
This part of the site is really simple. I have a .js file that uses ajax to insert a post into the database when submit is clicked. I get the success part of the jquery, but nothing ever gets put into the database.
Here is the jquery in the $(document).ready(function():
//Button for profile post
$('#submit_profile_post').click(function(){
$.ajax({
type: "POST",
url: "includes/handlers/ajax_submit_profile_post.php",
data: $('form.profile_post').serialize(),
success: function(msg) {
$("#post_form").modal('hide');
location.reload();
},
error: function() {
alert('Failure');
}
});
});
Here is the ajax handler:
<?php
require '../../config/config.php';
include("../classes/User.php");
include("../classes/Post.php");
include("../classes/Notification.php");
if(isset($_POST['post_body'])) {
$post = new Post($con, $_POST['user_from']);
$post->submitPost($_POST['post_body'], $_POST['user_to']);
}
?>
As I said, If I add an alert under the jquery success, I get it just fine but nothing happens after that.
Any help would be greatly appreciated!

Try using FormData
var fd = new FormData();
fd.append('field', value);
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
`enter code here`
success: function(data) {
alert(data);
}
});

Related

Posting data with jQuery in Wordpress succeeds, but fails with FormData

I want to upload a file using jQuery/Ajax in my Wordpress plugin. The javascript to PHP call works. So the wiring etc. works. But as soon as I post the formData, necessary to post the files, I don't reach the PHP function any more.
The javascript,
var doesntWork = new FormData();
doesntWork.append('file', 'a name');
var withthisItWorks = 'text'
var data = {
'action': 'emfi_file_upload',
'data': doesntWork
}
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: data,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
The PHP function just returns a string answer:
function emfi_file_upload_callback() {
echo 'Yes, in the callback';
wp_die();
}
When I put the plain text in my data object I get answer from the PHP function. When I put the formData in, there is no answer. I've tried a lot of examples on the internet, but it boils down to this every time. Adding contentType: false and processData: false, as was mentioned somewhere else, didn't help. What's wrong?
All fields that are being sent must be in the formdata object.
Additionally for FormData to work with jQuery.ajax, processData and contentType have to be set to false.
var doesWork = new FormData();
doesWork.append('file', someFile);
doesWork.append('action', 'emfi_file_upload');
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: doesWork,
contentType: false,
processData: false,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});

Undefined index Jquery Ajax POST

I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});

How to send Form Data and other Data using AJAX

I'm trying to send HTML form data using AJAX however I'm also trying to send other data along with the same AJAX POST call.
Is this possible?
$('#HTMLConForm').on('submit', function (e)
{
e.preventDefault();
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data:{
'otherinfo': otherinfo,
'form_data': new FormData(this),
},
processData: false,
contentType: false,
success: function (data)
{
alert('You Have Registered')
/*window.location = "index.html"; */
},
error: function (xhr, desc, err)
{
}
});
});
Any help with be appreciated!
Pass the FormData object itself to data, don't wrap it in a simple object.
Use the FormData object's append method to add additional data.
e.preventDefault();
const formdata = new FormData(this);
formdata.append("otherinfo", otherinfo);
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data: formdata,

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

AJAX request not working properly

Hey guys and gals,
I have a form that I would like to use AJAX to submit. For the callback function basically what I want to happen is, the form elements disappear (.hide) and are replaced by a div element (which will ready success or something of that nature). I then want the function to pause for 5 seconds and then redirect to a different URL.
The AJAX request successfully submits (as I receive an e-mail to the specified address as I should) but the callback function is not carrying out properly. Any suggestions?
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(5000);
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
}
})
}
}
**
UPDATE #1
**
This is the only error code that I am getting when I initially load the website (I've heard these errors only pop up in the dev tools and do not affect the user?)
But then when I submit the form I get this error code
I've also updated my JavaScript to the below code, taking advice from a few people who posted, it's still not working 100% though
$(document).ready(function() {
var $form = $('form');
$form.submit(function(){
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
}
});
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000)
});
});
Joey
setTimeout usage is wrong.
See :
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000);
}
})
}
});
Further, the following should ideally be declared separately, if you want the user to click a link and go after ajax success.
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})

Categories

Resources