How to extract the value passed in through onclick function event? - javascript

I have this onclick="ShowSingleNew(299)" event for a link and it opens up a new popup, what I'd like to do is extract the 299 (which is an id of the given new item) and pass it in my php script so that that would be the item the user can read.
The php bit looks like so:
if (empty($_GET['news_id'])) { sql select .. }
else { sql select where news_id == $_GET['news_id']; }
So how can I pass this ShowSingleNew id to the next page and give it to the $_GET variable?

You have to pass the newsId using query string like url?newsId=104 format.
The basic format should be: ?strID=XXXX&strName=yyyy&strDate=zzzzz
The sample code looks like:
function ShowSingleNew(newsId) {
var url = "Your url goes here";
window.open(url + "?newsId=" + newsId);
// other code
}
On php side, you could use $_GET['newsId'] to fetch the news id.
Note:
Check how to pass mutiple values in query string here: multivalue query string passing
Reference:
QueryString Structure

Try to send like
function ShowSingleNew(id) {
url = desired_url + '?news_id=' + id;
window.open(url , "_blank");
}

Related

How to sent data to server, remove parameter from url and reload window with new url Javascript, jQuery and PHP

I am currently stuck with a problem I can't seem to find a decent solution for.
Problem:
I have written some code that will send 2 parameters to an action within a PHP script through a url. I need these parameters sent to the action no matter what. However, after the parameters are sent, I need to remove one of said parameters from the URL and then reload the page with said new URL.
I hope I could give you a clear description of my problem. Following is the code I have written so far.
jQuery(document).ready(function() {
// Define array with the dashboard id and title as key => value pairs.
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
// Get arg01 from the server.
var arg01 = <?php echo json_encode($arg01); ?>;
// Prepare URL variable and spike it with arg01 to be sent back to the server.
var url = 'Path/To/action/Index/index&arg01='+arg01;
// Button change and function tied to it. Instead of an ajax request, we reload the page completely.
$("#idDashboards").change(function() {
// Define dashboardIndex. The -1 stands for the option tag that has already been created.
var dashboardIndex = $(this).prop('selectedIndex')-1;
// Sent parameters to actionIndex in Controller and remove dashboardIndex after the request was successful.
if (url.includes(arg01)) {
window.location.href = url+"&dashboardIndex="+dashboardIndex;
console.log("Yes i was here");
}
// window.location.href = url; <---- Here is where the problem begins.
});
});

Getting the value of # from a url

I have a problem. i have a website am working on. I have created a php script to fetch all the receipts id from the data base using pagination, and all works fine. But the problem is every receipt id, i have added a link so as when clicked a specified results will be displayed without loading the page.
The links are like :
G145252 G785965 and when each link is clicked will show http://test.com/?go=any#G145252
When clicked the page will not reload.
So what i need help with is how can i get G145252 from the url after when the link is clicked using javascript and print it using html?
i need to pass the value to the process.php as a $GET value so the i can load the receipt detail of the clicked id with out reloading the page.
Please note: there are a lot of get values before the #value i need to get out of the url address.
You should not be using the fragment identifier section of the URI for server side related tasks. This section is intended for client-side manipulation only. More info here.
You can use some other means such as query parameters to access this data.
For example, turn this:
http://test.com/enter code here?go=any#G145252
Into this:
http://test.com?go=any&hash=G145252
Then:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
console.log(getQueryVariable("go")); // any
console.log(getQueryVariable("hash")); // G145252
NOTE: I know this is not the exact answer to your actual problem, but the question itself is presenting a bad practice scenario, thus my suggestion.
Credits for the getQueryVariable function goes to CSS Tricks: https://css-tricks.com/snippets/javascript/get-url-variables/?test=3&test2=5
Let's assume you're using jQuery.
Change all your links so that they have a common class name, lets say 'hashClick' e.g
My Link
To get the hash part when clicked, add a click event handler for those links
$('.hashClick').click( function(event) {
event.preventDefault();
var url = $(this).attr('href');
var hash = url.substring(url.indexOf('#')+1);
alert("You clicked " + hash);
// or at this point you can do an AJAX call
// or GET request to process.php with hash as one of the parameters
})
suppose this is the link
http://test.com/?go=any#G145252
to get the hash value
window.location.hash
which will return you #G145252
and
window.location.hash.substring(1) will return you "G145252"

Jquery $.getJSON User Input

