Background
I have a web application which displays "simple" information about an account, i.e. Name and account Number.... I have a button on the side to display "detailed" information... i.e Name, Acct# and Phone#.
The system needs to pull the information dynamically upon clicking this button, and will populate into specified div's... What am I doing wrong in this case, because I am constantly receiving the alert with "Error Loading Information". Edit: -Changed error alert to alert(textStatus) - Now all I have is "error" in the alert box....
JS/Ajax
$('.view_information').click(function(e) {
//On Clicking the function, dynamically load the data for the viewing
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
/* Doesn't Work....*/
$('.view_id').html(data.id);
$('.view_name').html(data.name);
$('.view_account').html(data.account);
$('.view_phone').html(data.phone);
/*Also Doesn't work...
$('.view_id').html(data.message['id']);
$('.view_name').html(data.message['name']);
$('.view_account').html(data.message['account']);
$('.view_phone').html(data.message['phone']);*/
},
error: function(jqXHR, textStatus, errorThrown){
// alert('Error Loading Information');
alert(textStatus);
}
});
JSON
<?php
include_once('customer.class.php');
$customer = new Customer();
$query = "SELECT * FROM table WHERE id=$id LIMIT 1"; //expecting one row
try {
$result = $customer->runQuery($query); //class function with fetchAll
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
$message = array(
'id' => $id,
'name' => $result[0]['agency_name'],
'account' => $result[0]['account_number'],
'phone' => $result[0]['phone']
);
}
print json_encode($message);
?>
It appears I was able to fix the syntax to get it operable.... Had to do with passing the array into json to execute.
I changed the JS/AJAX to:
/* Old Variable Definitions
//var dataObj = {};
//dataObj["id"] = $(this).data('id');
//dataObject["column"] = $(this).data('column');
//dataObj["action"] = "get"; // "get" or "set"*/
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
//data: dataObj, // OLD array
data: {id : data_id, action: data_action, column: column_toact_on},
dataType: 'json',
success: function(data){
alert("Wooptee Doo Basil!");}
Related
I am trying to pass some basic data using JavaScript and PHP.
The PHP is not receiving any data.
I have the following JavaScript code:
var formData = new FormData();
formData.append("action", "save-game");
formData.append("title", title);
formData.append("players", players);
formData.append("noTables", noTables);
formData.append("maxPPT", maxPPT);
formData.append("rounds", roundChart);
$.ajax({
url: "/static/apps/games.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
if (response.success) {
alert("Saved Game Setup");
} else {
alert("Failed to save game setup, "+response.reason);
console.log(response.reason);
}
}
})
And I have stripped the PHP down to the bare minimum but it is still not receiving the data
header("Content-Type: application/json");
$action = $_POST["action"];
echo json_encode(array(
'success' => false,
'reason' => $action,
));
The $action variable in PHP is returning null
try to build data like here
var buildData = function( _action, _title, _players, _noTables, _maxPPT, _rounds){
var data = {};
data.action = _action;
data.title = _title;
data.players = _players;
data.noTables = _noTables;
data.maxPPT = _maxPPT;
data.rounds = _rounds;
return JSON.stringify(data);
}
var _json = buildData("save-game", title, players, noTables, maxPPT, roundChart);
I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
I am sending data via jQuery's .ajax method to my PHP file. Both files are on the same domain. The file making the post looks like this..
$('#pdf').click(function() {
var proj_name = $('#proj_name').text();
var date = $('#date').text();
var req_comp_date = $('#req_comp_date').text();
var status = $('#status').text();
var secondUserID = $('#secondUserID').text();
var postData = {
"proj_name" : proj_name,
"date" : date,
"req_comp_date" : req_comp_date,
"status" : status,
"secondUserID" : secondUserID,
};
console.log(postData);
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
}
});
});
And the PHP file getting the post data is...
//request parameters
$proj_name = $_POST['proj_name'];
$date = $_POST['date'];
$req_comp_date = $_POST['req_comp_date'];
$status = $_POST['status'];
$secondUserId = $_POST['secondUserId'];
echo 'postData: ' . var_dump($_POST);
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
In my firebug console, I can see that the parameters posted with .ajax, but I cannot get the post via PHP. Can anyone help me out please? Thank you.
Add the error callback to your to your $.ajax call to debug if the request is failing.
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
},
// Alert status code and error if fail
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Update
Change this:
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
To this:
if ($_POST)){
// Make a array with the values
$vals = array(
'proj_name' => $proj_name,
'date' => $date,
'req_comp_date' => $req_comp_date,
'status' => $status,
'secondUserId' => $secondUserid
);
// Now we want to JSON encode these values to send them to $.ajax success.
echo json_encode($vals);
exit; // to make sure you arn't getting nothing else
} else {
// so you can access the error message in jQuery
echo json_encode(array('errror' => TRUE, 'message' => 'a problem occured'));
exit;
}
Now in your jQuery .success callback:
success: function(data){ // Our returned data from PHP is stored in "data" as a JSON Object
alert(data.req_comp_date); // access your returned vars like this.
// data.date; // is your posted date.. etc
alert(data.proj_name + ' ' + data.status);
window.open("test.php");
// You can also get your error message like so..
if(data.error) // if its true, we have a error, so display it.
alert('ERROR: ' + data.message);
},
You dont really have to do this next bit (jquery does a good job of determining the data type returned), but its nice to have it in the code to understand what is being returned.
$.ajax({ ...
type: "POST",
url: "test.php",
data: postData,
dataType: "json" // <-- Add this to tell jquery, we are being returned a JSON object.
.... });
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.