I have a problem because one parameter (out of 2) is always missing on the server side (when I send them via AJAX to it).
My JS code looks like:
function import_websql(user_id) {
var db = openDatabase("database", "1.0", "table", 2*1024*1024);
var favourite_ids = "";
if (window.openDatabase){
db.transaction(
function(t){ // This is the callback with "t" as the transaction object
t.executeSql('SELECT * FROM favourites', [], function (t, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
favourite_ids += results.rows.item(i).id + "t";
}
});
}, onError, onReadyTransaction(user_id,favourite_ids)
);
} else{
alert("Your smartphone is too weird!");
};
}
function onReadyTransaction(user_id,favourite_ids) {
alert(favourite_ids);
send_websql(user_id,favourite_ids)
}
function onError() {
alert("error");
}
function send_websql(user_id,favourite_ids){
$.ajax({
url: 'fct.import_websql.php',
type: 'GET',
data: {user_id: user_id, favourite_ids: favourite_ids},
dataType: 'json',
beforeSend: function(){
},
success: function(data)
{
if(data) {
alert(favourite_ids + "Worked!" + data);
}
else {
console.log("Error: " + data);
}
},
complete: function(data){
},
error: function(xhr,textStatus,err)
{
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
}
And my PHP looks like:
<?php
include_once('database_connect.php');
include_once('clean.php');
$user_id = clean($_GET['user_id']);
$favourite_ids = clean($_GET['favourite_ids']);
$favourite_ids_arr = explode('t', $favourite_ids);
array_pop($favourite_ids_arr);
foreach ($favourite_ids_arr as &$favourite_id) {
$sql = "INSERT INTO map_favourite_user_bookmark (map_favourite_user_bookmark_favourite_id, map_favourite_user_bookmark_user_id) VALUES ($favourite_id, $user_id)";
$result = mysql_query($sql) or die(mysql_error());
$sql = "UPDATE user_info SET user_websql_imported = 1 WHERE user_id = $user_id)";
$result = mysql_query($sql) or die(mysql_error());
}
$response = "ok" . $favourite_ids;
echo json_encode($response);
?>
'Funny' thing is that on the JS side before I send the data EVERYTHING exists (and would be alerted), but on the PHP side the favourite_ids are completely missing (can't echo them, can't process them, and they are not given back... like they don't exist).
What I'm doing wrong?
Your problem is that the database API is asynchronous, so you will execute your ajax call while the database transaction has not yet finished.
One way to solve it, is to put the ajax call in the callback of the query function.
Related
I'm calling an AJAX using a $.when to wait till that ajax completes and return to process the next ajax inside.
This is where $.when calling happens:
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1[0])); //this is in the attached screen shot
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
Above code is calling below ajax method function:
function getCreditorID(){
id = "";
var creditorcodex = document.getElementById('creditorcode').value;
// console.log("getCreditorID input: " + creditorcodex);
var urlx = "functions/getCreditorID.php";
return $.ajax({
type: 'POST',
url: urlx,
data: {
creditorcode: creditorcodex,
},
success: function(data) {
console.log("Result : "+data); //this is in the attached screen
}
});
}
Above function calling getCreditorID.php to get data:
getCreditorID.php:
<?php
include '../config/dbConn.php';
$creditorcode = $_POST["creditorcode"];
// $creditorcode = $_GET["creditorcode"];
$result="";
$sql = "SELECT intCustomerID FROM lms.tblcustomers WHERE varCustomerName='".$creditorcode."';";
mysql_select_db('$dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
$result=-999;
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$result=$row["intCustomerID"];
}
echo $result;
mysql_close($conn);
?>
Problem is:
If return from getCreditorID.php is '44' then console.log("Result : "+data); inside getCreditorID() function will output in console as 'Result : 44' and this is working fine. But the same function is getting returned in loadAllData() function and using the value returned for next ajax. Here if we print the return value using console.log("cx id is : " + parseFloat(a1[0])); output is '4' which should be '44'. Which means it's only giving the first character as output and ignoring the rest.
Screenshot of running console:
Please find a way out.
In your function loadAllData(), use a1 instead of a1[0] and update your code accordingly
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1)); // did correction here
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}
I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!
try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way
I'm trying to save a post to my database which it does, however the ajax error block is executing. It states ok in its response though so I looked around on some of the other questions and it seemed like I wasn't returning a Json object so I tried a few things:
Creating a NameValule variable and adding ("Success","true") and converting it to Json by Json.Encode(NameValue);
Returning a string in the format of Json:"{ \"Result\":[{\"Success\":\"true\"}]}";
Changing the dataType to "text json" "text/json"
The error block still executes for some reason, any ideas?
//Save it all in an object to be passed in ajax
var Post = {
Id: postID,
Title: postTitle.val(),
Author: postAuthor,
Date: postDate,
Content: postContent.val(),
metaDescription: metaDescription.val(),
metaKeywords: metaKeywords.val(),
metaID: metaId.text(),
Page: $(document).attr('title')
};
//save to database
$.ajax({
url: url,
type: 'POST',
dataType: "text json",
data: { data: JSON.stringify(Post) },
success: function (result) {
console.log("result: " + result);
if (result == "Success") {
// postContent.append("<br/><p>Edit Successful!</p>");
alert('Edit successfull');
//window.location.replace(window.location.href);
}
else {
postContent.replaceWith("<div>" + result + "</div>");
}
},
error: function (xhr, status) {
console.log('ajax error = ' + xhr.statusText);
}
});
Here is the response page:
#using WebMatrix.Data;
#functions{
public string EditPost()
{
var db = Database.Open("StarterSite");
var post = Request.Unvalidated["data"];
var result = Json.Decode(post);
var error = new System.Collections.Specialized.NameValueCollection();
/* Id: postID,
Title: postTitle,
Author: postAuthor,
Date: postDate,
Content: afterEdit,
Page: $(document).attr('title')
*/
if(string.IsNullOrEmpty(result["Id"]))
{
error.Add("Error", "Id empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Author"]))
{
error.Add("Error", "Author empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Content"]))
{
error.Add("Error", "Content empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Date"]))
{
error.Add("Error", "Date empty");
return Json.Encode(error);
}
//Page and Title only ones that can be empty
var cmd = "UPDATE Posts SET ID='" + result["Id"]
+ "',Author='" + result["Author"]
+ "',Content='" + result["Content"]
+ "',Date='" + result["Date"]
+ "',Title='" + result["Title"]
+ "',Page='" + result["Page"]
+ "' WHERE ID='" + result["Id"] + "';";
try { db.Execute(cmd); }
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaDescription"]))
{
error.Add("Error", "metaDescription empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaKeywords"]))
{
error.Add("Error", "metaKeywords empty");
return Json.Encode(error);
}
//Post was edited successfully add/update meta info
int parseResult = 0;
Int32.TryParse(result["metaID"], out parseResult);
if (parseResult > 0)//metaID is supplied
{
cmd = "UPDATE MetaInfo SET Description='" + result["metaDescription"]
+ "',Keywords='" + result["metaKeywords"]
+ "',postID='" + result["Id"]
+ "' WHERE ID='" + result["metaID"] + "';";
}
else //metaID is not supplied
{
cmd = "INSERT INTO MetaInfo (Description,Keywords,postID) VALUES('"
+ result["metaDescription"] + "','"
+ result["metaKeywords"] + "','"
+ result["Id"] + "');";
}
try
{
db.Execute(cmd);
}
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
//End Update meta info
error.Add("Success", "true");
return Json.Encode(error); //"{ \"Result\":[{\"Success\":\"true\"}]}";
}
}
#{
var result = EditPost();
}
#result
For anyone else that may have this same problem here was how I finally solved it: Just use Html.Raw(result) to send back only the json instead of extra stuff that gets added for some reason.
Can't be sure without knowing the requirements for the url. My guess would be that the data property is the reason you're off. I'm guess Post is an object defined elsewhere. When you send your request, the server will likely interpret the data field as an object not a string. Try to change {data: JSON.stringify(Post)} to just JSON.stringify(Post)
try with adding async: true, line after type: 'POST',
Problem is with your JSON response.
"{ \"Result\":[{\"Success\":\"true\"}]}";
There added slashes before double quotes(").
You can see the actual error thrown by jQuery using below updated error block:
error: function (xhr, status, errorThrown ) {
console.log(errorThrown )
Solution:
Remove slashes from your response try response like below:
'{ "Result":[{"Success":"true"}]}'
Hope this will help you.
Regards,
Can somebody can tell me why my code will suddenly callback to error and suddenly can successful randomly?Thanks.
function get_timeframe(){
var v_fldname = "xUPH_exclude_Timeframe";
if ($.trim(v_fldname) != '') {
//alert(v_fldname);
$.ajax({
url:"../ajax/get_timeframe.php",
dataType: "json",
data:{v_fldname: v_fldname},
success: function(data) {
if ( data.result != null ) {
$.each(data.result, function(){
var code_value = this['code_value'];
document.getElementById('v_xUPH_exclude_Timeframe').value = code_value;
//alert(" get v_xUPH_Scan_Count");
});
}
},
error: function(data) {
alert("get_timeframe error");
}
});
}
}
The following php code.
if (isset($_REQUEST['v_fldname']) === true) {
require '../Connections/con_meditop.php';
$query = mysql_query("
SELECT code_mstr.code_value
FROM code_mstr
WHERE code_mstr.code_fldname = '" . mysql_real_escape_string(trim($_REQUEST['v_fldname'])) . "'
");
$result = array();
if(mysql_num_rows($query) == 0)
{
$result = null;
}else{
while ( $row = mysql_fetch_array($query) )
array_push($result, array('code_value' => $row[0]));
echo json_encode(array("result" => $result));
}
}
The issue is on the receiving end of your Ajax call--get_timeframe.php. Press F12 and click the network part of the console, then send the Ajax call. You'll see get_timeframe.php show up in the network console and then turn red. Click it and look at the response body.
Or instead of alert("get_timeframe error"); Do console.log(data); to see a run-down of the error in the console (press F12).