pass img src path to php function through javascript - javascript

<script type="text/javascript">
$(function() {
$('.LSide img').click(function() {
$('.BigImage img').attr("src", $(this).attr("src"));
var img =$('.BigImage img').attr("src").slice(0,-5);
//alert($('.BigImage img').attr("src").slice(0,-5))
//alert(img);
});
});
</script>
I want to pass that var img variable to php function, and call that php function at the click event. does it possible?

You can use an AJAX call to your PHP script and pass the value of img with that call.
What you can't do is mix Javascript code (which is a client side scripting language) and PHP code (which is a server side scripting language)

Of course, you can do that by sending a POST request, and with AJAX it'd be:
$.ajax({
type: "POST",
url: "some.php",
data: { img: img.serialize() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/

In your html file. Call click finction like this:
<img src="a.png" id="BigImage" onclick="click()">
<script type="text/javascript">
function click(){
var a = document.getElementById('BigImage').src; //id of your img tag
$.ajax({
type: "POST",
url: 'b.php',
data: { ch : a },
success: function(data){
alert(data);
}
});
}
</script>
In your b.php file use `$_POST['ch']` as you want
<?php
echo $_POST['ch'];
?>

Related

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

Displaying XML information in HTML from a Public XML source

I'm looking for a very basic way to display one piece of XML data from this public source in html: http://avwx.rest/api/metar.php?station=KTPF
Here is what I have so far, with no luck:
<script type="javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser
});
});
function xmlParser(xml)
{
$(xml).find("Raw-Report")
{
$("#metar-text").append('<marquee class="metar-marquee">' + $(this).find("Raw-Report").text() + '</marquee>');
};
};
</script>
I have a div in the HTML with the id #metar-text that I would like scrolling (hence the conc. marquee tags) I only need to display the Raw-Report text.
Your code require some corrections to work.
<script type="javascript">
$(document).ready(function(){
$.ajax({//this part is OK
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser //note that success receives 3 arguments
});
});
function xmlParser(data, state, xhr)
{
var xml = xhr.responseXML; //xml document is here
if($(xml).find("Raw-Report").text()) //that is exists and not empty
{
$("#metar-text").append('<marquee class="metar-marquee">'
+ $(xml).find("Raw-Report").text()
+ '</marquee>'); //**this** is $.ajax in this context
};
};
</script>

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Get response of ajax when target content loads on document.ready

Hi i've got an ajax post and the response div i want from the other file will be generated after $document_ready function. But the div show empty string when i alert it. Here's my code
var cekJawaban = function(){
var form_data={
kode:$("#code").val(),
id_materi:$("#idmateri").val(),
id_user:$("#iduser").val(),
id_lesson:$("#idlesson").val()
};
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
/*var res = resp;
if(resp=="true")
{
$("#alertsukses").show();
$("#submit").hide();
$("#lanjut").show();
}
else
{
$('#salah').html(resp);
$("#alertsalah").show();
}*/
console.log($(data).find('#mocha').text());
},
error: function(xhr) {
}
});
return false;
};
And here's the target url file:
<!DOCTYPE html>
<html>
<head>
<script src="<?php echo base_url('assets/jquery-2.0.3.min.js')?>"></script>
<script src="<?php echo base_url('assets/expect/jquery.expect.min.js')?>"></script>
<script src="<?php echo base_url('assets/mocha/mocha.js')?>"></script>
<link href="<?php echo base_url('assets/mocha/mocha.css') ?>" rel="stylesheet">
</head>
<body>
<script>mocha.ui('bdd');
mocha.reporter('html');</script>
<div id="mocha"></div>
<?php echo $code; ?>
<div id="cek">
</div>
<script type="text/javascript">
describe("Index", function () {
it("Harus punya div",function(){
fn();
})
})
mocha.run();
$(document).ready(function(){
var notif=""
if($('.error').length>0)
{
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
else
{
notif="pass";
}
$('#cek').text(notif);
});
var fn = function(){
$expect('body').to.exist('Jangan lupa buat body')
.and.to.have.children('p', "Jangan lupa buat p");
};
</script>
</body>
</html>
I think this is not possible, javascript is executed on client side and if you're requesting the page by ajax you will get only the static content of it. You must consider to change the work flow of your code and stick to dynamic content generation of the target url on the server-side code.
if you pursue this workflow you may get the content and also the javascript code which I think you don't want
Instead of putting your javascript document.ready() function in the "target url file", you can put the javascript code into the success-function of the Ajax call.
So you call the url, the url returns your content, and after content has been returned you can execute javascript code in the success()-function.
Example:
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
//Call your document.ready() here instead.
var notif=""
if($('.error').length>0){
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
}
});

Deleting a file with ajax javascript and php

I am creating a page where you can upload files and delete them.
My upload is working fine and my download also.
But i cant get my delete working, i want to have the delete using AJAX and a possible confirm box but when i click my button now it doesnt do anything.
The formatoverzicht.php and ajax.php are in the main folder and the files that need to be deleted are in a uploads folder in side the main folder.
Here is my code.
Formatoverzicht.php
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$('.delete-btn').click(function(filename) {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
The Button:
<button data-file="<?php echo $file ?>" class="delete-btn">Delete</button>
Ajax.php:
<?php
if (isset($_POST['filename'])) {
if (unlink(htmlentities( $_POST['filename']))) {
echo "success";
}
}
?>
I am trying to get this fixed for a couple of days now but it still doesnt work.
EDIT:
I am not using this code:
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename': filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
})
});
</script>
and i now get: event.returnValue is deprecated. Please use the standard event.preventDefault() instead. as an error. But the code still doesnt delete or do anything.
It is because filename is totally undefined. You should use something like this:
<script type="text/javascript">
$('.delete-btn').click(function() {
var filename = $(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename' : filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
Shouldn't
$('.delete-btn').click(function(filename)
be:
$('.delete-btn').click(function(file) ?
Or retrieve the filename inside the anonymous function like:
$(this).attr('data-file'); ?
<script type="text/javascript">
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
try doing it on('click'), also your filename is not passed to function.
Try this,
HTML:
<button data-file="<?php echo base64_encode($file); ?>" class="delete-btn">Delete</button>
ajax.php
<?php
if (isset($_POST['filename'])) {
$file = base64_decode($_POST['filename']);
if(is_file($file)){
if (unlink($file)) {
echo "success";
}
}else{
echo "there is no file found (". $file.")";
}
}
?>
Your button click is not handled because the javascript is not triggered. You need to wrap your javascript in jQuery 'ready()' statement, like so:
$( document ).ready(function() {
// your stuff
});
Then you should set your filename variable, as suggested by the others, like so:
filename=$(this).attr('data-file');
instead of passing it directly to the function...
Also, check that the filename that is send to ajax.php matches the original filename. The path should also match off course, since deleting is a filesystem action. Either use the full system path when deleting (or a relative path) or make sure that ajax.php is inside the same directory as the file you want to delete

Categories

Resources