How to display retrieved data from JavaScript through html - javascript

I know this seems kind of vague, but it was the best way I could put this into words. Below is the example of my code.
JavaScript
<script type="text/javascript">
var name = $('#firstName').val();
var email = $('#userEmail').val();
var json = { Email: email, FirstName: name };
var string = JSON.stringify(json);
$.ajax({
url: 'http://uBuildRewards.api/api/Users/GetInfo',
type: 'GET',
contentType: 'application/json',
dataType: "json",
crossDomain: true,
data: string
});
</script>
HTML
<div class="user-logged-in">
<div class="content">
<div class="user-name" id="firstName"> **NAME HERE** <span class="text-muted f9">admin</span></div>
<div class="user-email" id="userEmail"> **EMAIL HERE** </div>
<div class="user-actions">
<a class="m-r-5" href="">settings</a> logout
</div>
</div>
</div>
Before all this, in another view I have similar JavaScript code that is doing my login. Which is accessing a method from the UsersController that gets all information, and if email and pass is correct it logs me in. Then, this method, is when I am logged in I want it to say that Welcome, (name of user logged in as) and your current email address is (who ever I am logged in as).
So I am trying to find out how, from the javascript, to paste the info retrieved from the 'GetInfo' method, and display the Name and Email where I put "NAME HERE and EMAIL HERE"
I tried to be as descriptive as I possibly could. Sorry for any confusion. I greatly appreciate your help in advance :) Still fairly new to JQuery and JavaScript!

why are you sending login credentials over http and not https (SSL)?
That aside...
You have to use .done method.
$.ajax({
url: 'http://uBuildRewards.api/api/Users/GetInfo',
type: 'GET',
contentType: 'application/json',
dataType: "json",
crossDomain: true
}).done(function(data) {
console.log("Sample of data:", data);
$('#firstName').text(data.name);
$('#userEmail').text(data.email);
});

Related

How to build entire dataset prior to sending AJAX -Jquery

I have a system that allows an admin to add managers to a campaign from a table. The table looks something along the lines of
<tr>
<td>Checkbox</td>
<td>Last name, First name</td>
<td>Employee Id #</td>
</tr>
Currently, when the "Add Manager" button is hit, I pass the manager's id and a "checked" value using this function
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
})
}
</script>
What this does is iterate through the table, build the JSON response and pass it back to the Django view to do the backend processing. My problem is this, for each row it sends a POST request and that drastically increases the time it takes for the process to complete. I'd like it to build the entire dictionary prior to sending the response, but just can't wrap my head around how to do that. Any help would be appreciated.
Alright, so as n1md7 pointed out in the comments, I simply needed to move the AJAX request outside of the loop. Here is what the code block looks like now:
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
})
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
}
</script>
As you can see, I now close the loop prior to making the request and it went from a 4+ minute process to almost instantaneous. Thank you n1md7

Django POST With Using Ajax

