Jquery post, response in new window - javascript

I have a script that on.DocumentReady posts data to another page. That page responds with some HTML encapsulated in one div tag.
My goal is to have this post response/data open in a new window.
Any hints or clues?
Here is the snippet I created from Dr. Mille's advice.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var packslip_id = 35592;
var po_no = 0018439;
var box_no = 1;
$.post("https://example.com/barcode/generate", { packing_slip: packslip_id, reference: po_no, total_boxes: box_no},
function (data) {
alert(data);
var win=window.open('about:blank');
with(win.document)
{
open();
write(data);
close();
}
});
});

Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});

Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:
Example:
<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
<input type="hidden" name="packing_slip" value="35592" />
<input type="hidden" name="reference" value="0018439" />
<input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>
Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

I did it with an ajax post and then returned using a data url:
$(document).ready(function () {
var exportClick = function () {
$.ajax({
url: "/api/test.php",
type: "POST",
dataType: "text",
data: {
action: "getCSV",
filter: "name = 'smith'",
},
success: function(data) {
var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
w.focus();
},
error: function () {
alert('Problem getting data');
},
});
}
});

Related

Jquery ajax post create a second form on form submit

I have this form:
<form id='form'>
Begin time<input id="begintime" type="text" name="begintime"><br>
End time<input id="endtime" type="text" name="endtime"><br>
<input name="submit" type="submit" value="Submit">
</form>
on my website it looks like this:
the thing is that I don't want the web page to refresh. so I made this ajax post:
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
var begin = $("#begintime").val();
var end = $("#endtime").val();
$.ajax({
type: 'post',
url: '',
data: {begin: begin, end: end},
success: function (result) {
$( result ).appendTo('p');
}
});
});
});
But every time is click on submit this happens:
also I use this to get the data:
<p>
<?php
$begin = $_POST['begin'];
$end = $_POST['end'];
?>
</p>
I have tried this:
$('p').empty();
I put tihs inside of ajax code this is the result is the same. What am I doing wrong? please help. and thank you.
Try the code below instead. It will clear everything inside the p tag and append the form to i
success: function (result) {
$('p').html(result);
}
You should just change the HTML, not append it like so
...
success: function (result) {
$('p').html(result);
}
...

how to update a value in database using jquery when a link is clicked in php

I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

parse title of other urls using jquery

i am looking for a way to get title of urls mentioned in the webpage.
I tried http://urldecoderonline.com/ but it does not provide a way to parse the page.
Just for ex: user enters a url say http://www.google.com in a text input box and on pressing a submit button i would like to alert him with a title of "http://www.google.com"
Any ideas??
you need to use ajax and a php ajax proxy script on your server
i didn't test this, but it should work
ajax_proxy.php
<?php
if(isset($_POST["url"]){
echo file_get_contents($_POST["url"]);
}
?>
js
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "post",
dataType: "text",
url: "ajax_proxy.php",
data: { url: $("#input").val() }
success: function(data){
alert($(data).find("title").html());
}
});
});
});
If the problem is to extract the host part from the URL string, then this is a typical regular expression problem.
If there's something before the first semicolon, that's the protocol. Everything from there up to the forward slash is the host.
Something along the line of:
<http>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function parseUrl(url) {
var regexStringProtocol = '^([A-Za-z]*)://';
var protocolResults=new RegExp(regexStringProtocol).exec(url);
if(protocolResults) {
var protocol = protocolResults[1];
url = url.substring(protocolResults[0].length);
}
else {
var protocol = '';
}
var regexStringHost = '^([^/^?]+)';
var hostResults = new RegExp(regexStringHost).exec(url);
if(hostResults) {
var host = hostResults[1];
}
else {
host = '';
}
alert('Protocol: ' + protocol + '\nHost: ' + host);
// Continue parsing if you care about the part and the parameters
}
$(function() {
$('input').val('http://stackoverflow.com/questions/6715438/parse-title-of-other-urls-using-jquery/6715527#6715527');
$('#parse').click(function() { parseUrl($('input').val());});
}
);
</script>
</head>
<body>
<input type="text" style='width:150mm' />
<br />
<button id="parse">Parse</button>
</body>
</html>
To get title of a href link you can use attr function of jQuery.
$("a").attr("title");
To get titles of all links on page:
$("a").each(function(){
var title = $(this).attr("title");
});

JSON response opens as a file, but I can't access it with JavaScript

In the code below I make a POST request to a servlet that replies in this way:
response.setContentType("application/json");
json = "{success:true,sessionUid:\""+sessionUid+"\"}";
response.getWriter().write(json);
So Firefox opens it like a file and I can see it's ok. Here you have the JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
The problem is that I can't inspect the JSON object. It seems not to exist inside my callback function (also using Firebug). Take a look to the code and alerts.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#loginForm").submit(function(response){
alert("response="+response); //output: "response=[object Object]"
var obj = jQuery.parseJSON(response);
alert("obj.sessionUid="+obj.sessionUid); //doesn't work, Firebug says "obj is null"
if (response.success == true){ //never true
document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp';
}else{
alert("Something went wrong in the login process.");
}
return false;
});
});
</script>
</head>
<body>
<form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post">
<fieldset><legend>Login to Quotero:</legend>
<label>Action:</label><input type="text" name="action" value="login"/><br />
<label>Username:</label><input type="text" name="login-quotero" value="admin"/><br />
<label>Password:</label><input type="text" name="password-quotero" value="admin" /><br />
<label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
EDIT: I also tried to do the same with an AJAX request, wothout success:
$("#ajaxSubmit").click(function () {
$.ajax({
type: "GET", //GET or POST is the same for this servlet
url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero",
dataType: "json",
success: function (response) {
alert("response=" + response);
var obj = jQuery.parseJSON("" + response);
alert("obj.sessionUid=" + obj.sessionUid);
if (response.success == true) {
document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp';
} else {
alert("Something went wrong in the login process.");
}
}
});
return false;
});
This is not valid JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
This is valid JSON:
{"success":true,"sessionUid":"D07WC15R7LFRFRGPF4P5"}
In JSON the keys must always be quoted. See DEMO.
I think you have mixed up ajax with submit. submit is just simply an event, when form is submitted do the following. then you can
$("#loginForm").submit(function(){
var post_data = $(this).serialize();
$.ajax({
url: '',//url of the php file that handles the forms
type: 'GET',
dataType:'json',
data:post_data,//this are the query strings, e.g. ?q=blabla&s=blabla
success:function (data){//if page was 200 or successfully loaded
alert(data.sessionUid);
// do what ever you wish with the data here
},
error: function (){
alert('Page failed to load');
}
})
return false;
});

Categories