Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: how to open an url in new tab with passing post data to that url

Tags:

jquery

post

php

I have a php file localhost/~user/sample.php file which gets data from post method.

<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;

I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.

I can use get method in php, but the number of variables are more

like image 788
Santhosh Avatar asked Oct 23 '25 16:10

Santhosh


2 Answers

I would probably go for using a form, like so:

<form action="sample.php" method="post" target="_blank">
  <input type="hidden" name="name1" />
  <input type="hidden" name="name2" />
  ...
  <input type="hidden" name="name20" />
  <input type="submit" value="Go to page">
</form>

This is the most cross-browser JS-failsafe basic html version way of achieving this task that I can think of...

If you need to dynamically add form fields to the form, I believe you will find this question: Jquery - Create hidden form element on the fly handy. Copying the modified answer:

$('<input type="hidden" name="myfieldname" value="myvalue">').appendTo('form');
like image 173
Noy Avatar answered Oct 26 '25 07:10

Noy


One way would be to dynamically create a hidden form and then submit it, make sure you encode the input:

var params = [['someKey0', 'someValue0'], ['someKey1', 'someValue1'], ['someKey2', 'someValue2'], ['someKey3', 'someValue3']];

var inputs = $.map(params,function(e,i){
  return '<input type="hidden" name="'+e[0]+'" value="'+encodeURIComponent(e[1])+'"/>';
});
var form ='<form action="sample.php" id="hidden-form" method="post" target="_blank">'+inputs.join('')+'</form>';

$('#hidden-div').html(form);
$('#hidden-form').submit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-div"></div>
like image 25
Wesley Smith Avatar answered Oct 26 '25 07:10

Wesley Smith