Ajax data element not picking up - javascript

I have an error here I'm sure:
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
var remember = $("#remember").val();
console.log(username, password, login, remember); //this shows up fine
$.ajax({
url: 'php/login.php',
//here i think
data: {username:username,password:password,login:login,remember:remember},
type: 'POST',
dataType: 'application/json',
success: function(data)
{ ....
Because when I get to my login.php I get undefined index on lines:
<?php
$username = $_POST['username']; //here
$password = $_POST['password']; //here
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember']; and here
.....
I return in login.php further down:
echo json_encode("true"); //or "false"
in the response pane in firebug:
<br />
<b>Notice</b>: Undefined index: username in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>6</b><br />
123123123<br />
<b>Notice</b>: Undefined index: login in <b>C:\xampp\htdocs\www\php\login.php</b> on line <b>8</b><br />

Try using php://input
This allows you to read raw data. Since your are using application/json you must be getting data in raw

Try using:
$.ajax({
url: 'php/login.php',
data: JSON.stringify({'username':'username','password':'password','login':'login','remember':'remember'}),
type: 'POST',
dataType: 'json',
contentType: "application/json",
success: function(data) {.....

i am also getting same problem using this method $.ajax and passing everything by : separated but how i reslove this issue using the following snippet.
<script type="text/javascript">
$(function(){
$('#submit').on('click',function(){
var formdata ={
username:$('#username').val(),
password:$('#password').val(),
message:$('#message').val(),
submit:$('#submit').val()
};
var url=$('form').attr('action');
console.log(url);
console.log(formdata);
var posting = $.post(url,formdata);
posting.success(function(data){
$('.success').empty().append(data.username);
});
});
});
</script>
in this snippet .success is a vriable where it spit out the username after success. following is the sample PHP code.
<?php
foreach($_POST as $key => $val)
{
$result[$key] = $val;
}
header('Content-Type: application/json');
echo json_encode($result);
?>
try this method and let me know it does resolve your issue or not ??
Regards

Try this way. I ran into the same issue before and this is the only way I can get JQuery to properly send the key/value pairs when you're using your own string as the key.
var username = $("#username").val();
var password = $("#password").val();
var login = $("#login").val();
var remember = $("#remember").val();
$.ajax({
url: 'php/login.php',
data: "username="username + "&password="+password + "&login="+login + "&remember="+remember,
type: 'POST',
dataType: 'json',
success: function(data)
{ ....

Related

$.ajax not uploading files using data: object array method

Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

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

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

Passing javascript variables to another php page

I have a select list where in using javascript i get the selected values i want this selected values to pass through php file init.php so that i can use those variables in mysql query.
my javascript code is as follows:
$(document).ready(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
});
$('select').change(function(){
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
I have used ajax to send variables to init.php. my ajax code below is not working,can anyone tell whats the issue in this code:
$.ajax({
url: 'init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
and in init.php i have written :
<?php
$var1 = $_POST['y'];
$var2 = $_POST['x'];
$result = "Select amount from ". _DB_PREFIX_ ."demo_detail where product = '". $var1 ."' and city = '" . $var2 . "' ";
//echo json_encode($result);
Can you alter the url line to include the / to make sure that you're referring init.php relative to the root of your directory?
So it should look like this:
$.ajax({
url: '/init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
I don't know enough to say for sure but there's a chance that AJAX is making a POST request to the wrong URL.
Have you tried to pass absolute as well as relative path in url. What I mean is
have you tried using:
url:'localhost:xxxx/myapp/init.php'
or
url:'/init.php'
If you're passing variables into the data parameter in Ajax, they don't have to be in quotes.
$.ajax({
url: 'init.php',
type: 'POST',
data: { x: cit, y: pro },
success: function(data) {
console.log(data);
}
});
Use Query String. HTML5's Session Storage can also help you.
Try to replace your script code with following and see if it makes a difference
$(document).ready(function(){
$('select').change(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
$.ajax({
type: 'POST',
url: 'init.php',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(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