I'm using iFrame class JSP page with Date picker field on it. On selecting a date from the picker, I'm sending the date to the Struts Action using jQuery AJAX call like below:
$( "#datepickerStart" ).datepicker({
onSelect: function(dateText, instance) {//date select from picker to trigger
$.ajax({
type: "Post",// post method
url: 'checkAvailability.do?operation=getlist&datepickerStart='+ ("#datepickerStart").val(), // passing URL with date value to STRUTS Action
data: "date="+date,
//dataType: "application/json",
success: function(data) {
alert(data); //getting with the complete HTML page
}
});
}
});
And from DB I'm fetching the results in LIST and converting to JSON object like below:
Gson gson = new Gson();// Using google GSON to convert to JSON
String json = new Gson().toJson(lRList);
response.setContentType("application/json");// setting content type
response.setCharacterEncoding("UTF-8"); //setting character encoder
response.getWriter().write(json);// writing to response the JSON object
System.out.println("JSON Object::"+json);
And in standard output gives me the result like this:
JSON Object::[{"bookDate":"2014-07-11","fromTime":"2:00PM","totime":"3:30PM","userID":"XXX","isSuccess":false},
{"bookDate":"2014-07-11","fromTime":"10:30AM","totime":"11:00AM","userID":"XXX","isSuccess":false}]
But the alert in Ajax success gives the complete HTML page :(. I need this data and want to populate the values in the same JSP by showing in a div table. So can anyone help me on this to resolve it and let me know where I'm doing the mistake...
i think you should use get instead of post in the ajax call
$( "#datepickerStart" ).datepicker({
onSelect: function(dateText, instance) {//date select from picker to trigger
$.ajax({
type: "get",
url: 'checkAvailability.do?operation=getlist&datepickerStart='+ ("#datepickerStart").val(), // passing URL with date value to STRUTS Action
data: "date="+date,
//dataType: "application/json",
success: function(data) {
alert(data); //getting with the complete HTML page
}
});
}
});
setup AJAX error to get the error like:
$.ajaxSetup({
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText);
console.log('Error msg: '+msg);
}
});
and then set datatype as json in your AJAX call as your getting response in Json format like:
$("#datepickerStart").datepicker({
onSelect: function(dateText, instance) {
$.ajax({
type: "post",
url: 'checkAvailability.do?operation=getlist&datepickerStart='+$("#datepickerStart").val(),
data: "date="+date,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
}
});
}
});
also you were forgot to put $ starting of ("#datepickerStart").val()
for further reference checkout my app
Related
I'm using Django and Bootstrap to create a simple website.
In my .html file, I'm using Bootstrap to display a datepicker.
<div id="datepicker" ></div>
Also in the .html, I have some quick and dirty javascript code that gets updated when my datepicker gets clicked on.
<script>
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
});
$(document).ready(setup);
</script>
I want to pass back this new date to my Django page. Basically I want to refresh the page with data pertaining to this new date, and my Django code knows how to handle the new date.
How should I do that? Should I redirect back to my current page, but add something to the URL so that Django's regex will pick it up? Or should I make it an Http GET with the new date?
<script>
function pass_this_to_backend(date){
$.ajax({
type: "POST",
url: "/get_date/",
data: { 'date':date },
dataType: "json",
success: function(response) { alert(response); },
error: function( rrror) { alert(error); }
});
}
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
pass_this_to_backend(date);
});
$(document).ready(setup);
</script>
You can use Ajax to get data from server without page refresh:
jQuery.ajax({
type: 'POST',
url: 'web/path/to/php/file.php',
data: {
post_date: $('#datepicker').val() //this is the data to post to server
},
success: function(res) {
//code executed after server response. res - server response
$('#datepicker').append(res); //modifying your html
}
});
And in file.php for example:
echo $_POST['post_date']; //accessing your date on server side and return it
If you do need to refresh the page, you can send your data in url:
$('#datepicker').on("changeDate", function() {
var val = $('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
val = encodeURIComponent(val); //encode data for url passing
window.location.href = '?date = ' + val; //goto url with appended parameter
});
To get data you use:
$date = urldecode($_GET['date']);
I have the following jquery function which submits data to the database :
$('#book_client_form').submit(function (event) {
dataString = $("#book_client_form").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>operations/book_client",
data: dataString,
success: function (data) {
console.log(data);
$('.job_card_id').val(data[0].id);
$(".info_box_reload").show('slow');
setInterval(function () {
$(".add_new_client_div").hide('slow');
$(".clients_table_div").show('slow');
}, 3000);
}
});
event.preventDefault();
return false;
});
Once the data is supposed to returned the last insert id in json format which gives me the following output :
[{"id":"17"}]
But when I try to pass it to a text field or alert it , I get an undefined output or passes empty. Please advise on how can I pass it to the text input? I'm using datatype : datastring.
did you try parsing the JSON data?
data = JSON.parse(data);
console.log(data[0].id); // you can see the id in the dev console
$('.job_card_id').val(data[0].id);
or you can set dataType : 'jsonp' to get a JavaScript object as response
use dataType, its case sensitive.
My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;
Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.
First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});