I am trying to pass data to php code using ajax. but I cant get is success.
<?php
$message = $_POST["message"];
$buyer_name = $_POST["buyer_name"];
$order_number = $_POST["order_number"];
$account = $_POST["account"];
$designer = $_POST["designer"];
echo $message; ?>
this is my js code.
var formdata = {buyer_name:byrName,order_number:orderNum.trim(),account:account,designer:'admin',message:'testing'}
if(autoMode){
$.ajax({
type:'POST',
url: 'msgHandle.php',
data: formdata,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
},
success: function(data) {
alert(data);
},
error: function() {
alert('failed');
}
});
I have set a button to click and when clicked in runs this ajax code. the output is a alert with empty message. that means it success but seems like variables does not pass correctly to the php code. what is wrong in my code, I can't find.
I tried your code and found that by removing all the three parameters
contentType: false,
cache: false,
processData: false,
From the code posts your data onto another page.
Tried for just a sample array.
Related
I use form for input date to DB. After submit form I need refresh php code (because when form is submit then I need display this value sent, instead of this form.)
I've script:
$(document).on('submit','#form_create_user',function(e){
e.preventDefault();
var fd = new FormData(this);
var obj = $(this);
fd.append('course_id', "<?php echo $this->uri->segment(4); ?>");
obj.find('input[type="submit"]').val("Tworzenie...")
$.ajax({
url: $(this).attr("action"),
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
// obj.find('input[type="submit"]').val("Confirm user")
}
});
$.ajax({
url: "<?php echo site_url('home/saveValues/'); ?>",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
toastr.success("Success created user.");
obj.find('input[type="submit"]').val("Potwierdź")
}
});
})
I can implement to this code refresh page below script:
document.getElementById("form_create_user").onsubmit = function(){
window.location.replace("<?php echo $course_details_url_back; ?>");
}
But the problem is, I have main tab and togle switch tabs with end url #user #domain etc.
example:
- mydomain.com/course
- mydomain.com/course#user
- mydomain.com/course#domain
When I run url in browser: mydomain.com/course#user then still is displayed main tab with url mydomain.com/course
This working only on switch tabs (without directly run url) So when I use above solution this stil reload page and back to main mydomain.com/course
So I need to find any solution for implement to above script refresh php code without reload page. Can anyone help me?
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>`);
}
});
Please how can I send a whole number like twelve to php using ajax. I have been able to send string variables using both GET and POST methods successfully, but when it comes to numerical values it becomes a problem , I don't know why.below is my jQuery
function user_ajax_call(){
var data = $(".people_names").length;
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data:{data:data},
processData: false,
contentType: false,
cache:false,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And these are sample php lines
$limistart = $_POST['data'];
if(isset($limistart)){
echo $limistart;
}
You need to send them through: data.
You could do something like this in your data variable:
data = {
name_length : $(".people_names").length,
number : 12
};
And just pass it like this in your ajax:
function user_ajax_call(){
var data = {
name_length : $(".people_names").length,
number : 12
};
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data: data,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And in your server side access it like :
$_POST['name_length']
$_POST['number']
If you change the value of contentType key it should work correctly.
So change this:
contentType: false
to:
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
EDIT:
and change the line:
processData: false
to:
processData: true
I am trying to get the excelPrintarea and post that data to my Employees controller. But when I add the data and datatype attribute it tells me it's an illegal invocation. I don't understand why it is saying that.
Also when I leave the data, datetype and POST out the downloadExcel from my employees controller does fire.
function printExcel() {
var excelPrintarea = document.getElementById('printarea');
$.ajax({
url: "<?php echo $this->webroot; ?>employees/downloadExcel",
data: {myPrintArea: excelPrintarea},
dateType: 'json',
type: 'POST',
cache: false,
success: function(excelPrintarea) {
alert("printing excel worked")
}
});
}
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);