I have one app name register_login and this app manages login and register opeartions. I have a form on localhost:8000/login page and i want that the button redirects to my func in register_login app but i cant do it. I'm new at Django Framework. How can i handle this?
MAIN URLS.PY
from django.conf.urls import include,url
from django.contrib import admin
from register_login.views import login, register, test
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^homepage/', include('homepage.urls')),
url(r'^login/$', login),
url(r'^register/$', register),
url(r'^success/$', test),
]
LOGIN PAGE .HTML
<form id=registerLogin style="margin-top: 30px; margin-left: 350px;">
<header>Login</header>
<label >Username <span>*</span></label>
<input id="username"/>
<label >Password <span>*</span></label>
<input id="password"/>
<button id="login">Login</button>
<h1 style="margin-left: 20px;">Are you not registered?</h1>
<button id="register">Register</button>
</form>
At the end of this html there is my .js file. I didnt forget.
JAVASCRIPT
if (!jQuery) { throw new Error("This page requires jQuery") }
function readInput() {
e.preventDefault();
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
debugger
$.ajax({
type: "POST",
url: "/success/",
data: {'username':username,'password':password, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: 'json',
success : function(json) {
$('#post-text').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
console.log("success"); // another sanity check
},
});
}
(function ($) {
$("#login").click(function(){
readInput();
});
})(jQuery);
And finally my function. Its in register_login app as i said before
REGISTER_LOGIN VIEW
def test(request):
embed()
if request.method == 'POST':
embed()
return HttpResponse("hell world")
I tried to change url like "/register_login/success/","/register_login/success","/register_login/success/$","/success/","success/" or "/success/$". Nothing works
I need to go that function but it doesnt :(
Since you are logging in via ajax, you can not redirect in your test view. What you can do is add a redirect in your ajax success function. Something like this:
// similar behavior as an HTTP redirect
window.location.replace("/some-url/");
or
// similar behavior as clicking on a link
window.location.href = "/some-url/";
Also, you need to fix your javascript code, add preventDefault in the click handler and remove it in the readInput. You also need to remove the quotes in the data object and make sure you used the correct variables. Something like this:
$(function() {
function readInput() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
$.ajax({
type: "POST",
url: "/success/",
data: {
username: username,
password: password,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
dataType: 'json',
success : function(json) {
window.location.replace("/some-url/");
}
});
}
$("#login").click(function(e){
e.preventDefault();
readInput();
});
});

Send a POST request in jQuery when a div is clicked

I am having trouble figuring out how to get the following done.
click on a paragraph element
send a .post request using jQuery
get the sent data from the server to display in the paragraph
I've searched quite a bit and tried using some of the solutions proposed but it failed.
Here's my folder structure:
+ html
- index.html
+ js
- eventhandling.js
+ php
- test.php
HTML
<div class="channel" id="channel1">
<p class="title">CHANNEL 01</p>
<p class="stb_sub_menu" id="model">STB Model</p>
<p class="network_sub_menu" id="network">Network</p>
<p class="smartcard_sub_menu" id="smartcard">Smartcard</p>
<p id="reboots">Reboots</p>
</div>
<p id="demodata">Demo Data</p>
PHP
<?php echo "PHP script -> You called master?"; ?>
JS
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").val("data");
});
});
The click event is successful because the alert pops up. Nothing shows on the Firebug console window.
Might be the service URL you passed into post is wrong (according to the folder structure).
The code must be like this.
$(".channel").click(function(){
var postData = {"name":"john"};
$.ajax({
type: "POST",
url: '../php/test.php',
data: postData ,
contentType: "application/json",
dataType: "json",
processdata: true,
success: function (response) {
},
error: function(error){
}
});
});
This will work for you.
$(".channel").click(function(){
/*alert(I am clicked");*/
$.post('test.php', {name: 'John'}, function(data) {
$("#demodata").text(data);
});
});

Ajax submission on page load

I'm trying to create a test script for a small little website I'm doing, and it requires a lot of troubleshooting with this particular form. In order to get a response, I need to fill out 5 step form wizard and then wait for the results. I've been trying to create a small little script I can use on a seperate page to test my php functions in a heartbeat. Here is what I have so far, and it doesn't seem to even post to the page.
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var data = {
console: "playstation",
game: "FIFA14",
coinamount: "10000",
team: "Some Team Name",
league: "Some League Name",
player: "Some Player Name",
quality: "Silver",
chemistry: "Basic",
position: "CAM",
customername: "Joey Small",
customeremail: "jsmall#email.com",
customerphonenumber: "23454343534",
payment: "pp"
}
$.ajax({
type: "POST",
url: "order.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#response").html(data);
}
});
});
</script>
I'm inspecting the network data in my browser, and it is not sending to order.php. I don't have much love for javascript, especially Jquery, so any help would be greatly appreciated.
first thing you should do is close the script tag on your Jquery include at the top
Ok, so the additional options added on to the end are what is making the script not submit.
$.ajax({
type: "POST",
url: "order.php",
data: data,
success: function(data){
//alert("---"+data);
$("#response").html(data);
}
});
That works correctly. Daedalus's comment got me to thinking about the additional tags, and how they are not needed.

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories