how to call a php file from javascript? - javascript

Hi I am very new to JavaScript, looking for some help. I have a form, shown below. When the user gives input and clicks submit, I want to call a php file (shown below also) to be invoked and return a hello. Here is the code I have tried, though it is not working as intended.
<html>
<head>
<script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text" />
<input id="name-submit" type="submit" value="submit" onclick="post()"/>
</form>
<div id="result"></div>
</body>
<script>
function post() {
var hname = $('input#name-typed').val();
$.post('dat.php',{name: hname},function(data) {
$('div#result').html(data);
});
}
</script>
</html>
The PHP file dat.php looks like this:
<?php echo "hello";?>
As in my first paragraph, can anyone suggest any changes I should make?

Try this:
you can change dat.php to say:
<?php
$name = $_POST['name'];
echo "Hello ".$name;
?>
And then your html file would be:
Notice that the button type is changed to a normal button so that it just execute the function rather than submitting the form.
<html>
<head>
<script type='text/javascript' src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<form>
<input id="name-typed" type="text" />
<button type="button" onclick="post()">Submit</button>
</form>
<div id="result"></div>
</body>
<script>
function post() {
$.ajax({
type: "POST",
url: "dat.php",
data: { name: $('#name-typed').val()
},
success: function(response) {
$('#result').html(response);
}
});
}
</script>
</html>

I haven't test but something like this:
$('form').submit(function(){
post()
return false;//block the reload of the page
})
In fact I think you just forget the return false. remvove the onclick if you use my answer

Related

how to echo the ajax data with the help of php?

I trying to print the data which was entered by the user, and transfer that through ajax and trying to print or echo it with the help of php code, but I could not do that. enter code here
this is my code:
<html>
<head>
<title>
test ajax
</title>
<script src="jquery.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<script>
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
</script>
</body>
</html>
<?php
extract($_POST);
if(isset($_POST["c"])) {
echo $_POST["c"];
}
?>
I think that, I have the problem with the php code. please give me any solution.
Try it like this
This is your Html
<html>
<head>
<title>
test ajax
</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type = "text" id = "a" > <br>
<input type = "button" id = "b" value = "display" >
</form>
</body>
</html>
<script>
$(document).ready(function(){
$('#b').click(function() {
let a = $('#a').val();
//alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {c: a},
success: function(response) {
alert(response);
}
});
});
});
</script>
This is your same_file.php
<?php
//extract($_POST); code works even without this
if(isset($_POST["c"])) {
echo $_POST['c'];
}
?>
Not sure if your jquery library call is ok so I called the one on the web instead. Also your success:function() was not doing anything which is why you didn't receive anything.
Also always format your code with some indention so that it can be easier to read and comprehend by others.
You probably want to echo before the body is rendered.
But in true, unless you need to process the data the user sends, you don't need PHP at all.
And in truth, you probably don't need jQuery as well, fetch() works just fine.
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
<?php
if (isset($_POST["c"]))
{
// print/echo user data send from form.
echo $_POST["c"];
// stop the script from rendering the html below.
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<!-- add script element with js code here -->
</body>
</html>

Button onclick event in Javascript does not trigger alerts

I'm trying to make a simple register/login system but when I press the button for both, it doesn't do what I need it to do.
I put
alert("I work!");
at the beginning of each function supposed to work to see if it actually gets triggered but it doesn't. I also checked if the onclick events for both are referenced correctly and they are. I even tried to copy the actual scripts into the html file to ensure that it's not a reference issue. At this point, I'm really stuck, and if this is some syntax error, it doesn't alert me and I'm not aware of any.
The codes are:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Opportunities</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/js/script.js"></script>
</head>
<body>
<p>Uwu</p>
<form>
<p>Username <input type="text" class="username" /></p>
<p>Password <input type="password" class="password" /></p>
<button onclick="loginUser()">Login</button>
</form>
<p>Not yet registered? Click here to create an account. </p>
</body>
</html>
registration.html:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src=/js/script.js"></script>
</head>
<body>
<p>Registration page</p>
<form>
<p>Username <input type="text" class="username" /></p>
<p>Password <input type="password" class="password" /></p>
<button onclick="registerUser()">Register</button>
<!--onclick event doesn't work-->
</form>
<p>Click here to go back.</p>
</body>
</html>
and script.js:
var url = "http://localhost:8888";
function test(){
console.log('hello');
}
function registerUser(){
alert("I work!");
var username = document.getElementbyClassName("username");
var password = document.getElementbyClassName("password");
$.ajax{(
url: url + "/register",
method: "post",
data: {
username: username[0].value,
password: password[0].value
}
success: function(respons){
alert(response.message);
}
}).error(function(response){
alert(response.message);
});
}
function loginUser(){
alert("I work!");
var username = document.getElementbyClassName("username");
var password = document.getElementbyClassName("password");
$.ajax({
url: url + "/login",
method: "post",
data: {
username: username[0].value,
password: password[0].value
}
}).success(function(response){
alert(response.message);
}).error(function(response){
alert(response.message);
});
}
Whenever I press the buttons for each, it just clears the texts in my inputs but doesn't launch an alert like I intend to. Please do tell me what I should check regarding this. Thank you.
I think your script is not loaded
Remove the frist backslash ('/') from
<script type="text/javascript" src=/js/script.js"></script>
If you are using your browser I would try first that you dont have any "popup" script blocking extensions, I had the same issue and the issue was chrome popup js blocker cause simple adblocker doesnt work for some sites.
cheers
Looks like a typo in the registerUser() function try changing the ajax call to
$.ajax({
url: url + "/register",
method: "post",
data: {
username: username[0].value,
password: password[0].value
},
success: function(respons){
alert(response.message);
}
}).error(function(response){
alert(response.message);
});

Executing PHP with HTML Button (jQuery)

i got a website with some buttons and a camerastream which shows a coffee machine. with php function i'm able to set the machine on/off via TCP/IP messages. Now i would like to send on/off commands over button, without refreshing the website. After reading some similar threads, i recognized that the only way is using AJAX.
After pressing Button the Page doesnt refresh but it seems that something in backround get done. But my "Test" String doesnt get show.
Does anyone know whats wrong with my code?
Thanks in advance!
ajax.php
<?php
if($_POST['action'] == 'call_this') {
echo 'TEST';
}
?>
buttonClick.js
function myAjax() {
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
index.php
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
<form>
<input type="submit" name="submit" value="SET ON" onClick="myAjax()">
</form>
....
....
</body>
</html>
Modified Mouad Nejjari code as below and this works
index.php
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
</head>
<body>
<button id="btnTest">Click</button>
<script>
$(document).ready(function () {
$('#btnTest').click(function () {
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
})});
</script>
</body>
</html>
ajax.php
<?php
if($_POST['action'] == 'call_this') {
echo 'TEST';
}
?>
You are using the HTML element input with a type set to submit, this means that on click the page assumes you want to be redirected to the handling page URL normally supplied in the Form tag. You can use the javascript method of PreventDefault() or you can change the element from a form submit to a link like this.
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
SET ON
....
....
</body>
</html>
A link with a javascript href will not try and redirect. Your example left the page before waiting for the php script to return.
Try This, ajax.php :
<?php
if($_POST['action'] == 'call_this') {
echo 'TEST';
}
?>
buttonClick.js :
$(document).ready(function()
{
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
})
})
index.php :
<html>
<head>
<script src="jquery-1.12.0.min.js"></script>
<script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
<form id="form1">
<input type="submit" name="submit" value="SET ON">
</form>
....
....
</body>
</html>

