Ajax MySQL POST responses with Object without data - javascript

I am using that code to send a POST request to add data to a mysql table.
var todoItem = $(this).serialize();
$.ajax({
type: "POST",
url: "/test",
data: todoItem,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.success){
$('#todo-list').append(
'<li class="list-group-item">' +
'<span class="lead">' +
data.todo +
'</span>' +
'<div class="pull-right">' +
'Edit' +
'<form style="display: inline" method="POST" action="/test/${data.id}">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button>' +
'</form>' +
'</div>' +
'<div class="clearfix"></div>' +
'</li>'
);
} else {
$("#todo-list").append(
'<li class="list-group-item">' +
'<span class="lead">' +
'Fail' +
'</span>' +
'<div class="clearfix"></div>' +
'</li>'
);
}
}
Then i want to use data from the response to append to my list.
But if(data.success) isnt passing. why is that?
Also my data in console.log looks like object Object and doesnt contain the inserted row data.
Do i need to send a get request now to retrieve the last data row?

Related

One page app doesn't refresh with Ajax and SQL requests (online only)

I'm trying to build a trip organiser. It's a one page app. There are a list of trips, with their activities on one side, and the Google Map on the other side.
Screenshot here : http://hpics.li/fc1b59c
I have two main files : one called app.js, where I trigger events with forms and click on buttons. Then I get or send data to travelAPI.php, where I send and retrieve data from the database.
When I add a trip or an activity; I empty the whole list, then I retrieve all the trips and activities again from the DB.
In my local environment, everything works fine. But when I tried to put it online, it's a mess. SQL requests work fine, but my trips list doesn't update, and I don't understand why. Actually, the list seems to refresh, but with the same results, and without the trip I just added. (But the trip is pushed into the database)
To display the new trip, I need to clear Google Chrome cache.
I tried to analyse this issue with Postman extension, but it seems to come from the client side.
Ajax request:
function insertTrip() {
$.ajax({
url: 'travelAPI.php?call=insertTrip',
type: 'POST',
data: {
cityName: $("input[name=cityName]").val(),
date: $("input[name=date]").val(),
dateUpdatePlace: $.now()
},
success: function() {
initTripList();
}
});
};
initTripList method:
function initTripList() {
$("#tripList").html('');
var listPlace = new Array();
$.ajax({
type: "GET",
url: "travelAPI.php?call=getTrips",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
} else {
if ($.inArray(data[i].idPlace, listPlace) != -1) {
$('.trip[data-id="' + data[i].idPlace + '"] ul').append('<li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li>');
} else {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
}
}
listPlace.push(data[i].idPlace);
}
}
});
setTimeout(function() {
initTripListSec();
}, 100);
};

URL Name not resolved in Jquery

I am trying to dynamically build up HTML using JQuery in ASP.NET MVC5. I have so far had success, but the URL cannot be resolved in the JQuery Code.
My code looks something like this:
$.ajax({
type: 'POST',
url: '#Url.Action("QuerySearch")',
dataType: 'json',
data: {
queryName: $("#queryText").val()
},
success: function (data) {
// var items = '';
$.each(data, function (i, item) {
var resource_Url = item.ResourceURL;
// var resource_url = item.ResourceURL;
var append_data = $('<div class="row">'
+ '<h3>' + item.ResourceTitle + '</h3>'
+ '</div>'
+ '<div class="row">'
+ '<span class="label label-primary" style="margin:3px;font-size:small;">'
+ item.ResourceEducation
+ '</span>'
+ '<span class="label label-warning" style="margin:3px;font-size:small;">'
+ item.ResourceGrades
+ '</span>'
+ '<span class="label label-info" style="margin:3px;font-size:small;">'
+ item.ResourceSubject
+ '</span>'
+ '<a href="#Url.Content("' + item.ResourceURL + '")">'
+ '<img src="#Url.Content("~/Content/Resources/download_icon.png")" alt="Download Resource" style="height:24px;width:24px;"/>'
+ '</a>'
Although this code is able to retrieve the image for the download_icon defined in my project, it is not able to display / embed the URL fetched from the server by my function which I am trying to display in the <a href> tag.
Any help is greatly appreciated.
You will need to pass the complete url value from the server as a property of the data received. Or have it stored locally
ASP code doesn't run in the browser, only on server
The trick was simple, the href tag had to be changed to:
'<a href="' + item.ResourceURL + '">'
It worked like a charm

Jquery loop with AJAX, looping through bootstrap modal

I am getting data from database, looping trough it and appending to the div in html page. It works until I am looping trough function witch contains bootstrap MODAL. I am passing parameters to function but every MODAL that was created display first row of my database table. My goal is to loop trough my function(MODAL) and pass different rows of my table, not only the first one.
VARIBLE WITH MY HTML
var table = {
createTable: function(result) {
$.each(result, function(i, column) {
$("#loopRows").append(
'<tr id="post"><td>' + column.ID + '</td>' +
'<td>' + column.Title + '</td>' +
'<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#details">Details</button>+showBookmark.showItemTemplate(column.Title, column.Url, column.User)+</td>'
});
}
}
AJAX REQUEST
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'http://localhost:62795/api/bookmarks',
success: function(result) {
table.createTable(result);
}
});
});
BOOTSTRAP MODAL WITH HTML FORM
var showBookmark = {
showItemTemplate: function(title, url, user) {
return '<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" id="details">' +
'<label for="recipient-name" class="control-label"> Title:' + title + '</label>' +
'<label for="message-text" class="control-label"> Url:' + url + '</label>' +
'<label for="message-text" class="control-label"> User:' + user + '</label>' +
'</div>'
}
}

Format of OnClick link in a .append

I am building a iPhone PhoneGap app, I am trying to include a Share button to share some data I pull from the server using JSON.
Here is what my code looks like:
$.ajax({
url: 'http://www.myurl.com.au/api/get_category_posts/?category_id=5&custom_fields=displaynative&callback=?',
dataType: 'json',
data: null,
// crossDomain: true,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
timeout: 15000,
success: function(data, status)
{
(data.portfolio);
$.each(data.posts, function(i,item){
if(item.title_plain != undefined){
if(item.custom_fields.displaynative != undefined){
$('#datanews').append("<div data-role='collapsible' class='ui-nodisc-icon ui-alt-icon' data-theme='a' data-icon='r'><h4>" + item.title_plain + "</h4><p>"+ item.custom_fields.displaynative +"</p><a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a></div>").trigger('create');
}
}
});
IT works except the Save/Share button and I know why but i don't know how to fix it.
Needs to be: `Save/Share
But I can't use the "" for the on click because it causes a formatting error.
Anyone know what I can do?
Thanks,
Ben
Your last parenthesis was on the wrong side.
Your code
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a>
Fixed
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "')>Save/Share</a>
Could also recommend to put double quotes on the onclick attribute:
<a href='#' class='ui-btn' onclick=\"window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "'\")>Save/Share</a>

JQuery Form Submission with enter key AJAX API

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}
$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.
You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

Categories

Resources