How to call this.id in a $.get URL - javascript

I am trying to execute a javascript script but I am not sure how to do this. I usually work in PHP but for this specific thing I needed to implement some javascript. On my website I have a couple of buttons with different ID's. When a button gets pushed, a javascript will run. Inside the javascript the ID will be used to execute a php page. Right now I am using the button to delete a certain thing.
For instance, let's say I push the button with ID= 20. Then I would need the page to run the follow script:
$("button").click(function() {
$.get("example.php?id=(this.id)");
});
As you can see I am trying to execute the page example.php?id=20 but this is somehow not working and I have no idea how I would fix this. Is there a different way to solve this problem? Btw, I use this as button
<button id="<?php echo $id; ?>" class="btn btn-primary sweet-4" onclick="_gaq.push(['_trackEvent', 'example', 'try', 'sweet-4', 'this.id']);">Test</button>
There are some more things happening here, but the main thing I want happening is getting the ID. Thanks in advance.

JavaScript doesn't have string interpolation (unless you use a template literal, but there's no IE support), so you will have to concatentate.
$.get("example.php?id=" + this.id);

$.get("example.php?id=" + $(this).attr('id') );

Everything inside of quotes is interpreted as a String, not as a Javascript key word. It looks like you're trying to use parentheses to interpolate the string held in this.id. You can't do that in Javascript.
$.get("example.php?id=" + this.id );

Related

Javascript and PHP in harmony - Search function

I am currently constructing a "datatable"-ish search function.
When a user inputs something into a search box, I'd like to update the div containing its values.
Currently I do this using this input field:
<input type="text" id="IdSearch" onkeyup="Search()" value="<?php echo $searchtext; ?>" onfocus="this.value = this.value;" name="zoeken" autofocus>
The onfocus="this.value = this.value; makes sure the selector is behind the values after the page is reloaded.
<script>
function Search() {
var x = document.getElementById("IdSearch").value;
window.location.href = "index.php?search" + x;
}
</script>
And then
if (isset($_GET['search'])) {
$searchtext = $_GET['search'];
echo $searchtext;
$sql = "SELECT blabla FROM blabla";
//execute sql statement and update the table now..
} else {
//generate the standard table
}
This works, it outputs a correct result, but it's sluggish. The page needs to reload every time you input a character.
So maybe, just maybe, I can somehow retrieve the searchbox' value every time a key pressed, and update my table that way?
I know PHP runs and then doesn't run again without a page reload. Maybe I can reload certain elements? I don't know.
Please, don't go all "PHP runs on the server" on me. I know, that's why I'm currently using this method. I am not even going to attempt to learn ajax in the timespan I have to finish this.
Any help is appreciated.
I am not even going to attempt to learn ajax in the timespan I have to finish this.
I'm afraid you'll have to either learn AJAX or submit to using iFrames. If you are going to use AJAX, there's some great libraries out there (JQuery or Zepto.js, or maybe qwest) that make it super easy to learn, quickly.
Maybe I can reload certain elements?
Yes! The other option, using iframes is pretty strongly frowned-upon by the web developer community as a whole, but it does exactly what you ask for. Check out MDN's information about scripting iframes. You can use the same properties as you do on window now, but it will still probably be sluggish and most likely quite annoying to work with as well.
So, if you want my advice: use AJAX. But it's your choice!
-Either you use a button " " to submit the search....
and remove the onkeyup="Search()"
<button type="submit">Search</button>
-Or you can try to post your form into an Iframe.... but still will be sluggish.
-The way to go is AJax : dynamically update the content while type-in.
use AJAX (like $.ajax) and create a php response in json. then recreate your content with a javascript template or an MVVM framework like angular.
Another way is return the part of the content than you need and inject with $('#mycontent').html(response).
try jquery $.post it's everything you're looking for.
http://api.jquery.com/jquery.post/

Double Nested PHP and Javascript with jQuery

I've run into a bit of a design problem. I have a webpage with a button. The page is written in php. The php outputs HTML that uses jQuery to initialize a button. When I click that button, a jquery dialog appears. The contents of the dialog are created from an object in PHP. and passed from a php object, but require formatting in Javascript, which is also passed from the php object.
A simplified version of the code would look like this:
$obj = new Custom_Object();
echo <<<EOD
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>" + {$obj->print()} + "</div>");
dialog.dialog();});
</script>
EOD;
with $obj->print() looking something like:
$return = "<p>Some HTML</p>";
$return .= "<script>Some Javascript to format the 'Some HTML' paragraph</script>";
return str_replace(array("\r", "\n"), '', $return);
My questions: (1) Is there some obviously better way of writing this code that just isn't occurring to me; and (2) how does the browser deal with the fact that there are two sets of \script\ tags nested inside of each other? (For some reason the code doesn't work and I am guessing that this is what is causing it, but I am not sure).
Answer to question 1:
You could just write your normal HTML and then insert the PHP values inside of it, without using a heredoc, like so:
<?php $obj = new Custom_Object(); ?>
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>"+<?php {$obj->print()} ?>+"</div>");
dialog.dialog();
});
</script>
Answer to question 2:
The second script tag is not being nested inside of the first, it just seems like it. The second script tag is actually being inserted in a completely different place in the DOM by jQuery after your code is interpreted.
If you think it may be getting interpreted incorrectly, you should try wrapping your JavaScript in CDATA tags and escaping quotes properly inside of the string generated by PHP.
You can achieve a lot more stability by simply "closing" your php tag and re-opening it later in the document.
So for instance, you could have:
<?php
$obj = new Object();
?>
<input type="button" id="button1">
<script>
$("#button1").button().click(function(){
var dialog = $("<div><?php $obj->print(); ?></div>");
dialog.dialog();
});
</script>
Just remember that what ever you output from $obj->print(); will need to have double-quotation marks escaped
Most modern browsers are able to work very well with more than 1 tag.
I'd also advise that you set the script type by changing your opening tag to .

