How to handle the PHP response from jQuery AJAX? - php

Currently, I cant access the return data from my jquery ajax. Actually, I dont even know if I am sending any data at all? I just need to send data from a form with JSON to php, and get the response as an array.
Thanks for the help.
HTML/JS/jQuery
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function () {
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var postData = {
username: uname,
password: pword
};
alert(uname);
$.ajax({
url: "test.php",
type: "GET",
data: postData,
dataType: 'json',
contentType: 'json',
cache: false,
success: function (data) {
alert(data);
}
});
});
});
</script>
</head>
<body>
<form action="">
<input type='text' id="username" name="username" placeholder="Username" />
<br />
<input type='password' id="password" name="password" placeholder="password" />
<br />
<input type="submit" id="submit" value="Login" />
</form>
</body>
PHP
echo json_encode(array(
'username' => $_GET['username'],
'password' => $_GET['password']
));

You are creating a handler for the submit event but it seems that you forgot to return false in order to stop the basic submit process.
A form with an empty action will POST data in the same page (your initial PHP page), so the AJAX call back is sent but just after, you are posting again with basic way.
Add a return false at the end of the function (just after your AJAX call) and then your form will not be submitted, the AJAX will be sent and you will see the response.
If you are using Firefox, install Firebug and look at the Network tab to see your request sent by the Ajax call and check your JSON response.
Good luck.

Related

Jquery Ajax success data from PHP echo not working

I'm trying to get the data value on success from the php. However when I alert(data) in the success, it returns the page html.
HTML:
<input type="text" class="form-control" name="project_name" id="projectName" required>
Jquery AJAX:
$('#projectName').on('blur', function(){
var projectName = $(this).val();
$.ajax({
url: 'page.php',
type: 'POST',
dataType: 'text',
data: {
'projectChecked': 1,
'project_name': projectName,
},
success: function(data){
if (data == 'taken') {
$('#projectName').addClass('border-red');
}
}
});
});
PHP:
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
Alert Message:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="/favicon.png"/>
<title>Page Title</title>
<meta name="description" content="Meta Description">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlTw8HfCJo=" crossorigin="anonymous"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-157194354-1"></script>
You should use exit in php code to get return data use following code
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
can you check the html code when you do alert(data); and post here?
alternatively, you might want to check the developer tools of browser and validate network tab to monitor parameters and response of ajax request.
It is possible that you are getting http 400/500 response and you are actually seeing default error page (which is of course not a JSON response) in the data variable (this depends on the way server is configured)

Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value?

I have the following form which has
a text field
date field
a file browser.
I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.
In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.
I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below
AJAX
<script>
$("#submit").click(function() {
var prjId = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
$.ajax({
type: 'POST',
url: "process.php",
data: {prjId: prjId,updatedDate: updatedDate},
success: function(response) {('#resulting').html(response);}
});
});
</script>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/png" href="images/version-control.png">
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<body>
<div class="container" id="contactform">
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Project ID</label>
<div class="col-sm-7"><?php if(isset($_POST['prjId'])){echo '
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Updated Date</label>
<div class="col-sm-7"><?php if(isset($_POST['udatedDate'])){echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>
</div>
</div>
<fieldset class="form-group ">
<label class="btn btn-default tempPerm" id="techLabelText">
<input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />
</label>
</fieldset>
</form>
<div class="cover">
<div id="result"></div>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
</div>
</body>
</html>
PHP
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($prjId)){
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
The code below automatically includes all fields from the form without manually adding them using the append function.
Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.
You can try tinker with these working template.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var FD = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url: "process.php",
processData: false,
contentType: false,
data: FD,
success: function(response) {
$('#resulting').html(response);
}
});
});
});
</script>
process.php
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($_POST['prjId'])){
$target_dir = "uploads/";
$target_file = $target_dir.basename($_FILES["file"]["name"]);
$save_file = basename($target_file); // this holds the filename to save.
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));
// Modify this query string to add the file uploaded as well.
// Change the query string to use prepared statements for failure safe and for security reasons.
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
^ Added a simple file upload handler.
You can use formdata to send your files along with your request like this:
<script >
$("#submit").click(function() {
var formData = new FormData();
var prjid = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
formData.append( 'file', input.files[0]);
formData.append('prjId', prjid);
formData.append('updatedDate', updatedDate);
$.ajax({
type: 'POST',
url: "process.php",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(response) {
$('#resulting').html(response);
}
});
});
</script>
If you submit form using ajax it will not pass $_FILES
you have to create object for that using FormData
note : please add enctype="multipart/form-data in form tag
<form id="upload" enctype="multipart/form-data">
please refer : jQuery AJAX file upload PHP
Thanks

