Problems in submitting form data using ajax - php

i am new in ajax. i am aware to html,php. i want to do the CRUD operation in ajax. i have created a two file
index.php
insert.php as below.
when i click on submit button it submit data and inserted in database. But it resfresh the page. please suggest me that where i made mistake.
my code as below:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id="contactForm1" action="insert.php" method="post">
<label>Name</label><input type="text" name="user_name"><br>
<label>Age</label><input type="number" name="user_age"><br>
<label>Course</label><input type="text" name="user_course">
<br>
<input type="submit" name="sumit" value="submit">
</form>
</body>
</html>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "" ,"aj");
$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];
$insertdata=" INSERT INTO test3 (name,age,course) VALUES( '$name','$age','$course' ) ";
mysqli_query($conn,$insertdata);
?>

Close the script tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Use when document is ready
$( document ).ready(function() {
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
frm[0].reset();
alert('ok');
}
});
ev.preventDefault();
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.

The JavaScript code, binding the event handler, is executed too early. The DOM is not fully loaded yet so the form can't be found. jQuery doesn't warn about this.
Either wrap your code in jQuery's on doc loaded method $(function(){ /* code here */ } ).
Or/and move your JavaScript to the bottom of your HTML. This is a preferred method. See Benefits of loading JS at the bottom as opposed to the top of the document for more details

There is no mistake. Technically, its correct. It's just not fitting in your use-case.
It's default behaviour that page refreshes when user submits form.
You have two options:
Stop further execution when your ajax call is completed. You can do this by javascript by using preventDefault method. Then, use return false.
Change the submit button to normal button. In other words, don't submit form normal way. Give an id to normal button and call javascript function upon its click.

Related

SQL query without refresh

I've read all the related posted, watched videos, and read tutorials... But I still can't figure this out. I just want to run a mysqli_query insert without a refresh.
No inputs, no variables, just a pre-defined sql insert without a refresh.
Here is the main doc:
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
$("#click").click( function()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
});
</script>
</head>
<body>
<input type="button" id="click" value="Click">
</body>
</html>
Click.php (Has been tested standalone):
<?php
$db = mysqli_connect("localhost","root","","mytable")
or die("Error " . mysqli_error($db));
mysqli_query($db,"INSERT INTO items VALUES
('','test','test','total test','test','test','test','test')");
?>
This has been driving me crazy... I've read tutorials and watched many videos about ajax... but I can't figure this out.
Thank you for any advice.
To refresh a part of a page you got to bind the success function to a div in the html so add a div with an Id
<div id="myDiv"></div>
And then
$('#like$id').click(function()
{
$.ajax({
url: 'inc/scripts/liker_ajax.php?like=$id',
type: 'GET',
success:function(result){
$('#like$id').addClass('green');
$('#dislike$id').removeClass('red');
$('#myDiv').html(result);
}
});
});
You're binding the event $('#click').click() before there is an element to bind to (since $('#click') isn't loaded yet).
Just move your <script> tag with the click binding event into the <body> underneath the input button and it will work as expected.
You might also want to wrap in a jQuery document ready enclosure like:
$(function() {
});
to make sure it runs when DOM ready.
Try this.
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
function runAjax()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
</script>
</head>
<body>
<input type="button" id="click" onclick="runAjax()" value="Click">
</body>
</html>
You are binding the event to the element when the element is not exixting yet.
You have 2 options here.
Either move your script block to just below the end of body tag after the element.
Encase your code inside the script block under $(document).ready(function() {
// your code here
});
Also use the console tab under your developer tools to find the root cause if any errors are present.

PHP not capture $_POST data send by ajax jquery on same page

I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().

Form submit supposed to refresh only Div, but instead refreshes Page

I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......

jquery is resetting my div content

I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>
It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.
Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?
You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

Categories