I am trying to add an html input box to allow users to set a value which adjusts the result returned from a sql request. My request currently contains a parameters to which a variable is supplied and sent as a request.
I am new to jquery and uncertain as to how to fetch the user inputted value as previously done with the simple getElementById in JavaScript.
My jquery is:
var schema = 'sewer_pipelines';
$.getJSON("sql_query.php", // The server URL
{ parameter: schema },
saveToArray
);
Is there a method which will allow for user input in this approach?
You have to use a selector like this :
var schema = $('#sewer_piplines').val();
More on jquery selectors : https://api.jquery.com/category/selectors/
Thanks for the help, problem is now sorted.
Working code is:
var schema = $('#attribute_parameter').val();
$.getJSON("sql_query.php", // The server URL
{ parameter: schema },
saveToArray
);
var value= $('#inputid').val();

How to save a JavaScript string on a server with PHP and request it again later?

So my problem is actually pretty simple:
I have this function (simplified) - it is triggered when a button is clicked:
$search.onclick = function () {
// let's just say the user did put in a valid documentname
// something like "John"
documentname = $('#userinput').val();
url = "https://example.api.url.com/" + documentname + "&format=json"
// looks weird but "source = $.getJSON(url).done..." works like expected
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
// this findid(); below is just a function that takes the id i'm looking for
// out of the just stringified JSON (works also), it does "id = "123456"
// (just a number but in string format)
findid();
// id has a value now ("123456"), so lets console.log it
console.log(id);
});
};
What I want to do is:
After findid(); is executed and id has a value I want to save this value as a readable file on the server. It's filename should be the same as the name of the document it's coming from (in this case John). The content of the file should just be the value of id (in this case 123456). Which file format? I don't know. And here is the next problem...
Reuse the file:
The next thing I wish I would be able to do is, to load this generated file when the exact documentname was inputted again by another user. Because if the file already exists, it would be unnecessary to load the whole JSON again. So the updated code would look like this (i know that this isn't actual code, but maybe it's easier to understand with this):
$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if ([A FILENAME ON THE SERVER] == documentname) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
[OPEN FILE/TAKE CONTENT]
// and just assign it to the variable
id = [CONTENT OF FILE]
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// and of course save this now on the server
[SOME PHP ACTION HERE]
});
}
};
I already tried a lot of things with Ajax and jQuery's $.get, I just have no idea how to handle sent things with PHP. I don't know which file format is best for this, or if this is even possible. I don't know how to transfer variables from JavaScript to PHP documents or how to use them there or vice versa.
PS: My developer environment: I don't run a server by myself, I have some webspace and a domain from a web service. Yes it supports PHP. MySQL and other database types are available too, if that's a useful information. jQuery is also installed.
Sorry again, for my bad english and for my lack of knowledge and interest in PHP and other serverside things. However, I hope you can help me somehow.
You can use localStorage to store a file at users browser configuration folder : user filesystem. If file exists at localStorage, use the file from localStorage without making $.getJSON() request, else call $.getJSON(); at success of $.getJSON() set the file at localStorage.
$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if (localStorage.getItem(documentname) != null) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
// and just assign it to the variable
id = localStorage.getItem(documentname);
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
// and of course save this now on the server
// [SOME PHP ACTION HERE]
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// set `localStorage` item key to `documentname`
// set value to `id`
localStorage.setItem(documentname, id);
});
}
};
See also How to cache a downloaded javascript fle which is downloaded using script tag
Flow process to make this work should be more like:
ajax request to php endpoint on server.
php checks if data stored locally ( in file or database)
If not stored already , php makes request to other api. When the api returns data, php stores it in file or database.
php returns the data to ajax from either the local source or from api response.
So the javascript would only make one request to your server and get the data returned and not know or care how php found it
jQuery has a $.post() function, https://api.jquery.com/jquery.post/
$.post(url, { id: 123456 });
or
$.ajax({
method: 'POST',
url: 'http://example.api.domain.net/document.php',
data: { id: 123456 },
success: function(responseData) {
}
});
PHP will then be able to read it like so:
$post_data = $_POST['id'];
// Here you do whatever with it, for example store to database

Append string to the end of a JSON request in javascript

I am trying to append data data from a form to a request so that the complete URL is sent as the request. I know I can do this in PHP but want to know if I can also do it in the javascript
For example the json request is sent to
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
Where ZIP will be replaced by the user submission
$(function() {
$("#getzip").submit(function() {
var zip_data =$(this).serialize();
$.getJSON("get_weather.php",null , function(data); {
Is it possible to pass it in stead of the null? And how would I go about appending it to the request strictly in the javascript?
$.getJSON("get_weather.php",{
whatever: "value",
somemore: "another value"
}.function(){
//
};
then in your PHP:
$whatever=filter_input(INPUT_GET,"whatever",FILTER_SANITIZE_STRING);
$somemore=filter_input(INPUT_GET,"somemore",FILTER_SANITIZE_STRING);
Seems like you would need to append it to the URL string itself:
$.getJSON("http://api.wunderground.com/api/myapi/conditions/q/"
+ zip_data, function(data){ return data });

Categories