how to call a onclick function in <a> tag?

I want to open a new window on click of 1
$leadID = "<a href='javascript:onclick=window.open(lead_data.php?leadid=1, myWin, scrollbars=yes, width=400, height=650);'>1</a>";
It is not showing me error. Is there any other way to open new window?
Here is the fiddle
http://jsfiddle.net/ankurdhanuka/uwypv/
Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.
Example:
function newwin() {
myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}
See how to call it from your anchor tag
<a onclick='newwin()'>Anchor</a>
Update
Visit this jsbin
http://jsbin.com/icUTUjI/1/edit
May be this will help you a lot to understand your problem.
Fun! There are a few things to tease out here:
$leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
<a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: Google homepage.
You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write Activate me to reload when anything is clicked.
Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: Google homepage.
Hope those are useful.
You should read up on the onclick html attribute and the window.open() documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
JSFiddle: http://jsfiddle.net/TBcVN/
Use the onclick as an attribute of your a, not part of the href
<a onclick='window.open("lead_data.php?leadid=1", myWin, scrollbars=yes, width=400, height=650);'>1</a>
Fiddle: http://jsfiddle.net/Wt5La/

Passing a URL to a Javascript function

I've spent a while going through numerous similar questions, but based on the answers given, I'm lead to believe I have this setup correctly - but it's not working, and I'm not sure why.
I'm a newbie with Javascript/jQuery, so it's very possible (or probable!) that I'm missing something completely obvious here.
I have a page with a large 'main' div, and I'm loading content into that using jQuery .load via the navigation. That all works fine. However, some of the target pages are data-heavy, so I'm trying to integrate something in between to indicate to the user that the page is loading. Because there are numerous navigation elements, rather than having multiple functions (i.e one for each navigation element) I'm trying to do it in a single function, like so...
<script type="text/javascript">
function loadPage(pgurl) {
$('#main').html('<p align="center">Loading...</p>');
$('#main').load(' +pgurl+ ');
}
</script>
The problem I have is the onclick within the navigation. Prior to this, I had the .load within the onclick (i.e onclick="$('#main').load('/pages/testpage/');") and that worked fine. Now I'm firing the loadPage function via onclick, it's loading a black page (which firebug tells me is the site root).
Here's my onclick code;
<a onclick="loadPage('/pages/testpage/');return false;">Test</a>
I get no errors returned. I can only assume that the loadPage function is getting a zero value, rather than /pages/testpage/ - but I have no idea why!
Pointers much appreciated - much head scratching going on here!
It's already a string:
$('#main').load(pgurl);
$('#main').load(' +pgurl+ ');
needs to be
$('#main').load(pgurl);
You should probably write it as one line to prevent the second look up.
function loadPage (pgurl) {
$('#main').html('<p align="center">Loading...</p>').load(pgurl);
}
Is that a typo? Try changing:
$('#main').load(' +pgurl+ ');
to
$('#main').load(pgurl);
Because it seem you're not using the pgurl parameter, this thing in the load brackets is string a text of the variable name :)
$('#main').load(' +pgurl+ ');
use that instead
$('#main').load(pgurl);
Maybe you should look at that if you're not familiar with string concatenation http://www.youtube.com/watch?v=n17aX2TdQRk
You have to change following line // you pass string not a variable //
$('#main').load(' +pgurl+ ');
to
$('#main').load(pgurl);

pictures with Javascript from array

EDIT: I have followed the advice of Happy and Bart Friederichs and it has been really helpful. Instead of using php i am using javascript and the code is now working, but i still have an issue. When I click the button on the page it displays the pic that i want but the button disappears, so i cant cycle though the rest of the pictures in the array. What going on? Any help would be appreciated.
<html>
<head>
<script type="text/javascript">
var picArray=["images.jpg","customLogo.gif.png"];
var count=0;
function changePic(){
document.write("<img src='"+ picArray[count] +"' />");
count++;
}
</script>
</head>
<body>
<button type="button" onclick="changePic()">Click Me!</button>
</body>
</html>
Your changePic() function is a PHP function however when you call onclick="changePic()" you are using HTML to call a Javascript function. If you looked at your debug window in your browser you would see an error saying that changePic does not exist.
You can not use html's onClick to call a PHP, not without either redirecting or calling 'wrapper' function in JS that loads your PHP file with arguments via AJAX and so forth.
You have a few options here.. either put your images into a Javascript array and use the onclick call to grab them from that, if your doing that, you do not even need your iframe you can just print the image directly to the page using document.write. Or, why not just set the source of the iframe to your PHP script with an argument for the array index. So where you have
src=$picArray[count]
Change to
src=whatever.php?image=1
For example. This way would only need to render the iframe once rather than on every click like you are attempting to know, you would just be changing the iframe content.
There are a heap of ways to do what you are trying, let me know if either of the above suggestions work for you.
You need to use ajax to handle the onClick event, this in turn would run a PHP page in the background which could return it a filenmae.
Then ajax / jQuery would change the actual pic
Here is a tutorial covering ajax with php:
http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
Alternatively you can output all the filenames to a java script array:
echo '<script> var picarray = array() ;';
foreach($arrayPic as $pic) ...
Then just access it using js

Categories

Resources