calling JQuery HTTP GET request inside javascript function - javascript

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}

//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}

jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});

Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Related

AJAX search suggestions on user typing

The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript
input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:
$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor
I tried to do some things on Javascript code but i still don't notice the request on Network Tab
Edit: I also have another ajax call like this in the same file and it works
var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "#" + topheadjsonresponse.username;
}
}
You can use jquery for simplified get request
input.addEventListener("input", (event) => {
output.innerHTML = "Cerca " + document.getElementById("tophead-
searchbar").value + " su Nevent";
getData(); //Call the get function
});
// Ajax function to get data using jquery
function getData() {
let ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
$.ajax({
url : ajaxquerylink,
type : "GET",
success : function(data)
{
let response = JSON.parse(data);
console.log(response);
}
});
}
I solved by myself, in this row
searchqueryajax.addEventListener("load", innerhtmlqueries);
I removed the () in innerhtmlqueries() and now the call response works
Thanks anyway for the support!

Angularjs how to preserve url in function?

Hi I am developing one Angularjs application. I have three cascading drop downs. Based on the selected values in drop down i am binding div with data received from api(div with ng-repeat). I have implemented paging.
On page load i am binding first dropdown.
var arrMakes = new Array();
$http.get(url + 'api' + '/Vehicle/' + 'GetVehicleMake').success(function (data) {
$.map(data.data, function (item) {
arrMakes.push(item);
});
$scope.list = arrMakes;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/';
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
function getcadetails(baseurl)
{
var arrallcarDetails = new Array();
$http.get(baseurl,{ params: $scope.pagingInfo }).success(function (data) {
$.map(data.data, function (item) {
arrallcarDetails.push(item);
});
$scope.carDetails = arrallcarDetails;
$scope.pagingInfo.totalItems = data.totalcount;
}).error(function (status) {
});
}
getcadetails is a function i am calling from different scenarios. For example,
ng-change event of first dropdown
$scope.getModel = function (selectedMake) {
var selectedMakeData = selectedMake.ID;
var arrModel = new Array();
$http.get(url + 'api' + '/Vehicle/' + selectedMakeData + '/GetVehicleModel').success(function (data) {
$.map(data.data, function (item) {
arrModel.push(item);
});
$scope.Modellist = arrModel;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/' + '?MakeID=' + selectedMakeData;
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
}
In paging i have below function. This is executed when i click on page numbers for example 1,2, etc
$scope.pageChanged = function (currentPage) {
$scope.pagingInfo.pageNumber = currentPage;
getcardetails();
};
Here my problem starts. If i click on any page number $scope.pageChanged function executes. I will get page number to send it to server. after that i will call getcadetails(?). Now how can i get baseurl for getcadetails? Is there any way i can implement this in better way? Any help would be appreciated. Thank you.
i think u can define a variate for selectedMakeData, and define a function to create url. every time before invoke getcardetails() u should calculate the dynamicUrl.
code looks this:
var selectedMakeData = 0;
selection.addEventListener('change', () => {
selectedMakeData = newData;
});
$scope.pageChanged = function (currentPage) {
var url = getUrl();
$scope.pagingInfo.pageNumber = currentPage;
getcardetails(url);
};
function getUrl() {
// return url baseed on selectedMakeData
}

How get specific html from a jQuery object

I am fetching html from a website. I want to get specific html from that page not all how to get that? I have tried following;
before appending data to target below
container.html(data);
I want to do like data.find('.site-header').html(); and then do container.html(data);
How can I achieve that?
DEMO
HTML
<div id="target"></div>
Script
$(function () {
var container = $('#target');
var url = 'http://aamirshahzad.net';
$.getJSON("http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) +
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg).focus().effect('highlight', {
color: '#c00'
}, 1000);
}
});
});
function filterData(data) {
// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g, '');
// no linebreaks
data = data.replace(/[\r|\n]+/g, '');
// no comments
data = data.replace(/<--[\S\s]*?-->/g, '');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
// no self closing scripts
data = data.replace(/<script.*\/>/, '');
// [... add as needed ...]
return data;
}
Quite simply;
container.html($(data).find('.site-header'));
Add this line after container.html(data);:
container.html(container.find(".site-header"));
Here is your updated JSFiddle

Saving data to parse using javaScript SDK

Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected

How do I fetch PHP script output from Javascript?

This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/

Categories