Unable to send JSON via AJAX - javascript

I made a function which counts how much time I spent on some page and where I came from. I collect all the data and save it into a JSON but when I try to send that JSON via ajax on the success it alerts me with an empty alert box, which means that nothing is being sent. I tried to add async to false because I use the onbeforeunload function but that doesn't work. I tried numberless combinations with AJAX setting but nothing is working.
HTML / JS
(function(){
var time,timeSite,endTime,seconds,testObject,retrievedObject,text;
window.onload=function(){
time= new Date();
}
window.onbeforeunload=function(){
endTime = new Date();
timeSite= time.getTime()-endTime.getTime();
seconds =Math.abs(timeSite/1000);
window.localStorage['seconds']=seconds;
text = 'Visitor accessed site directly.';
if(document.referrer == ''){
var link = text;
} else{
var link = document.referrer;
}
var url = window.location.href;
var main = {
'From': link,
'Current was' : url,
'Time Spent': seconds
}
$.ajax({
type: "POST",
data: {'data': main},
url: "http://localhost:8080/projectFour/test.php", //i use this page only to check if i receive data
contentType:'application/json',
success: function(data) {
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
}
})();
Test.php
<?php
if(isset($_POST['main'])) {
$obj = json_decode($_POST['main']);
//some php operation
echo $obj;
}
?>

Your test.php is looking for a POST variable called main, but you're sending one called data.
You can change the data part of the ajax call from:
data: {'data': main}
to
data: {'main': main}
and that should cause it to post the variable with main as the variable name.
Secondly, when you return the data, it would be better to return it as JSON again, otherwise it might mangle the result a bit.
Replace
echo $obj;
with
echo json_encode($obj);
And in the ajax replace
alert(data);
with
alert(JSON.stringify(data));
That will give you a view of the returned data structure as a string.
You should also consider returning something from PHP when the if statement is false, whether that be an error code, or some other response. Sending no response in this case isn't very helpful to the client side, and has hindered your debugging.

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.

AJAX not coming up a success even though its updating the database

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;

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).

Ajax Error Potentially Due to Incorrect Data Object Being Passed

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.

send multidimensional array to php using ajax as json and receive html text to show in a div

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);
}
});

Categories

Resources