change an image using ajax request in jquery - javascript

I want to use $.ajax to get any picture from a URL and show it on the page.
It should happen when button is clicked.
$(document).ready( function() {
$("button").click(function(){
$.ajax({url: "index.html", success: function(result){
$("#image").attr("src","test.png");
}});
});
});
HTML Code:
<button type = "button">Click Me</button>
<div>
<img id = "image" src = ""/>
</div>
Edit:
The errors is,

Use a server and serve your file over the http protocol

This works fine. But still I need to use a localserver to run this without the console error mentioned in edit.
$(document).ready( function() {
$("button").click(function(){
var url = 'test.png';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#image").attr("src", url);
});
});
});

Related

Send value in a database through jquery + ajax

I want to store the value "20_2018" (for example) with an id in my database. I want to count clicks on each downloading.
This is what I tried:
<html>
<body>
<a id="20_2018" rel="link1" href="folder.pdf">Download</a>
<script type="text/javascript">
$(document).ready(function(){
$(\'a[rel="link1"]\').click(function() {
$.ajax({
type:'POST',
url: 'send.php', // folder for sending value in id to the database
data: 'id='+$(this).attr("id"), // take the value in the id
async: false
});
return true;
});
</script>
</body>
</html>
Somehow this does not work. How can I implement a click count for downloads?
First, prevent the default action with preventDefault, then send your request. After success, bring them to the file URL.
$(document).ready(function(){
$('a[rel="link1"]').click(function(event) {
event.preventDefault();
// Gets href of the clicked anchor
var href = $(this).attr('href');
$.ajax({
type:'POST',
url: 'send.php',
data: 'id='+$(this).attr("id"),
success: function(){
// After recording click count, bring them there
location.assign(href);
},
error: function(){
alert('failed');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="20_2018" rel="link1" href="folder.pdf">Download</a>

Replace the URL, contents and title without reloading the page

I want to create one page site by change div content with out load new page.
So, I've implemented my code like this:
HTML:
<title>Post title</title>
<body>
<a class="js-post-bt" href="/post/1" data-id="1"></a>
<a class="js-post-bt" href="/post/2" data-id="2"></a>
<a class="js-post-bt" href="/post/3" data-id="4"></a>
<div id="post-container"></div>
</body>
Script
$(function() {
$(".js-post-bt").on("click", function(e) {
var post_id = $(this).attr("data-id");
$.ajax({
url: "post_title.php?id="+post_id,
success: function(data) {
var title = data;
$.ajax({
url: "post.php?id="+post_id,
success: function(data2) {
// how to change url to post/post_id?
document.title = title;
$("#post-container").html(data2);
}
});
}
});
e.preventDefault();
});
});
Is it possible to create only one ajax call and get returned data either title and post data.
ANd how to change browser address to post/post_id after anchor link clicked.
You can use history api in HTML5
Demo -> http://html5demos.com/history
Howto ->
http://diveintohtml5.info/history.html
http://html5doctor.com/history-api/
If you want to make just one ajax call, which is a good idea, you will also need to change the code on your server.
It should respond a json object:
json_encode( array( "title" => $title, "post_data" => $post_data ) );
And you ajax call becomes:
$(function() {
$(".js-post-bt").on("click", function(e) {
var post_id = $(this).attr("data-id");
$.ajax({
url: "post_title.php?id="+post_id,
dataType: "json",
success: function(json_data){
document.title = json_data["title"];
$("#post-container").html(json_data["post_data"]);
}
});
e.preventDefault();
});
});

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>

Why the jQuery colorbox popup is not getting displayed when called through $.ajax() method?

I'm calling a hidden colorbox popup in the $.ajax() method's success: function() but I'm not able to show that. I did the same thing previously but at that time it worked fine, now it's not displaying the specified hidden pop-up. The only difference from this implementation to previous implementation I was using data attrribute of $.ajax() method in the previous implementation. Does that thing is responsible for my current issue? Please help me out in resolving this issue. For your reference I'm putting the necessary code snippets as follows:
<div class="hidden">
<div id="emailinfoPopContent" class="c-popup">
<h2 class="c-popup-header">Email Invoice</h2>
<div class="c-content">
<h3>Invoice has been sent to your email id</h3>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(document).on('click', '#email_url', function (e) {
e.preventDefault();
var post_url = $(this).attr('href');
$.ajax({
url: post_url,
type : 'get',
dataType: 'json',
success: function(data) {
var status = data.status;
var dialog_title = "Email Invoice";
var message = data.msg;
if(status == 'success') {
$.colorbox({
inline:true,
href: "#emailinfoPopContent",
width:666
});
//alert(message);
} else {
$.colorbox({
inline:true,
href: "#emailinfoPopContent",
width:666
});
//alert(message);
}
}
});
});
});
</script>
One more thing I wold like to say is I'm getting the proper response from PHP code in json format, if I show alert instead of colorbox it shows the desired response properly. There are no syntactical errors found in firebug console and I'm using jQuery 1.9
try adding open: true, like:
$.colorbox({
inline:true,
href: "#emailinfoPopContent",
width:666,
open: true
});
You can try something like this. I am not sure about this
var show_html = $('emailinfoPopContent').html();
$.colorbox({html:show_html});

Execute php url with JS

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories