Php onclick javascript window open

Jquery Onclick Send data to new opened window

I know this is a common question but I can’t find any answer. I have a PHP file which contains a link. When that link is clicked, I want to open another page in a new window, and on this newly opened page I want to get the ID attribute of the link clicked on the previous page.

Current page= ‘patientreg.php’
Newpage to open in new window= ‘patient_history.php’
Post data from current page to new loaded page.

function phistory(myVar) < var myurl = '../main/patient_history.php'; $.post(myurl,,function()<>); window.open(myurl,'_blank'); > 
$phid = $_REQUEST["data"]; echo phid; 

The problem is that it is not echoing the data on the next page, but I can see echo with the full new page in the Firebug response tab of the current page.

Also you don’t have to provide a success function if you’re not using it function()<> it’s an optional parameter indicated by the [ ] brackets in the documentation: api.jquery.com/jQuery.post

2 Answers 2

try this, so using a form to send data to your page, and you can have more verbose the anchor element:

$(function() < $('.see-history').bind('click', function(event) < try < window.open('about:blank', 'mynewwindow'); $('#myform').find('#data').val($(this).data('idref')); $('#myform').attr('target', 'mynewwindow').submit(); >catch(e) <> return false; >); >); 

if you need to open a new window for each story, you can create a new window with the name of the element id:

 $('.see-history').bind('click', function(event) < var try < window.open('about:blank', 'mynewwindow_' + id); $('#myform').find('#data').val(id); $('#myform').attr('target', 'mynewwindow_' + id).submit(); >catch(e) <> return false; >); 

Try this instead. For your JavaScript onclick handler:

$phid = $_REQUEST["data"]; echo $phid; 

Your problem is that you are misunderstanding the use of jQuery’s .post() method. It simply retrieves the page (with the specified POST parameters) — it does not modify the page such that when you open it in a new window, it will have your specified ID parameter. I switched it so that it no longer uses jQuery’s .post() , but simply uses the GET parameters by opening the new window with ?data=[YOUR-ID] . The PHP, you’ll notice, stays mostly the same, but I changed the echo statement to include the $ sign before the variable name. That might have been a typo just in the question, but if that’s in your code, it’s part of the problem.

Читайте также:  Красивый зеленый цвет html

Another possibility is to remove the ID from the query string completely, and instead store it as a global variable on the first page, then retrieve that with the window.opener property on the second page, like so:

var pid=0; function phistory(myVar) < pid=myVar; window.open("../main/patient_history.php"); >

Second page (JavaScript):

pid=window.opener["pid"]; alert(pid); //Just to check that it's working 

Источник

how to call a onclick function in tag?

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.

See how to call it from your anchor tag

Update

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 ' to escape the HTML quotes.
  • 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: . 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 ): ;»> . .
  • 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 .

You should read up on the onclick html attribute and the window.open() documentation. Below is what you want.

Use the onclick as an attribute of your a , not part of the href

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

Открытие нового окна при клике

Открытие нового окна при клике

Описание: Очень часто возникает необходимость при клике по ссылке не переходить по соответствующему адресу, а просто открывать новое окно, куда подгружать страницу. Например, при клике по изображению показать его увеличенный размер в новом окне. Именно такой скрипт я выкладываю в этой статье. Он позволяет открыть страницу в новом окне при клике по ссылке с помощью JavaScript. Разумеется, Вы можете это переделать под клик по изображению, по блоку и так далее.

Код JavaScript (вставлять между тегами и ):

Код HTML (вставлять между тегами и ):

Создано 28.04.2011 20:52:05

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 24 ):

    Всё хорошо, но при открытии нового окна также перезагружает и текущую страницу, с этим можно бороться?

    Подправил немного статью. Можете копировать HTML-код. С ним исходная страница не будет перегружаться.

    Спасибо, а можно добавить скрипт появления текста с эфектом печатной машинки, но чтоб не в форме печаталось, и с циклом повторялось.

    Да, можно. Обязательно напишу об этом статью.

    Миш подскажи пожалуйста как сделать открытие такого окна при клике в любом месте страницы, а не только по ссылке Заранее спасибо!

    Добавить onClick в div, который растянут на всю страницу через css (width:100%, height:100%)

    Объясни пожалуйста поподробнее А то я в html чайник

    Это самый простой и очевидный способ — сделать элемент div, который закроет сверху всю страницу, и в него уже добавить onClick. Точно так же как в моём примере добавлено в тег .

    Всё получилось Спасибо за помощь!

    Используйте confirm(), чтобы задать подобный вопрос. Данная функция вернёт ответ пользователя и уже через if можно выполнить определённые действия.

    сейчас попробую!спасибо!значит это все таки реально!

    Михаил — не получается с автоматическим открытием — перехожу на weborder.php — есть ссылка на нее нажимаешь только тогда открывается окно с вопросом, а мне надо бы что бы когда только перешол на эту страницу сразу же открывал вопрос! вот так вот выглядет скрипт function confirmSubmit() оплата уровня

    Михаил огромное спасибо все получилось и работает без блокировки браузера.

    В firefox 18.0.1 нет полос прокрутки, а нужны.

    Уточните как можно преобразовать скрипт, что бы при заходе на страницу первоначально был открыт блок, а далее по клику уже сворачивался и показывался. заранее спасибо.

    Окно открыться при заходе на страницу никак не может.

    Михаил, здравствуйте. А вот если то, что открывается в новом окне, видно только половина материала, возможно туда добавить прокрутку, чтобы увидеть все? А сам скрипт просто спасение.

    Да, можно. Для этого надо добавить scrollbars=yes в параметры.

    Спасибо, Вам большое за Ваши знания.

    А почему ссылка на статью /php-onclick-openwindow.html Это же JavaScript!

    Всё работает, сделал чтобы и прокрутка была. А можно сделать так чтобы открывалось в фоне, чтобы не открывалось поверх основной страницы?

    Spasibo vam bolwoye.Vse rabotayet

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Оцените статью