PHP not reciving data with AJAX's POST - javascript

I have to say I saw a dozens of topics similar to my problem, but most of them were typos or spelling.
My PHP file does not seem to receive any data from AJAX POST function (I'm getting Undefined Index). Here is my code:
var login = $("#log_l").val();
var pwd = $("#pwd_l").val();
alert(login);
alert(pwd);
$.ajax({
type: "POST",
url: 'app/menu/login.php',
data: {
login1: login,
pwd1: pwd,
},
cache: false,
success: function (data) {
if (data == 'fail') {
alert('test2');
$('#failure_log').show();
}
else {
document.location = " {$conf->action_root}postlogin";
}
}
});
return false;
And the login.php:
$login = $_POST['login1'];
$haslo = $_POST['pwd1'];
...
I tried with both:
login1:login,
pwd1:pwd,
And:
'login1':login,
'pwd1':pwd,
But in both ways I receive "Undefined index" error in .php file on 'login1' and 'pwd1' variables.
I checked that ajax 'reaches' file and it even receives the echos from .php file, but the variables are not sent/received.
Do you have any ideas what might be wrong?

You need to use file_get_contents to capture ajax calls or you need to define. Check this
How to get JSON data in php ?
Or
you need to set the ajax call as form_encoded_url
contentType: "application/x-www-form-urlencoded",
refer this link
Submitting HTML form using Jquery AJAX

Related

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

AJAX not passing variables on Server (Any AJAX)

So i have a lot of AJAX functions, they worked all well all good in server as well as in localhost until recently i made some changes in the js files and some ajax-php files as well. Nevertheless...they are still working absolutely fine on localhost...but not on server
During debugging, i found out...that the ajax has no problem getting the file....i mean there is no 404 error....however....it isn't passing the variable...
JS FILE
function nextImg(Imgkey){
changeImgViewerN = 0;
var currUrl = window.location.href;
var baseUrl = currUrl.split(/[\\/]/).pop();
var splitUrl = baseUrl.split('&');
var folderKey = splitUrl.pop();
var groupKey = splitUrl[0];
if(groupKey == undefined) groupKey = folderKey;
$.ajax({
url:'/9712d9c1_2be4d8c9318e69_1b526557b8_sF',
type: 'POST',
data:{searchNextImg:Imgkey, groupKey:groupKey, folderKey:folderKey},
success: function(response){
$('#in_folders').prepend(response);
}
})
}
PHP FILE
echo "Here";
if(isset($_POST['searchNextImg']) || isset($_POST['searchPrevImg'])) && isset($_POST['groupKey']) && isset($_POST['folderKey'])){
echo "Reading";
}
However on the server, it just executes
echo "Here";
but not
echo "Reading";
My .htaccess file says:
RewriteRule ^9712d9c1_2be4d8c9318e69_1b526557b8_sF$ http://www.example.com/ajaxinc/searchFile.php
There are such other AJAX functions but they are not passing variables to the server, however on localhost, they are working perfectly. All of them.
replace:
url:'/9712d9c1_2be4d8c9318e69_1b526557b8_sF',
with
url:'9712d9c1_2be4d8c9318e69_1b526557b8_sF',
You did not pass this variable searchPrevImg in your ajax call, but that is in or condition so does not matter.
suggestion:
use the below way to create data objects:
data:{'searchNextImg':Imgkey, 'groupKey':groupKey, 'folderKey':folderKey},
You have a js syntax error:
Replace: type: 'POST'; by type: 'POST',
The rest of the code looks well.
try to make your ajax call like below.
$.ajax({
url:'/9712d9c1_2be4d8c9318e69_1b526557b8_sF',
type: 'POST',
data:{searchNextImg:Imgkey, groupKey:groupKey, folderKey:folderKey},
async:false,
success: function(response){
$('#in_folders').prepend(response);
}
})

Passing array with Ajax to PHP script results in empty post

I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"

Not able to submit file via AJAX

Following is my ajax call in which I am sending my form data to a PHP page and diplaying the messages accordingly. The issue I am facing is with ajax seralize() post my file is not getting posted and send.php gives error in response Notice: Undefined index: file . Kindly let me know what is an appropriate way to post form data with ajax enctype="multipart/form-data" so files can be send as a post too via ajax.
var post_data = $( "#form" ).serialize();
$.ajax({
type: "POST",
url: "send.php",
async: false,
data: post_data,
success: function(html){
if (html.indexOf("filerror") != -1)
{
alert('error');
}
else if(html.indexOf("true") != -1)
{
alert('true');
}
else if (html.indexOf("false") != -1)
{
alert('false');
}
},
beforeSend:function()
{
}
});
$( "#form" ).serialize() just get form fields values, not its content(for file). If you want to get file content works with files control field:
var $fileInput = $('input[type="file"]');
var files = $fileInput.get(0).files;
You must work with variable files with FileReader constructor. But better for file uploading by AJAXuse plugins, for example this.

Categories

Resources