jquery + ajax + php (loading jquery library) - javascript

So im learning about jquery and ajax. Originally i did an old school php page, where when i submit the form, the data gets stored in a database, and then the webpage loads a new page and tells me i've successfully added a student... I'm not trying to implement ajax and jquery to my code, but i my js script isn't working. I'm trying to call an Alert() just to test if jquery is working, but no alert popup appears when i click the submit button.
This is what i have so far:
addStudent2.php code:
<!DOCTYPE html>
<html>
<head>
<title>Adding Student With AJAX</title>
</head>
<body>
<form action = "userInfo.php" id="myForm" method="post">
<p>Name:
<input type="text" name="name" value=""/>
</p>
<p>Age:
<input type="text" name="age" value=""/>
</p>
<input type="submit" id="submit" value="Add"/>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-3.2.0.min.js" type = "text/javascript"></script>
<script src="my_script.js" type = "text/javascript"></script>
</form>
</body>
</html>
userInfo.php code:
<?php
include('connection.php');
$name = $_POST['name'];
$age = $_POST['age'];
$query = "INSERT INTO student2 (first_name, age) VALUES(?, ?)";
$var = array($name,$age);
$response = sqlsrv_query($conn, $query, $var);
if($response == true){
echo "Student has been added";
}
else{
echo nl2br("Insertion failed\n");
die( print_r( sqlsrv_errors(), true));
}
?>
my_script.js code:
$('input#submit').on('click', function(){
alart(1);
});
i know my javascript or jquery library isn't working, because i'm not getting an alert popup when i click on the submit button.
Could someone please help?

The problem was the js script was not updating on the browser, i had to force refresh the page by pressing "Ctrl + F5" here.
Also I changed input#submit to #submit:
$('#submit').on('click', function(){
alert(1);
});
...and of course changed "alart(1)" to "alert(1)" lol.

Related

link onclick does not submit form [duplicate]

