Passing serialized data from jquery mobile to PHP using $.post - javascript

I am using jQuery mobile to pass form data to a PHP script but I can't access the data in PHP. I have tried this:
$.post('http://127.0.0.1/tum_old/testi.php', $('form#login_form').serialize(), function(data) {
console.log(data);
});
After checking on the data being passed through $('form#login_form').serialize() by
var param = $('form#login_form').serialize();
console.log(param);
I get:
username=ihfufh&passwordinput=dfygfyf
The PHP script:
<?php
$username = $_POST['username'];
echo "$username";
?>
Gives me this error:
Undefined index: username

Serialise and send your data with something like this:
jQuery / AJAX
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
// give your form the method POST
type: $(this).attr('method'),
// give your action attribute the value yourphpfile.php
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
})
Then receive it in PHP like this:
<?php
// assign your post value
$inputvalues = $_POST;
$username = $inputvalues['username'];
?>

Related

how to use data sent with Ajax POST in PHP

I have a strange behaviour, I sent data to a PHP page using Post request, my problem is when I try to manipulate this data (echo for exemple) in PHP page I get nothing, but when I make condition on the value I sent the condition is ok.
My JS code
$.ajax({
type: "POST",
url: 'admin/page.php',
data: {
type: 'search',
date1:'2021/04/15',
date2:'2021/04/13'
},
success: function(data){
alert(data);
}
});
My PHP code
$uname = $_POST["type"];
$date1 = $_POST["date1"];
$date2 = $_POST["date2"];
if ($uname=='search') // condition OK
{
echo $date1;
echo $date2;
}

load a file using variable from client side

I need to load a file inside a container, but using an argument - to get some data from database firstly:
$('#story').load('test.php');
test.php
$st = $db->query("select * from users where id = " . $id);
... processing variables... load the finished content
Here I need $id from client side. Is it possible?
yes ..you could pass with url query
$('#story').load('test.php?id=1');
test.php
$id = isset($_REQUEST['id'])?$_REQUEST['id']):'';
$st = $db->query("select * from users where id = " . $id);
You can use ajax request and on success you load your file something like:
$.ajax({
type: 'POST',
url: "test.php", //make sure you put the right path there
data: {id: id},
dataType: "json",
success: function (resultData) {
$('#story').load('test.php');
}
})
Just make sure that your php function returns/echos the id you want.
That way you make a call to your php file and when it's successful you will load your file and you can put extra logic there if you want to return more data to use it of course.
resultData holds the output of your php function so it's up to you what info you want to be there.
You could use Ajax to post the ID to your php code.
$.ajax({
type: "POST",
url: "test.php",
data: { 'id': foo },
cache: false,
success: function(){
alert("Order Submitted");
}
});
php:
<?php
$id = $_POST['id'];

Sending AJAX post request to PHP

So here is my AJAX code using JQuery:
$('#button-upload').on('click', function(){
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
}
});
}
});
The request isn't registered in the network.
Secondly, I'm not sure how can I collect this data with PHP using $_POST.
You seem to be a php newbie. Here is a snippet of code you can use to retrive the ajax data.
Here is the link to the documentation about the global variable $_POST I suggest you to read it.
Another useful link about the predefined variables in php
JS code:
$('#button-upload').on('click', function(event){
event.preventDefault();
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
console.log(response);
}
});
}
});
PHP:
<?php
if(isset($_POST['distribution'])){
# I've added a sanitization filter, but you can omit it if you don't need to pass the data to a database.
$dist = filter_var($_POST['distribution'], FILTER_SANITIZE_STRING);
# put your logics here after you got the distribution $_POST variable value.
}
?>

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Jquery post both file and data with one ajax call

Hi I have a wordpress php class that receives my ajax and works good.
Now i have to upload a file in the same POST request i use to pass parameters to the PHP class ( i have a switch in the class that sends me to the proper function based on the parameters in the POST data ).
this is the code:
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <?php echo get_current_user_id(); ?>;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var data = {
'action': 'romme_call',
'whatever': 1234,
'userID': userID,
'function_call': 'upload_profile_photo',
**'form_data' : formData**
};
console.log(data);
jQuery.post(ajaxurl, data, function(response) {
console.log("done");
console.log(data);
});
this code will of course return a "Uncaught TypeError: Illegal invocation"
because it does not accept formData as parameter in data.
how can i handle this?
It returns Illegal invocation because jQuery is trying to parse the form data with $.param.
When submitting files with jQuery's ajax processing must be turned off
$('#imageUploadForm').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <? php echo get_current_user_id(); ?> ;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
formData.append('action', 'romme_call');
formData.append('whatever', '1234');
formData.append('userID', userID);
formData.append('function_call', 'upload_profile_photo');
$.ajax({
url : ajaxurl,
type : 'POST',
data : formData,
contentType: false,
processData: false
}).done(function(response) {
console.log("done");
console.log(data);
});
});

Categories

Resources