HTML input to php and then back to input

So, I tried everything that I know and I tried to find everywhere but no luck. I want to paste imdb link into (id="id_imdb") and then when I press button (name="b") I want that link to become variable $hjo and then to execute php script get_info_imdb.php and then return variable $slbl into javascript which will set textarea (name="movie_desc") to echo $slbl.
insert-movie.php
<html>
<body>
<?php
global $hjo;
$hjo = "http://www.imdb.com/title/tt1431045/";
include ("get_info_imdb.php");
?>
<form action="insert_movie.php" method="post" enctype="multipart/form-data">
<div>
<div>
<div>Description:</div>
<div><textarea name="movie_desc" rows="7" cols="50" id="id_desc" value="<?php echo (isset($slbl))?$slbl:'';?>"></textarea></div>
</div>
<div>
<div>Imdb:</div>
<div><input id="id_imdb" type="text" name="movie_imdb" size="50">
<button name="b" type="button">Button</button></div>
</div>
<div>
<div><input type="submit" name="submit" value="Publish"></div>
</div>
</form>
<script type="text/javascript">
function myFunction() {
document.getElementById("id_desc").value = "<?php echo $slbl; ?>";
}
</script>
</body>
</html>
<?php
...here is script to insert in database which is working...
?>
get_info_imdb.php
<?php
include ("simple_html_dom.php");
$html = new simple_html_dom();
$html->load_file($hjo);
$html = $html->find('.summary_text', 0);
$nesto = strip_tags($html);
$nesto = trim($nesto);
$slbl = $nesto;
?>
This is an example to explain how to perform your request through javascript and jQuery. It's only an example, you have to implement it wih your own code:
File get_info_imdb.php:
<?php
$movieID = $_GET['id'];
// Your code to retrieve movie info and chunk of HTML you want put in textarea
echo $TextAreaValue;
?>
Fle insert-movie.php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/JavaScript">
function getHTML()
{
$.get( "get_info_imdb.php?id=tt1431045", function( data ) {
$( "#myTextArea" ).html( data );
});
}
</script>
<form action="YourAction.php" method="YourMethod">
<textarea id="myTextArea"></textarea>
<button id="myButton" onclick="getHTML(); return false;">Click Me</button>
</form>
</body>
</html>
In the <head><script> I load jQuery; In javascript function getHTML() I use jQuery get method to retrieve desired url (I have insert movie id, you can insert variable id with php) and put it into the content of textarea #myTextArea.
In the <form> the <button id="myButton"> call getHTML() js function.
See more about jQuery
See more about jQuery.get method
See an alternative in javascript

Replace the current content of div with another page response

Sample code:
<html>
<head>
.....
</head>
<body>
<div id="content">
<form>
....
<input type="submit" onclick="loadAnotherPage()"/>
</form>
</div>
</body>
</html>
I want to load another page say edit_profile.php in the content div. How can it be achieved without refreshing the page?
I tried to use jQuery load() method. But looks like I missed something. Any help would be highly appreciated.
When you click submit button it's submit form and page refresh that's why its not working.
Instead of type submit set button and then set function onclick.
function loadAnotherPage(){
$("#content").load('edit_profile.php');
}
$(document).ready(
function() {
$('#load_file').click(
$.post('edit_profile.php',
{},
function(data){
$("#content").html(data);
},''
)
);
}
);
Try this
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
<button id="loadpage">load new page</button>
<script>
$(document).ready(function () {
$("#loadpage").click(function() {
$.get("edit_profile.php", function(response){
$("#content").html(response);
});
})
});
</script>
</body>
</html>

Categories

Resources