This question already has answers here:
How to submit a form with JavaScript by clicking a link?
(9 answers)
Closed 2 years ago.
i have a db records echoed out and formatted in a table with a delete link(icon) on each table row, indexed with a while loop as the data gets fetched from db.
On clicking the delete icon, i expect the particular indexed row to get deleted from db and also from the table .
Here are my codes:
<script>
function submitForm(){
document.getElementById("myform").submit()
}</script>
</head>
<body>
<table>
<tbody>
<?php
$rowIndex = 0;
while($row = mysqli_fetch_row($result){
$user = $row[0];
$address=$row[1];
$phone = $row[2];
echo '<tr>
<td>'.$user.'</td>
<td>'.$address.'</td>
<td>'.$phone.'</td>
<td>Delete(icon)
</tr>'
$rowIndex+=1;
}
?>
</tbody>
</table>
<form method ="post" id ="myform" action ="test.php" >
<input type="hidden" name="del">
</form>
on clicking the 'Delete' Link , i expect the javascript to submit the form and move to 'test.php'(though i intend to remain on same form, but that way i will know my form ACTUALLY got submitted). Please any help will be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>test javascript form test </title>
</head>
<body>
<form action="#" method="post">
<label>Username</label>
<input type="text" id="name"><br>
<label>Password</label>
<input type="password" id="password"><br>
<button onclick="data()" type="button">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>
function data(){
var name = $("#name").val();
var pass = $("#password").val();
alert(name);
alert(pass);
}
</script>
</body>
</html>

PHP How to update text if a user submits a form

I am trying to make it so a user enters something into a textarea, and once the user submits it, the content will immediately display inside of a div above whose id is "currentMessage". Here is the php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Message Page</title>
<link rel="stylesheet" href="styles.css" type="text/css"/>
<script type="text/javascript">
function loadMessage(){
document.getElementById("currentMessage").innerHTML = "<?php
$my_file = "msg.txt";
$handle = fopen($my_file, "r");
$data = fread($handle, filesize($my_file));
fclose($handle);
echo $data;
?>";
}
</script>
</head>
<body onload="loadMessage();">
<?php include "header.html";?>
<div>
<div class="PageTitle">Messaging</div>
<p class="Paragraph">
Here you can send a message to the LCD display so that it may be shown when the display
cycles through its time, temperature and status.
</p>
<div class="Paragraph">
Current Message:<br>
<p id="currentMessage" class="CodeBlock"></p>
</div>
<div class="SubTitle">Enter Your Message:</div>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
<input type="submit" value="Submit Message" name="submit">
</form>
<?php
if (isset($_POST['submit'])){
$msg = $_POST["msg"];
$my_file = "msg.txt";
$handle = fopen($my_file, "w") or die("Cannot open file: " . $my_file);
fwrite($handle, $msg);
fclose($handle);
echo "<script>
loadMessage();
</script>";
}
?>
</div>
</body>
</html>
Currently, I attempt to save the user's submission to a file on the server, and then run loadMessage() and echo the result in the currentMessage div. However, this obviously isn't working. I'm also new to php and I am not sure how to direct the output of echo, or if there is no way to be more specific as to where to place output text.
So the problem with this is, you are loading the contents of the file before you've saved anything to it. The php code in loadMessage gets executed immediately on page load, and you'd like to execute it after your msg.txt file has been saved.
You can see that this is kind of working if you submit some text once, then try to submit some text again. it'll display what you submitted last time.
Although this overall approach shouldn't be used on an actual website to save info and then load it back to display, if you're just learning there shouldn't be anything wrong with this.
So, to use Javascript to load your data, you need to make an AJAX request.
Typically, most people use jQuery to perform an AJAX request to load data after the page has loaded.
However, to prevent you from including the whole jQuery library, you can use vanilla Javascript to load the msg.txt file asynchronously. This site, http://youmightnotneedjquery.com/#request, has many useful snippets on how to achieve the same effect without the jQuery library.
So, here'd be your code if you loaded the data via Javascript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Message Page</title>
<link rel="stylesheet" href="styles.css" type="text/css"/>
<script type="text/javascript">
function loadMessage(){
console.log("Performing AJAX request!");
var message_element = document.getElementById("currentMessage");
var request = new XMLHttpRequest();
// Load our msg.txt file
request.open('GET', 'msg.txt', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
// Display the text we loaded.
resp = request.responseText;
message_element.innerHTML = resp;
} else {
// We reached our target server, but it returned an error
message_element.innerHTML = "An error occurred.";
}
};
request.onerror = function() {
// There was a connection error of some sort
message_element.innerHTML = "An error occurred.";
};
// Send the AJAX request (which displays the data after it has been loaded)
request.send();
}
</script>
</head>
<body onload="loadMessage();">
<?php include "header.html";?>
<div>
<div class="PageTitle">Messaging</div>
<p class="Paragraph">
Here you can send a message to the LCD display so that it may be shown when the display
cycles through its time, temperature and status.
</p>
<div class="Paragraph">
Current Message:<br>
<p id="currentMessage" class="CodeBlock"></p>
</div>
<div class="SubTitle">Enter Your Message:</div>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
<input type="submit" value="Submit Message" name="submit">
</form>
<?php
if (isset($_POST['submit'])){
$msg = $_POST["msg"];
$my_file = "msg.txt";
$handle = fopen($my_file, "w") or die("Cannot open file: " . $my_file);
fwrite($handle, $msg);
fclose($handle);
}
?>
</div>
</body>
</html>
The problem I think you're having is that you're echo'ing javascript that is not getting evaluated.
Try echoing:
<script>
(function(){
loadMessage();
})();
</script>
instead of just
<script>
loadMessage();
</script>
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Passing javascript variable to php variable on the same page concept

need your advice, I have a form with some many fields, i use it to post to database, it's simply if i post it one by one. But it's so heavy if we have thousands data to post. i wanna post it cumulatively.
For now i use javascript, i add it to an array for temporary storage then show it with table under form. i want to use this array then post it into array variable of PHP. Then i can post to database. But i don't know how to do it if it on the same page. Because javascript is client side, and PHP is server side.
Is there any idea?
EDITED :
this my code, I have not made it in the table:
<!DOCTYPE html>
<html>
<body>
<label>Fruit Name</label> :<br>
<input type="text" id="text1"/><br>
<label>Nominal</label> :<br>
<input type="text" id="text2"/><br><br>
<button onclick="myFunction()">Add</button><button onclick="tableCreate()">Add</button>
<p id="demo"></p>
<?php $a = array(); ?>
<script>
var products = [];
function myFunction() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
var temp = text1 + "-" + text2;
products.push(temp);
document.getElementById("demo").innerHTML = products;
}
</script>
<hr>
<form action="" method="post">
<button type="submit" name="test" value="Test">Save</button>
</form>
<?php
if(isset($_POST['test'])){
// get array products from javascript, isn't possible?
}
?>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
You can make use of php for submitting a form and inserting the record to database.Write php script on the same page which will be executed on form post.
Save the following code snippet to a php file name as currentPhpFileName.php and execute it over localhost.
<!DOCTYPE html>
<html>
<body>
<form action="currentPhpFileName.php" method="post">
<input type="text" name="fieldName1" value="testValue1" />
<input type="text" name="fieldName2" value="testValue2" />
<button type="submit" name="test" value="Test">Save</button>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
print_r($_POST['fieldName1']);
print_r($_POST['fieldName2']);
foreach($_POST as $value)
{
print_r($value);
//database connection
//logic to insert records into database
}
}
?>

save data from php to ajax and change color of div when new data insert?

Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Values to PHP function parameters from Button click Javascript function

Friends,
I'm a newbie to PHP.
I've had a problem to deal with that I couldn't understand, so I posted it in this thread.
I've dynamically created 2 textboxes and a button.
Question ID text field
Question text field
Change Button
for the change button I need to write a 'onclick' javascript to pass Question ID
and Question value to a PHP function (set_id) written inside the Same file. In fact that’s why i
Called Form action $_SERVER[“PHP_SELF”].
Here’s my code.
<html>
<head>
<script>
function getvalue(value)
{
var qid_value = 'qid_'+value.substring(4);
alert('QID = '+ document.getElementById(qid_value).value + ' QUESTION = ' + document.getElementById(value.substring(4)).value);
/*
I created this javascript alert to test the id s of textboxes and their values
*/
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<!-- These fields are dynamically created -->
<input type="text" id="'.$var_id.'" name="'.$var_id.'" value="'.$row['qid'].'" readonly size="2 px"/>
<input type="text" id="'.$var_question.'" name="'.$var_question.'" value="'.$row['question'].'" style="size:auto"/>
<input type="button" id="'.$var_question.'" name="'.$var_question.'" value="Change" onclick="getvalue(this.name)"/>
<!-- These fields are dynamically created -->
</form>
</body>
</html>
<?php
$msg= "";
function display($qid,$question)
{
require('uni_db_conn.php'); // this is my db connection
$qid = $_POST[$qid];
$question= $_POST[$question];
$query = "UPDATE question SET question='.$question.' WHERE qid='.$qid.'";
$result = mysql_query($query);
if(!$result)
{
$msg= 'Cant Insert Values to the Table !'.mysql_error();
}
else
{
$msg = 'Successfully Added to the Table !';
}
echo '<label>'.$msg.'</label>';
}
function set_id($qid,$question)
{
if(isset($_POST[$question]))
{
display($qid,$question);
}
}
?>
Thank You ! Sorry If there was any mistake.
Try this code
<?php
if(isset($_POST['submit'])){
$QID = $_POST["qid"];
$QUE = $_POST["question"];
echo $QID;
echo $QUE;
}
?>
<html>
<head>
<script language="javascript">
function getvalue()
{
var valid= true;
var id = document.getElementById("ID").value;
var ques = document.getElementById("ques").value;
return valid;
}
</script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit=" return getvalue()" >
<input type="text" id="ID" name="qid"/>
<input type="text" id="ques" name="question"/>
<input type="submit" name="submit" value="Change"/>
</form>
</body>
</html>

Categories