I am trying to make a form to insert data to database with jQuery, but there's no action happen and want to know where the problem is.
Here's the code I wrote, and I hope someone will help me find where the mistake is, and why there's no action on it.
index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="insert.js"></script>
</head>
<body>
<form id="form-search" method="post" action="index.html">
<input name="gov" id="gov" type="text" class="textinput required" maxlength="80" required><br>
<input name="area" id="area" type="text" class="textinput required" maxlength="80" required><br>
<button id="submit" type="button">insert</button>
</form>
</body>
</html>
insert.js code
$(document).ready(function(e) {
$('#submit').click(function() {
var gov =$('#gov').val() ;
var area =$('#area').val() ;
$.ajex({
type :'post' ,
data :{gov:gov,area:area},
url :"insert.php",
success :function(result) {
alert(result);
}
})
});
});
insert.php code
<?php
$con = mysqli_connect('localhost','user','pass','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if($_REQUEST['gov']) {
$gov=$_REQUEST['gov'];
$area=$_REQUEST['area'];
$q="inser into gov values ('','$gov','$area')";
$query=mysqli_query($con,$q);
if($query){
echo "data insert " ;
}
}
?>
Look at the Networks' tab using the Developer Tools. Check if there's something happening when you press the submit button. Check for a status code.
This script (with your html) will submit the data (with console logs to the browser) to 'insert.php'. Please read the comments for explanations. If it still doesn't work, the problem probably lies in your PHP code (I don't work with PHP). The ajax is sending the data to 'insert.php', which should be coded to accept the data variables and return a json response back to the ajax function in the script.
// Remove the 'e' from .ready and place in the 'click' function - this is the 'event'
$(document).ready(function () {
$('#submit').click(function (e) {
// Stops the form from being submitted 'normally' (to index.html)
e.preventDefault();
// Check console in your browser (this can be removed when it works)
console.log('submit clicked');
// Define the data to be submitted with the ajax form
var submitData = { gov: $('#gov').val(), area: $('#area').val() };
$.ajax({
// Make sure your path to insert.php is complete - check console in browser to see if there is an error
url: 'insert.php',
// Make sure 'insert.php' accepts 'post' transactions
type: 'POST',
// This could be changed (when it works) to - data: { gov: $('#gov').val(), area: $('#area').val() },
data: submitData,
// Make sure 'insert.php' returns a json result
dataType: 'json',
success: function (result) {
// This can be removed when it works
console.log('ajax success');
},
beforeSend: function () {
// This can be removed when it works
console.log('ajax beforeSend');
// This can be removed when it works - this lists out the data submitted with the form
$.each(submitData, function (index, value) {
console.log('index: ' + index + ' value: ' + value);
});
},
complete: function () {
// This can be removed when it works
console.log('ajax complete');
},
error: function () {
// This can be removed when it works
console.log('ajax error');
}
});
});
});
Related
I am trying to send ajax post javascript variable to php. My code php will only be executed if I press submit in another form.
My code is in one index.php file.
The console shows that this value has been sent, but my php code does not want to pick it up and does not execute the query. Why?
<?php
if (isset($_POST['imie2'])) {
...
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
$value = $_POST['item_id'];
if ($polaczenie->query("INSERT INTO zamowienia VALUES ('$value')")) {
...
?>
<form method="post">
<input type="text" name="imie2">
...
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
var value = localStorage.getItem('sumalist');
console.log(value);
$.ajax({
url:"index.php",
method:"POST",
data:{
item_id: value,
},
success:function(response) {
console.log('ok'); // console shows ok
},
error:function(){
alert("error");
}
});
});
</script>
You said:
if (isset($_POST['imie2'])) {
but your data looks like this:
data:{
item_id: value,
},
There's no imie2 field so your test will always fail.
I've got a basic html form and a div under it called "response", the user enters a password, the script should check the database to find the username (works fine) then print the username in the "response" div under the form for further processing, but I cannot get the jQuery/Ajax bit working to submit the form and query to the database behind the scenes (I'm quite new to jQuery).
I've got this so far, can anyone help get it working please?
php (checkuser.php):
$pass = $_POST['password'];
echo $pass;
$con = new mysqli("--IP--", "--USER--", "--PASS--", "--DB--");
if (mysqli_connect_errno()) {
echo "A problem has occured, please come back later.";
exit();
}
if ($stmt = $con -> prepare("SELECT `username` FROM --DB-- WHERE `password`=?")) {
$stmt -> bind_param("s", $pass);
$stmt -> execute();
$stmt -> bind_result($user);
while ($stmt -> fetch()) {
echo "welcome ".$user;
}
return $user;
$stmt -> close();
}
$con -> close();
html:
<form id="pass_form" action="post">
<input id="form_pass" type="text" name="password" placeholder="Password Goes Here"><br><br>
<input id="form_submit" class="submit_btn" type="submit" value="Submit">
</form>
<div id="response"></div>
jQuery (in head):
$(function() {
$("#form_submit").click(function() {
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function() {
// Not sure what to do here
}
});
});
});
You need to prevent the default form behavior and display the response from ajax request in the #response div
$(function() {
$("#form_submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function(result) {
$('#response').html(result);
}
});
});
});
Everything goes where you are Not sure what to do here.
success: function(response) {
alert(response);
}
Also, I am not sure why you have a return $user in your php. Comment that line out and test the above-mentioned code.
So response holds what the php echoed. You can now use that to do whatever you wish to do.
We rarely let the submit button do it's work. We kind of like to use it as a mere button while it is more than a button. So since you may be new let me introduce you to the submit button and event. The button is used to submit the form:
$(function() {
$("#pass_form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function(result) {
$('#response').html(result);
}
});
});
});
So we bind the a submit event handler to the form and the submit button takes it from there.
$("#form_submit").click(function(){
$("#response").show();
$.post( "http://--SITE--/--FOLDER--/checkuser.php", {
password: $("#form_pass").val(),
}).done(function( data ) {
$( "#response" ).html( data );
});
});
This will return whatever output your targeting page is going to output.
you don't really need a form to do this process
I am trying to post the data from this form into the database. I have tried some tutorials with no success. Here is my code. Any ideas?
View:
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
AJAX (in the view, right below the form)
<script type='text/javascript' language='javascript'>
$("#submitbutton").click(function(){
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("Fail")
}
});
e.preventDefault();
});
</script>
Controller
function insert_into_db(){
$this->load->model('insert_db');
$this->insert_db->insertQ();
}
Model
class Insert_db extends CI_Model{
function insertQ(){
$email = $_POST['email'];
$qText = $_POST['qText'];
$this->db->query("INSERT INTO questions VALUES('','$email','$qText','','')");
}
}
As #David Knipe already said, you should wait for the DOM to be ready before trying to access one of its elements. Moreover, you likely have an e is undefined error, since you're not passing the event reference to the click handler:
<script> //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>
To be more complete, your query is vulnerable, and you might be getting an error there. Make use of the advantage of having a framework beneath you:
function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}
^_ I'm guessing the column names since you didn't specify them
Looks like you've forgotten to use $.ready. As it is, the javascript runs before the page has loaded, which means it can't find the page element from $("#submitbutton"). Try this:
$(document).ready(function() {
$("#submitbutton").click(function(){
....
....
});
How do i load data into textfields after clicking a checkbox & after doing it, i need to disable that textbox, but again as i uncheck it, need to remove that data & make the textbox enable to manually enter data. I tried this code,i'm new to jquery/ajax, can't figure out how to solve this problem.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#chk').click(function(){
if($(this).is(":checked"))
$("#txtaddress").removeAttr("disabled");
else
$("#txtaddress").attr("disabled" , "disabled");
// here, i don't know how do i assign $row['address'] to txtaddress by
// using php mysql
});
});
</script>
<!-this is my html code-->
<form>
<input type="checkbox" id="chk" name="chk">Same as home address?
<input id="txtaddress" name="txtaddress" disabled type="text">
</form>
Try the following,
<script>
$(document).ready(function(){
$('#chk').click(function(){
if($(this).is(":checked"))
$("#txtaddress").val(""); //reset the textbox
$("#txtaddress").removeAttr("disabled");
else {
$.ajax({
type: 'GET',
url: destinationUrl, // your url
success: function (data) { // your data ie $row['address'] from your php script
$("#txtaddress").val(data); //set the value
$("#txtaddress").attr("disabled", "disabled");
}
});
}
});
});
</script>
From your php script you can echo $row['address'], so the data in success function can be put into textbox in ajax
javascript code:
$(document).ready(function(){
$('#chk').click(function(){
var txt = $("#txtaddress");
($(this).is(":checked")) ? txt.attr("disabled" , true) : txt.attr("disabled" , false);
});
});
I hope this is what u meant.. Hope this might help... :)
$('#chk').click(function(){
if(! $(this).is(":checked")){
$("#txtaddress").removeAttr("disabled");
$("#txtaddress").val('');
}
else{
$.ajax( {
url: "get_row_details",
type: "POST", //or may be "GET" as you wish
data: 'username='+name, // Incase u want to send any data
success: function(data) {
$("#txtaddress").val(data); //Here the data will be present in the input field that is obtained from the php file
}
});
$("#txtaddress").attr("disabled" , "disabled");
}
});
From the php file echo the desired $row['address'].This value will be obtained at the success of the ajax function
New to Jquery, even newer to Jquery Ajax calls - here is my problem:
I have a small form - email address submit - that fires to a PHP file which inserts the email into a table.
I want to do the following:
Handle the form submission through Ajax so there is no refresh
After successfully writing to the table I want to change the submit button's text to "Success!" for 3 seconds and then back to
"Sign Up" with fadeIn and fadeOut effects.
Here is my code for the form:
<form action="" id="registerform" name="registerform" method="post" >
<input type="text" id="email" name="email" value="Email Address" onClick="empty()" onBlur="determine()" />
<button id="join" type="submit" name="join" onClick="validate()">Sign Up</button>
</form>
Here is my terrible attempt at handling the POST request through Jquery:
$('form').on('submit', function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Can anyone comment on how to make the Ajax request work (doesn't seem to be)?
Thanks in advance!
Update
Alright, the following block of Jquery adds the data to the table, however, my button text does not change:
$('form').on('submit', function(e) {
$.post('register.php', $("#registerform").serialize(), function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Any ideas now?
Here is an example of one of my ajax calls
details = "sendEmail=true&" + $("form").serialise();
$.ajax({
url: "yourphppage.php",
type: "post",
data: details,
success: function (data, textStatus, jqXHR) {
if (data == "false") {
console.log("There is a problem on the server, please try again later");
} else {
//Do something with what is returned
}
}
})
And on the server side
if (isset($_POST['sendEmail'])) {
//Do something with the data
}
Of course this is only an example, and you may need to alter this to suit your needs :)
One thing to note is what if (data == "false") does. Well on the server side i can echo "false" to tell the ajax call it was not successful.
You're not actually sending any data to the server. You need to use the 'data' parameter of $.post to send your data.
$('form').on('submit', function(e) {
$.post('register.php', $(this).serialize(), function() {
$('#join').html('Success!');
});
//disable default action
e.preventDefault();
});
Not sure, but does the POST request send anything at all? Try adding the data in the POST request.
$('form#registerform').submit(function() {
var email = $(this).find('input[name=email]').val();
$.post('register.php', {email: email}, function() {
$('#join').html('Success!');
});
return false;
});
Where you're pushing your form data to server in ajax call? change code to this.
var data = {$("#email").val()};
$('form').submit(data ,function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});