Not able to submit file via AJAX - javascript

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.

Related

PHP not reciving data with AJAX's POST

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

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

Having Issue On Uploading Loaded Image by jQuery Ajax on Server

I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.
Here is the code I have for Ajax part:
<script>
$(function () {
$("#uploadimage").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
var imgloader = $.ajax({
type: "POST",
url: "imgLoader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formData);
}
});
imgloader.fail(function () {
console.log('Error');
});
imgloader.done(function (data) {
$('#res').text(data);
});
});
});
</script>
and I have this PHP on imgLoader.php
<?php
if (isset($_FILES["file"]["type"])) {
$file = $_FILES['file']['tmp_name'];
$newloc = "newupload/" . $_FILES['file']['name'];
move_uploaded_file($file, $newloc);
} else {
echo 'There is Something Wrong?!';
}
?>
but I am getting the
There is Something Wrong?!
on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)
Thanks
AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.
http://www.malsup.com/jquery/form/
This problem is already discussed in following link:
PHP and Ajax file upload - Can't get the tmp_name with $_FILES

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Getting JSON response from the server but can't display as HTML with Jquery

I'm building a mobile app and i build a PHP API that renders data from a mysql db and encode it as JSON
i call this api with Jquery ajax to get to display the records from the json output as JSONP and render it in my document in the success function.
so far i get the JSON correctly when i do the request via $.ajax and i can see the data in the Response in my firebug but in the other side the ajax function fires the ERROR not the Success.
i have a demo code in here :jsfidle
this is my $.ajax Call:
$(document).on("pageinit","#myPage", function() {
$("#autocomplete").on("listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
var dataString = 'keyword='+value;
if (value.length > 2 ) {
$.mobile.loading("show");
$.ajax({
type: "GET",
url: "http://example.com/search.php",
dataType: "jsonp",
jsonpCallback: 'jsonpCallback',
cache:true,
data: dataString,
success: function(data) {
$.mobile.loading("hide");
alert(data);
}
})
}
});
});
if you check the net panel you 'll find it successful and there is data coming.
Kindly Advise.
Thanks A lot
Your response is not including the callback jsonpCallback() in the response, the response I'm seeing is simply
({"name": ... })

Categories

Resources