I have a scenario where I have to show a progress bar to load data to sqlite from online server.I am loading a few master tables and transaction tables. I have created the sqlite tables and then called ajax to get data and have loaded in sqlite:
insert_sur_category(function(ret_insSur)
{
//calls ajax gets data from php and then inserts into sqlite using foreach loop and insert command
if(ret_insSur=="success")
{
insert_districts(function(ret_dis)
{
}
}
}
sample ajax code
function insert_sur_category(callBack){
//alert("ding here");
var i;
var separator='surveymaster';
//alert(sessionStorage.url+"load_masters.php?separator="+separator);
$.ajax({
type: "POST",
url: sessionStorage.url+"load_masters.php?separator="+separator,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
obj = JSON.stringify(data);
obj1 = JSON.parse(obj);
if(obj1!=0)
{
var i=0;
$.each(data, function(i, item) {
myDB.transaction(sur_category);
function sur_category(tx){
tx.executeSql('INSERT INTO survey_category (sur_category_id, sur_category_name,last_updated) VALUES("'+obj1[i].id+'","'+obj1[i].name+'",datetime())');
}
// sur1();
//callBack("success");
});
sur1();
callBack("success");
}
else
{
//alert("sdfdsf");
callBack("failed");
}
},
complete: function(){
}
});
}
After all callbacks are success I have given a alert to say data loaded successfully.However the alert comes long before the data is loaded.I am checking using google chrome.Any help Please
transaction is an asynchronous call. To make synchronous call, you can check this link and follow it's answer.
It will surely help you.
Related
I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});
I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!
I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)
The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}
I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });