/    Sign up×
Community /Pin to ProfileBookmark

How to call php function with ajax

Hi,
I am trying to learn php and ajax. Cannot figure out why this code not working?This message is only example.
I wish to run php script with ajax using button1 click.If someone have enough time to show me right way.Thank you.

[code]$(function(){
$(“#button1”).click(function(){

$.ajax({
url: ‘index.php’,
type: ‘POST’,
data: { action: “1”},
success: function(response) { console.log(response); }
});
});
});[/code]

[code]
<?php

if (isset($_POST[‘action’ == “1”])) {
$message = “Hello world”;
echo “<script type=’text/javascript’>alert(‘$message’);</script>”;
}
?>[/code]

to post a comment

22 Comments(s)

Copy linkTweet thisAlerts:
@NogDogFeb 27.2020 — > @Ahmo#1615369 if (isset($_POST['action' == "1"])) {

That needs to be:
<i>
</i>if(isset($_POST['action']) and $_POST['action'] == "1") {
Copy linkTweet thisAlerts:
@SempervivumFeb 27.2020 — Your PHP is faulty, should read like this:
if (isset($_POST['action']) &amp;&amp; $_POST['action'] == "1") {
$message = "Hello world";
echo "&lt;script type='text/javascript'&gt;alert('$message');&lt;/script&gt;";
}

However echoing javascript and executing it on the client may be the reason of confusion and issues. I recommend not to do so.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Thanks guys for your help.Nothing happened.

> However echoing javascript and executing it on the client may be the reason of confusion and issues. I recommend not to do so.

So how can i update Select (listBox1) without refreshing page?

This example could help me to update select (listBox1) with files from directory,without refreshing page.

Hire i have php code ,thanks to Sempervivum.

&lt;?php<br/>
//<br/>
$dir = './osaasto1/sunnuntai/';<br/>
// add directory as a data parameter to the select<br/>
echo '&lt;select name="listBox1" id="listBox1" class="listBox" multiple data-dir="' . $dir . '" &gt;';<br/>
// add filesnames from directory in to select (listBox1)<br/>
$files = glob('./osaasto1/sunnuntai/<EM>*.*</EM>');<br/>
foreach ($files as $file) {<br/>
echo "&lt;option&gt;".pathinfo($file, PATHINFO_BASENAME)."&lt;/option&gt;";

}<br/>
?&gt;<br/>
&lt;/select&gt;


I am trying run this cod with ajax if is possible to avoid page refreshing.
Copy linkTweet thisAlerts:
@SempervivumFeb 28.2020 — I recommend the following procedure:

Create an empty select in your HTML:
&lt;select id="listBox1" name="listBox1"&gt;&lt;/select&gt;

Then echo only the options in your PHP:
&lt;?php
//
$dir = './osaasto1/sunnuntai/';
// add directory as a data parameter to the select
// echo '&lt;select name="listBox1" id="listBox1" class="listBox" multiple data-dir="' . $dir . '" &gt;';
// echo filesnames from directory as options
$files = glob('./osaasto1/sunnuntai/.');
foreach ($files as $file) {
echo "&lt;option&gt;".pathinfo($file, PATHINFO_BASENAME)."&lt;/option&gt;";
}
?&gt;


Then on the client add these options to the select:
$.ajax({
url: 'index.php',
type: 'POST',
data: { action: "1"},
success: function(response) {
console.log(response);
// add response (options) to listbox:
$('#listBox1').append(response);
}
});


(not tested)
Copy linkTweet thisAlerts:
@VITSUSAFeb 28.2020 — @Sempervivum#1615392 It's working :)
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Yes it is true.Thank you Sempervivum.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — @Sempervivum#1615392

Now i have new problem :)

missing

echo '&lt;select name="listBox1" id="listBox1" class="listBox" multiple data-dir="' . $dir . '" &gt;';

I need data-dir="' . $dir . '" so i can open image from listBox in canvas.

old javascript working code:

$(function(){
<br/>
canvas = document.getElementById("canvas")<br/>
context = canvas.getContext("2d")<br/>
document.getElementById('listBox1').addEventListener('change', function(e) {<br/>
context.clearRect(0, 0, context.canvas.width, context.canvas.height);<br/>
img = new Image();<br/>
// compose relative path of the image and assign it to the src attribute<br/>
img.src = this.getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'<br/>
img.onload = () =&gt; {<br/>
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);<br/>
// get the top left position of the image<br/>
var x = (canvas.width / 2) - (img.width / 2) * scale;<br/>
var y = (canvas.height / 2) - (img.height / 2) * scale;<br/>
context.drawImage(img, x, y, img.width * scale, img.height * scale);

// unselect rest of listBoxes<br/>
$("#listBox6").val([]);<br/>
$("#listBox5").val([]);<br/>
$("#listBox4").val([]);<br/>
$("#listBox3").val([]);<br/>
$("#listBox2").val([]);<br/>
$("#listBox7").val([]);

} <br/><br/>
e.preventDefault(); <br/><br/>
});


});
Copy linkTweet thisAlerts:
@SempervivumFeb 28.2020 — No problem, simply add the directory to the option:
&lt;?php
//
$dir = './osaasto1/sunnuntai/';
// add directory as a data parameter to the select
// echo '&lt;select name="listBox1" id="listBox1" class="listBox" multiple data-dir="' . $dir . '" &gt;';
// echo filesnames from directory as options
$files = glob('./osaasto1/sunnuntai/.');
foreach ($files as $file) {
echo '&lt;option data-dir="' . $dir . '"&gt;'.pathinfo($file, PATHINFO_BASENAME).'&lt;/option&gt;';
}
?&gt;

and read it in the javascript like this:
img = new Image();
// compose relative path of the image and assign it to the src attribute
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'


BTW: It would make the PHP more friendly to modifications if you use the variable for the parameter of glob either:
[code]$files = glob($dir .'*');[]
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — I did as you said in PHP and javascript but wont open image.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — @Sempervivum#1615407

I did as you said in PHP and javascript but wont open image.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — &lt;?php
<br/>
<i> </i><CODE>if (isset($_POST['action']) &amp;&amp; $_POST['action'] == "1") {
<i> </i> $dir = './osaasto1/sunnuntai/';
<i> </i> $files = glob($dir .'*');
<i> </i> //$files = glob('./osaasto1/sunnuntai/*.*');
<i> </i> foreach ($files as $file) {
<i> </i> echo '&lt;option data-dir="' . $dir . '"&gt;'.pathinfo($file, PATHINFO_BASENAME).'&lt;/option&gt;';</CODE>
}<br/>
}<br/>
?&gt;


$(function(){
<br/>

canvas = document.getElementById("canvas")<br/>
context = canvas.getContext("2d")<br/>
document.getElementById('listBox1').addEventListener('change', function(e) {<br/>
context.clearRect(0, 0, context.canvas.width, context.canvas.height);<br/>
img = new Image();<br/>
// compose relative path of the image and assign it to the src attribute<br/>
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'<br/>
img.onload = () =&gt; {<br/>
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);<br/>
// get the top left position of the image<br/>
var x = (canvas.width / 2) - (img.width / 2) * scale;<br/>
var y = (canvas.height / 2) - (img.height / 2) * scale;<br/>
context.drawImage(img, x, y, img.width * scale, img.height * scale);
<br/>
<br/>
//strech image<br/>
//context.drawImage(img, (canvas.width / 2) - (img.width / 2), 0, img.width, canvas.height);
<br/>
// unselect rest of listBoxes<br/>
$("#listBox6").val([]);<br/>
$("#listBox5").val([]);<br/>
$("#listBox4").val([]);<br/>
$("#listBox3").val([]);<br/>
$("#listBox2").val([]);<br/>
$("#listBox7").val([]);

} <br/><br/>
e.preventDefault(); <br/><br/>
});
Copy linkTweet thisAlerts:
@NogDogFeb 28.2020 — @Ahmo#1615410

Note that if you surround your code blocks here with ... BBCode tags, it will be formatted much more nicely. (The back-ticks are just for in-line text that you want to be mono-spaced.
Copy linkTweet thisAlerts:
@SempervivumFeb 28.2020 — I created testfiles and this code works for me:

HTML/JS
&lt;select id="listBox1"&gt;&lt;/select&gt;
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;
&lt;script&gt;
$.ajax({
// adjust this according your filename:
url: 'thread319-ajax-webdev-2.php',
type: 'POST',
data: { action: "1" },
success: function (response) {
console.log(response);
// add response (options) to listbox:
$('#listBox1').append(response);
}
});
&lt;/script&gt;
&lt;script&gt;
$(function () {
canvas = document.getElementById("canvas")
context = canvas.getContext("2d")
document.getElementById('listBox1').addEventListener('change', function (e) {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
img = new Image();
// compose relative path of the image and assign it to the src attribute
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'
img.onload = () =&gt; {
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);

<i> </i> // unselect rest of listBoxes
<i> </i> // $("#listBox6").val([]);
<i> </i> // $("#listBox5").val([]);
<i> </i> // $("#listBox4").val([]);
<i> </i> // $("#listBox3").val([]);
<i> </i> // $("#listBox2").val([]);
<i> </i> // $("#listBox7").val([]);

<i> </i> }

<i> </i> e.preventDefault();

<i> </i> });

<i> </i> });


PHP
&lt;?php
// adjust this according to your path:
// $dir = './osaasto1/sunnuntai/';
$dir = './images/';
$files = glob($dir . '*');
foreach ($files as $file) {
echo '&lt;option data-dir="' . $dir . '"&gt;' . pathinfo($file, PATHINFO_BASENAME) . '&lt;/option&gt;';
}
?&gt;
Note that you have to adjust the directory $dir in the PHP script and the filename of your PHP script in the ajax call.

If it doesn't work for you please take a look at the console if it shows error messages.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Thanks for information. I didn't know this.

[code] $(function(){


canvas = document.getElementById("canvas")
context = canvas.getContext("2d")
document.getElementById('listBox1').addEventListener('change', function(e) {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
img = new Image();
// compose relative path of the image and assign it to the src attribute
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'
img.onload = () => {
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);



//strech image
//context.drawImage(img, (canvas.width / 2) - (img.width / 2), 0, img.width, canvas.height);


// unselect rest of listBoxes
$("#listBox6").val([]);
$("#listBox5").val([]);
$("#listBox4").val([]);
$("#listBox3").val([]);
$("#listBox2").val([]);
$("#listBox7").val([]);

}

e.preventDefault();

});`[code]
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — @Sempervivum#1615412

I made new fresh index.php file and i did like this.

Please try is it working.

I am getting same problem.

In terminal no errors:

[Fri Feb 28 18:53:10 2020] my ip adress+port Accepted

[Fri Feb 28 18:53:10 2020] my ip adress+port [200]: POST /images/image1.png

[Fri Feb 28 18:53:10 2020] my ip adress +port Closing

but won't appear in canvas.

[code]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<select id="listBox1" name="listBox1"></select>
<canvas id="canvas" style="border-style: double"></canvas>
<input type="submit" id="button1">

<?php
// adjust this according to your path:
$dir = './images/';
$files = glob($dir . '*');
foreach ($files as $file) {
echo '<option data-dir="' . $dir . '">' . pathinfo($file, PATHINFO_BASENAME) . '</option>';
}
?>


<script>
$(function(){
$("#button1").click(function(e){
$.ajax({
// adjust this according your filename:
url: 'index.php',
type: 'POST',
data: { action: "1" },
success: function (response) {
console.log(response);
// add response (options) to listbox:
$('#listBox1').append(response);
}

});
e.preventDefault();
});
});

</script>
<script>
$(function () {
canvas = document.getElementById("canvas")
context = canvas.getContext("2d")
document.getElementById('listBox1').addEventListener('change', function (e) {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
img = new Image();
// compose relative path of the image and assign it to the src attribute
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value; // Hire is 'data-dir'
img.onload = () => {
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);

// unselect rest of listBoxes
// $("#listBox6").val([]);
// $("#listBox5").val([]);
// $("#listBox4").val([]);
// $("#listBox3").val([]);
// $("#listBox2").val([]);
// $("#listBox7").val([]);

}

e.preventDefault();

});

});
[code]

Copy linkTweet thisAlerts:
@SempervivumFeb 28.2020 — Is the directory correct?

`$dir = './images/';</C><br/>
Previously you used a different one:<br/>
<C>
$dir = './osaasto1/sunnuntai/';`
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Yes.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — I am testing but path is not problem

I have images in path and images are not empty😀
Copy linkTweet thisAlerts:
@NogDogFeb 28.2020 — Don't you need that PHP block to be inside of the &lt;select&gt;...&lt;/select&gt; block?
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Yes sir!

i feel so shame.No words......

Thank you guys for your time and effort.
Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — @NogDog#1615419

PHP block must be in input so we can update listBox1, if is in select block then we cannot update listBox1

Hire is working HTML-PHP code:

&lt;canvas id="canvas" style="border-style: double"&gt;&lt;/canvas&gt;
&lt;input type="submit" id="button1"&gt;
&lt;?php
if (isset($_POST['action']) &amp;&amp; $_POST['action'] == "1") {
$dir = './images/';
$files = glob($dir . '*');
foreach ($files as $file) {
echo '&lt;option data-dir="' . $dir . '"&gt;' . pathinfo($file, PATHINFO_BASENAME) . '&lt;/option&gt;';
}
}
?&gt;
&lt;select id="listBox1" name="listBox1"&gt;&lt;/select&gt;



Hire is working Jquery-Ajax code:

$(function(){
$("#button1").click(function(e){
$("#listBox1").val([]);
$.ajax({
url: 'index.php',
type: 'POST',
data: { action: "1"},
success: function(response) {
console.log(response);
// add response (options) to listbox:
$('#listBox1').append(response);
}
});
e.preventDefault();
});
});


Hire is working javascript code:

$(function(){
<br/>
canvas = document.getElementById("canvas")
context = canvas.getContext("2d")
document.getElementById('listBox1').addEventListener('change', function(e) {
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
img = new Image();
// compose relative path of the image and assign it to the src attribute
img.src = this.options[this.selectedIndex].getAttribute('data-dir') + this.options[this.selectedIndex].value;
img.onload = () =&gt; {
var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
// get the top left position of the image
var x = (canvas.width / 2) - (img.width / 2) * scale;
var y = (canvas.height / 2) - (img.height / 2) * scale;
context.drawImage(img, x, y, img.width * scale, img.height * scale);
<br/>
} <br/>
e.preventDefault(); <br/>
});

Copy linkTweet thisAlerts:
@AhmoauthorFeb 28.2020 — Please if you can tell me how to mark this topic [RESOLVED]
×

Success!

Help @Ahmo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...