I am using JQuery Mobile for creating mobile application and i have index.html in this html page i have 2 pages(search_form, search_result). I want to submit search form from search_form page and then it should shows the search_result page. The following is my js code:
var formURL = "http://10.0.2.2/jobs/mobile/home/searchJobs/";
$.ajax(
{
url : formURL,
type: "POST",
data : $("#search_frm").serialize(),
//data : "&data=90",
beforeSend: function() {
showLoader();
},
success:function(result)
{
var list = '';
var data = $.parseJSON(result);
//$("#ulListview1").html($.parseJSON(result));
$.each(data,function(i,item){
if(item.id=='0')
{
list += "<li><span style='color:red;'>Record not found!</span></li>";
}
else
{
list += "<li><a data-transition='slide' href='#job_details_page' onclick='getJobDetails("+item.id+");'>" + item.job_title +"<p style='display:inline;'> at "+item.company+"</p><br><p><span><strong>Expiring On:</strong> "+item.expire_date+"</span> <br><span><strong>Job Location:</strong> "+item.location+"</span></p>"+"</a></li>";
}
//alert(data[i]["id"] + " " + data[i]["username"]);
});
//hide loader
hideLoader();
$("#search_list").html(list);
$("#search_list").listview("refresh");
$("#search_result").css("display","block");
},
error: function(jqXHR,status)
{
alert(status);
//alert($.parseJSON(jqXHR));
}
});
Could you please help to fix this problem?
Related
I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).
My ASP.Net webpage generates buttons with below codes
<a id="1173766" val="248506" titletext="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1" target="_self" href="https://localhost:6969/VenueTicketing/Start.aspx?sessionId=248506&cinemaId=cbcc0921bb8e233ab9626690" class="tooltip" title="<b>Click to book online for ABC Cinemas</b><strong>$10 tickets </strong>: Preview Screening<br /><br />Seats Available: 35<br />Screening in Cinema 1">11:30am</a>
When I hover over session I see basic information about session like screen name and seats remaining. Please see screenshot attached
On hover over session I want to display real time seats remaining number, So i am making an ajax call to a function which send api request and get live seats remaining number.
I am trying to update seats remaining number on rendered page by using following java script code.
<script type="text/javascript">
$(document).ready(function () {
function handler(ev) {
var target = $(ev.target);
var sessionid = target.attr('id');
var sessionPOSid = target.attr('val');
var TooolTipText = target.attr('titletext');
target.attr('title', TooolTipText);
if (sessionPOSid == "done")
{
}
else
{
if (target.is(".tooltip")) {
$.ajax({
type: "POST",
url: '../WebService/Home_SessionTimes.asmx/GetSeatsRemaining',
data: "{sessionId: '" + sessionid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//alert(msg.d);
var n = TooolTipText.indexOf("Seats Available: ");
var t = TooolTipText.substr(n + 17, 3);
if (t.indexOf("<") >= 0) {
if (t.indexOf("<") == 2) {
t = t.replace("<", "");
}
else {
t = t.Substring(0, 1);
}
}
TooolTipText = TooolTipText.replace(t, msg.d);
$('#' + sessionid).attr('title', TooolTipText);
$('#' + sessionid).attr('titletext', TooolTipText);
//$('#' + sessionid).attr('val', "done");
target.attr('title', TooolTipText);
target.tooltiptext = TooolTipText;
},
});
}
}
}
$(".tooltip").mouseover(handler);
});
Above code updates the "titletext" field of tag but does't change anything on "title" field.
Any help would be appreciated.
I have solved this by using qtip. Every time user hovers over div with 'sessiontimes' class, I make ajax call to generate tooltip text (that comes from server based upon session time).
This is my output now:
This is the jQuery code. you need to import qtip css and script files from their website.
<script type="text/javascript">
$(document).ready(function () {
$('.sessiontimes').qtip({
style: { classes: 'qtip-bootstrap' },
content: {
text: function (event, api) {
$.ajax({
url: '../SessionToolTip.aspx',
data: 'sid=' + $(this).children("a").attr("id"),
dataType: "text",
})
.then(function (content) {
api.set('content.text', content);
}, function (xhr, status, error) {
api.set('content.text', status + ':' + error);
});
return 'Loading...';
}
}
});
});
</script>
If you may look at this post and see if the same answer could apply to your situation
JQUERY Change Title not working with tooltip
i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
I have a total of 4 XML files in same format representing 4 different categories of project contents. However some projects does have more than 1 category.
I want to merge all 4 XML files using jQuery and display all projects contents in a single page within a , but due to the fact that some projects have more than 1 category, the displayed results show duplicates of project contents.
How do I remove duplicates within the combined extracted XML files?
Here is my jQuery Code:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();
I hope my code is correct. Had no data to test with, but I think the idea of it should be a bit more clear.
edited: Now working, version after receiving xml test-data
<html>
<head>
<title>asdasd</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</head>
<body>
<div id="list">
</div>
<script>
XMLLIST = {
dataToLoad: [
'test.xml'
],
loadedData: [],
appendTo: '#list',
rand: function() {
return new Date().getTime();
},
loadData: function(file) {
$.ajax({
type: "GET",
url: file + "?" + XMLLIST.rand(),
dataType: "xml",
success: XMLLIST.parseXML,
error: function(r) {
console.error(r);
}
});
},
init: function () {
XMLLIST.dataToLoad.forEach(function(file) {
XMLLIST.loadData(file);
});
},
parseXML: function (xml) {
var data = $('item', xml).get();
$(data).each(function (i, value) {
var $value = $(value),
item = {
url: $value.find('url').text(),
image: $value.find('image').text(),
title: $value.find('title').text()
};
if (!XMLLIST.itemIsInList(item)) {
XMLLIST.loadedData.push(item);
XMLLIST.insertHTML(item);
}
});
},
itemIsInList: function(item) {
var hits = XMLLIST.loadedData.filter(function(value){
return XMLLIST.compareItem(item, value);
});
return hits.length > 0
},
compareItem: function(item1, item2) {
return item1.url === item2.url && item1.image === item2.image && item1.title === item2.title;
},
insertHTML: function (item) {
var html = '<div class="item">';
html += '<img src="' + item.image + '"><br>';
html += '<span class="contentsubtitle">' + item.title + '</span><br><br>';
html += '</div>';
$(html).appendTo(XMLLIST.appendTo);
}
};
XMLLIST.init();
</script>
</body>
</html>
You have a list, where you push your objects to. This list has a checkFunction "itemIsInList". Additionally you need a seperate check-function "compareItem", because indexOf won't work with objects
Managed to modify my original script by adding a masterArr for comparison of duplicated data received accross the 4 XMLs.
Here's the codes:
XMLLIST = {
//general settings
xml1: 'xml/structural_steel.xml?' + Math.random(0,1), //solve ie weird caching issue
xml2: 'xml/building_work_id.xml?' + Math.random(0,1), //solve ie weird caching issue
xml3: 'xml/shear_stud_welding.xml?' + Math.random(0,1), //solve ie weird caching issue
xml4: 'xml/custom_solution.xml?' + Math.random(0,1), //solve ie weird caching issue
appendTo: '#list', //set the id/class to insert XML data
//end general settings
masterArr: [],
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml1,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml2,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml3,
dataType: "xml",
success: XMLLIST.parseXML
});
$.ajax({
type: "GET",
url: XMLLIST.xml4,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data;
data = $('item', xml).get();
var i = 1;
//Loop through all the ITEMs
$(data).each(function () {
//Check if masterArr[] already contains a duplicate of the item by checking using the XML label <image> or any other value/label that is unique.
//Insert into masterArr[] if not duplicate and publish HTML if not duplicate.
var string1 = $(this).find('image').text();
if( jQuery.inArray(string1, XMLLIST.masterArr) == -1){
XMLLIST.masterArr.push(string1);
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
};
//If it reached user predefined total of display item, stop the loop, job done.
//if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var title = item.find('title').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<img src="' + image + '"><br>';
html += '<span class="contentsubtitle">' + title + '</span><br><br>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
}
//Run this script
XMLLIST.init();
I am trying to craft an AJAX form to display a success/failure/share message via a Fancybox once a user submits their email address on a form. Currently, the code throws the response up to the top of the page.
I have attempted a few variations from other answers provided here here, and here on Stack Overflow, but to no avail, as upon insertion the entire form ceases to load.
My current init.js is as follows:
$("#form").submit(function(e){
e.preventDefault();
leSubmitLoader();
dataString = $("#form").serialize();
var templateURL = $('#templateURL').attr('value');
var blogURL = $('#blogURL').attr('value');
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json",
success:
function(data) {
$.fancybox(
'<p>Content of the box in HTML</p>',
{
padding:15,
closeBtn:true
}
);
function leSubmit(returning){
$.fancybox(
);
$('#form, #error, #presignup-content').hide();
$('#success').fadeIn(function(){
var successScroll = $('#signup-body').offset().top - 20;
$('html,body').animate({scrollTop:successScroll}, 300);
});
if (returning == true) {
$('#returninguser, #returninguserurl').show();
var refCode = data.returncode;
$('#returninguser span.user').text(data.email);
$('#returninguser span.clicks').text(data.clicks);
$('#returninguser span.conversions').text(data.conversions);
$('#returninguserurl input#returningcode').attr('value', blogURL + '/?ref=' + refCode);
} else {
$('#success-content, #newuser').show();
var refCode = data.code;
$('#newuser input#successcode').attr('value', blogURL + '/?ref=' + refCode);
if(data.pass_thru_error == "blocked"){
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html('AWeber Sync Error: Email Blocked.');
} else if (data.pass_thru_error.AWeberAPIException != undefined){
err = data.pass_thru_error.AWeberAPIException;
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html(err.type+': '+err.msg);
}
}
// Referral URL
var refUrl = blogURL + '/?ref=' + refCode;
// Twitter (note: refUrl might not show up in share box on localhost)
var tweetUrl = 'http://twitter.com/intent?url=' + encodeURIComponent(refUrl);
var tweetMessage = $('input#twitterMessage').attr('value');
$('#tweetblock').html('Tweet<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>');
// Facebook (note: won't work on localhost)
$("#fblikeblock").html('<div class="fb-like" data-ref="'+refCode+'" data-href="'+refUrl+'" data-send="false" data-width="75" data-show-faces="false" data-font="arial" data-layout="button_count"></div>');
// Google +
function renderPlusone() {
gapi.plusone.render('plusoneblock', {'href':refUrl, 'size':'tall', 'annotation':'none'});
}
renderPlusone();
// Tumblr
var tumblr_button = document.createElement("a");
tumblr_button.setAttribute("href", "http://www.tumblr.com/share/link?url=" + encodeURIComponent(refUrl) + "&name=" + encodeURIComponent(tumblr_link_name) + "&description=" + encodeURIComponent(tumblr_link_description));
tumblr_button.setAttribute("title", "Share on Tumblr");
tumblr_button.setAttribute("onclick", "window.open(this.href, 'tumblr', 'width=460,height=400'); return false;");
tumblr_button.setAttribute("style", "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('http://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
tumblr_button.innerHTML = "Share on Tumblr";
document.getElementById("tumblrblock").appendChild(tumblr_button);
// RinkedIn
$('#linkinblock').html('<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="'+refUrl+'"></script>');
}
if(data.email_check == "invalid") {
leSubmitLoaderStop();
$('#error').html('This email address is invalid.').fadeIn();
}
else if(data.required.length) {
leSubmitLoaderStop();
$('.error').hide();
$d = String(data.required).split(",");
$.each($d, function(k, v){
$("#" + v + ".error").fadeIn();
});
}
else {
if(data.reuser == "true") {
leSubmit(true);
FB.XFBML.parse(document.getElementById('fblikeblock'));
} else {
leSubmit(false);
FB.XFBML.parse(document.getElementById('fblikeblock'));
}
$('body').addClass('submission-success');
}
}
});
});
I am not trying to fix your code but why you don't use this ajax format to handle success/failure ?
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json"
}).done(function () {
//success
$.fancybox("success", {
// options
});
}).fail(function () {
//error
$.fancybox("failure", {
// options
});
}).always(function () {
// optional after ajax is completed
$.fancybox("else", {
// options
});
});