empty array when post data ajax phonegap

I am trying use ajax in phonegap. When I post data - php always take null array. And it is not wrong code.
I wonder if something with url is wrong. Is it possible? Or maybe I should add some more access? I have really no idea what i do incorrectly.
incorrectly..
Here is my code:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<div id="result"></div>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var values = $(this).serialize();
$.ajax({
url: "http://localhost/inne/phonegap_test/agregar.php",
type: "post",
data: values ,
success: function (response) {
console.log("okey");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
</script>
</body>
</html>
php:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
var_dump($_POST);
It is because script sends request immediately page is loaded.
You should use this code:
$("#foo").submit(function(e){
var values = $(this).serialize();
$.ajax({
url: "http://localhost/inne/phonegap_test/agregar.php",
type: "post",
data: values ,
success: function (response) {
console.log("okey");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
e.preventDefault();
return false;
});

Not getting return data from PHP script in JQuery

I'm learning how to integrate JQuery, AJAX and PHP together.
My problem is that my success function isn't getting any value from the parameter and just getting a '0'. I'm not really sure what I'm doing wrong either, but I have just been following this tutorial JQuery & PHP Tutorial and just copied how he got the value from the PHP code using echoes and a parameter variable r.
I have tried searching for the solution, but I'm not sure if any of the results are relevant to what I am doing. I tried following some of their advice but none seems to work (the promise thing for jQuery)
I hope someone can enlighten me what I am doing wrong as I am eager to learn more PHP and jQuery.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input = $("#input").val();
var url = 'input=' + input;
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
$("#output").text(function(r) {
return r;
});
}
});
e.preventDefault();
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form action="process.php" method="post">
Inputs:<br />
<textarea rows="15" cols="60" id="input" name="input">Some text...
</textarea><br /><br />
Start:
<input type="text" id="start" name="start" />
End:
<input type="text" id="end" name="end" /><br />
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<p id="output">Output: Some Random Text</p>
</body>
</html>
PHP:
require 'parser.php';
$parser = new Parser();
#header('index.php');
$hash = $parser->parse($_POST['input']);
$keys = array_keys($hash);
foreach($keys as $key) {
echo "$key ->";
$dests = $hash[$key];
foreach($dests as $dest) {
echo " $dest";
}
echo "<br />";
}
?>
<script>
$(function () {
jQuery("form").submit(function(e) {
var input1 = $("#input").val();
var url = {'input' : input1}; // a little change to the data parameter
$.ajax({
type: "POST",
url: "process.php",
data: url,
success: function(r) {
// $("#output").text(r); //<--- changed to this
$("#output").html(r); // this is better as you output html
}
});
e.preventDefault();
});
});
</script>
for jquery text(), use the return value from the server directly. If you are outputting html use jquery html() instead

jquery-ajax: pass values from a textfield to a php variable (same a file)

jquery-ajax: pass values from a textfield to php file and show the value
i made a variation of the link above this time using only one file and no div tag.
test.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function(result){
window.location.reload(true);
}
});
window.location.reload(true);
});
});
</script>
</head>
<body>
<input type="text" id="inputtext">
<input type="button" id="submit" value="send">
<?PHP
if(isset($_POST['dataString'])){
$searchquery = trim($_POST['dataString']);
print "Hello " . $searchquery;
}
?>
</body>
</html>
value from dataString won't show. why?
Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it.
Try this
In test.php:
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "anothepage.php",
data: dataString,
success: function(result){
$('#result').html(result).
}
});
return false; //so the browser doesn't actually reload the page
});
And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css.
<form method="POST" action="">
<input type="text" id="inputtext" value="" name="inputtext">
<input type="submit" id="submit" value="send" name="submit">
</form>
<div id="result"> <!-- result from ajax call will be written here --> </div>
In anotherpage.php:
if(isset($_POST['inputtext'])){
$searchquery = trim($_POST['inputtext']);
echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we?
}
When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results.
You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input.
If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code.
<?php
if( isset($_POST['dataString']))
{
echo 'Hello ' . trim( $_POST['dataString']);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing jQuery AJAX</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function( data){
alert( data);
}
});
});
});
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" id="inputtext" />
<input type="button" id="submit" value="send" />
</form>
</body>
</html>

Categories