How can I use session in script? - javascript

I can write out the images src with this script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("img.film").click(function () {
alert($(this).attr('src'));
});
});
</script>
But how can I fill it to a session, which I can use in php?
I know that this row has to be changed, but for what?
alert($(this).attr('src'));
Thanks.

Well, if you want it to be read by PHP, you can just use a cookie.
$(document).ready(function () {
$("img.film").click(function () {
document.cookie = "image_src=" + $(this).attr('src');
});
});
Then, on PHP, just get the cookie from the cookie variable:
$_COOKIE['image_src'];

you need to make for example an ajax call to set your php session like this:
$(document).ready(function () {
$("img.film").click(function () {
var src = $(this).attr('src')
$.ajax({
type: 'POST',
url: "set_session.php",
data:{your_var:src},
success: function(resultData) {
alert("Save Complete") }
});
});
});
and in the same directory you need to create a file called set_session.php
session_start();
$_SESSION['your_key'] = $_POST['your_var'];
It's important that session_start() is in the first line of both file

Related

send an element through a event

I want simply to send an element via a event so that to catch it as a parameter in a servlet, but NOT from the regular Form's button.
I would appreciate a suggestion.
<script>
$(document).ready(function () {
$('#idSelect').change(function () {
$.post("SelectChange",$('#idSelect'), function () {
});
});
});
</script>
Like so, capture the value on change, then send it to the php file.
Access in the PHP with $_POST['select_data'];
$(document).ready(function () {
$('#idSelect').change(function () {
var select_value = $("#idSelect").val();
$.ajax({
type: "POST",
url: '/var/www/file-receiving-data.php',
data: ({ select_data: select_value}),
success: function(data) {
console.log("successfully sent to php file");
}
});
});
});
So, with the 1st answer (without which no chance to get it), til fix the other simpler permanently, the working solution is:
In servlet:
String val = request.getParameter("val");
In jsp, append the value to the url, as follows:
<script>
$(document).ready(function () {
$('#idSelect').change(function () {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "SelectChange?val="+$('#idSelect').val(), true);
xhttp.setRequestHeader("String", "application/x-www-form-urlencoded");
alert("send de POST: "+$('#idSelect').val());
xhttp.send();
});
});
</script>

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>

Download a file in the browser

On my web page I have links for downloading mp3 files.
Upon user click, I make an ajax call and create an mp3 file on the server.
I return the path of the file to the script but now, how do I make it download the user system?
<SCRIPT TYPE="text/javascript">
function voice(id){
$.ajax({
url:'/download/',
type:"POST",
data:{'id':id,'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()},
success:function(return_data) {
alert(return_data['url']);
},
error: function(){
alert("Some Error");
}
});
}
</SCRIPT>
I get the url of the mp3 file in alert but how to download it ?
Thank you.
Create an anchortag in your HTML which is hidden using CSS
Hidden
And in your javascript
<SCRIPT TYPE="text/javascript">
function voice(id){
$.ajax({
url:'/download/',
type:"POST",
data:{'id':id,'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()},
success:function(return_data) {
var url= return_data['url'];
$('.hiddenUrl').attr('href',url) //adding value to the href attribute
$('.hiddenUrl').attr('download','any_filename.mp3');
$('.hiddenUrl')[0].click();
},
error: function(){
alert("Some Error");
}
});
}
</SCRIPT>
You can do window.location = return_data['url']; assuming that you have an url which starts with http... This approach is equivalent of the user clicking the link to the mp3. Another approach would be to create an iframe with src set to the newly created link. Using this method the user's browser will prompt to download the file without having to change the location (navigating away from the current page). I recommend the first approach.
This should work:
<SCRIPT TYPE="text/javascript">
function voice(id){
$.ajax({
url:'/download/',
type:"POST",
data:{'id':id,'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()},
success:function(return_data) {
window.location.href = return_data['url'];
},
error: function(){
alert("Some Error");
}
});
}
</SCRIPT>
I think this will work
<SCRIPT TYPE="text/javascript">
function voice(id){
$.ajax({
url:'/download/',
type:"POST",
data:{'id':id,'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()},
success:function(return_data) {
var url= return_data['url'];
window.location.assign(url);
},
error: function(){
alert("Some Error");
}
});
}
</SCRIPT>

Loading all files in jQuery ajax before success function PHP jQuery

I have a script like this.
The jQuery ajax loads all my files with no issues.
The ajax_load_books.php file have lot of css and js(inline edit, sliders etc.) files in it.
The problem is:
How to load all the files before the success function so that the user can see the loader_div message untill all the files are loaded.
In other words - Load all the js/css files and proceed with the success function.
Even I have checked with .load() function. Could someone redefine the below code .
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
$("#loader_div").show();
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Thanks,
Kimz
For the css files, you can find them using jQuery.parseHTML() function, but the <script> will be stripped with this so instead we would have to use regex for the <script> tags.
Try:
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$("#loader_div").show();
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
//parsing <link>
var $str = $('<output>');
//loading html into fake tag
$str.load("ajax_load_books.php");
//now $str includes all your page code
temp = $.parseHTML(str);
$.each(temp, function (i, el) {
//finding the <link> tag
if (el.nodeName == 'LINK') {
//appending it to the <head> tag
$('head').append("<link rel='stylesheet' href='" + el.getAttribute('href') + "'>");
}
});
//for script we will use regex
var pattern = /<script[^>]+?>.*?<\/script>/gi;
var matches = str.match(pattern);
var scripts = "";
for (var i in matches) {
scripts += matches[i];
}
//appending script tag to <head>
$('head').append(scripts);
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Demo
There is a drawback with this, your stylesheets and script code will repeat. If the above code causes issue running because of the repetition, you should place the code of beforeSend() before the AJAX and have a parameter sent from your AJAX function indicating that when an AJAX is called with this parameter, to execute all the HTML except the stylesheets and js scripts.

Ajax to assign src to Iframe Dynamically in MVC3

Hi i am basically new to Ajax and having a tough time writing it..
I want to assign src value to Iframe which is fetched from the database
Table is HobbyMasters
HobbyName
HobbyUrl
I write a function and fetch the url from the table now when i click on Hobbyname which is displayed as link i want that url to be loaded inside the Iframe.
Initially i wrote a javascript:
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
$('iframe').attr('src', "Dancing");
});
}); </script>
But here the src is static and through javascript i am not able to assign fetched value from databse to src attribute
So thought of writing Ajax..
I have tried something but it is incomplete.Please Help me with this:
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl ,
data: { data: filename },
success: function (returndata) {
Here i want to assign the fetched src from function FetchUrlByHobbyName to Iframe src
$('iframe').attr('src', filename);
}
});
});
Function inside the Controller:
[HttpPost]
public ActionResult FetchUrlByHobbyName(string Hobbyurl)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(Hobbyurl);
string url=hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(new{src=url});
return View();
}
If #Url.Action("FetchUrlByHobbyName") returns the url of the hobby , you can do
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl ,
data: { data: filename },
success: function (returndata) {
Here i want to assign the fetched src from function FetchUrlByHobbyName to Iframe src
$('iframe').attr('src', returndata);
}
});
});
The best method would be to return the data associated with json and get the url from the json object
success: function (returndata) {
jsonObj = jQuery.parseJSON( returndata)
$('iframe').attr('src', jsonObj.url);
}

Categories