Ajax form submission - php

I am trying to post the a form using ajax but the form never submits. Debugging using firebug doesn't show any errors. any help is appreciated. i am new to PHP and coding.
Taskload.php - Pushes data to the main page:
<?php
include_once 'dbconnect.php';
$varacctname = $_REQUEST['acct'];
$varViewtasks = mysql_query("SELECT * FROM tasks WHERE taskresource = '$varacctname' AND taskstatus='Active'");
while ($rows = mysql_fetch_array($varViewtasks)) {
$accttask = $rows['tasktitle'];
$acctTaskStatus = $rows['taskstatus'];
$taskOwner = $rows['taskOwnerFullName'];
$taskid = $rows['taskid'];
echo "<div class=\"timeline-messages\">
<div class=\"msg-time-chat\">
<img class=\"avatar\" src=\"img/chat-avatar.jpg\" alt=\"\">
<div class=\"message-body msg-in\">
<span class=\"arrow\"></span>
<div class=\"text\">
<p class=\"attribution\">$taskOwner</p>
<p> $accttask</p>
</div>
<form id=\"completetaskform\" method=\"post\" >
<input type=\"hidden\" name=\"taskid\" value=\"$taskid\" />
<input type=\"hidden\" name=\"acct\" value=\"$varacctname\" />
<input type=\"submit\" id=\"completetaskbtn\" class=\"btn btn-success\" />
</form>
</div>
</div>
</div>";
}
?>
Tasks.js - where the script lives
$("#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"functions//completeTask.php",
data: $('form#completetaskform').serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});
completeTask.php Where the php code runs to mark task as completed.
<?php
include 'dbconnect.php';
$acct = $_POST['acct'];
$taskid = $_POST['taskid'];
$complete = 'completed';
mysql_query("UPDATE tasks SET taskstatus='$complete' WHERE taskresource='$acct' AND taskid='$taskid' ");
?>
--On the main page , i have tasks.js included in - Hope this may describe the issue better.

try SerializeArray
$("#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"functions//completeTask.php",
data: $('form#completetaskform').serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});
or even $.post
$.post('functions/completeTrask.php',$('form#completetaskform').serialize(),function(){
notifyTaskCompleted();
location.reload();
});

1.Change
$("#completetaskform").submit(function(){
to
$("#completetaskform").on('click',function(){
Because jquery event is ".on()", not ".submit()"
2.Change
<input type=\"submit\" id=\"#completetaskbtn\" class=\"btn btn-success\"> Complete </a>
to
<button id="completetaskbtn"> Complete </button>
Bacause you don't need real submit button.
3.I'm not sure that your url is correct but this will submit your form to php.

after many trials, i found that changing the the form data section to $(this).serialize worked instead of $('form#completetaskform').serialize(). Not sure why but this worked. Thank you.
$("form#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"Functions/completeTask.php",
data: $(this).serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});

I would use a generic button and click handler instead of a submit button and the submit event. Try this:
<button type=\"button\" id=\"#completetaskbtn\" class=\"btn btn-success\"> Complete </button>
Then attach a click event to it
$("#completetaskbtn").on('click', function () {
// the rest of the code you have
});

Related

wizard-form tow button different call ajax

I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)

Simple PHP AJAX script

I have 2 scripts, submit.php and display.php.
I want to be able to load submit.php, click the submit button & the result div to display 123.
Right now, it just reloads my page. I'm not getting anything from my Console so stuck how to debug.
Can someone take a look and provide assistance?
submit.php:
<form>
<input type="submit" value="Submit" name="display" id="display">
</form>
<div id="result"> </div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$("#display").click(function() {
$.ajax({
url: 'display.php',
type: 'GET',
dataType: "html",
data: {
"id": "123",
},
success: function(data) {
//called when successful
$('#result').html(data);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
});
</script>
display.php:
<?php
$id = $_GET['id'];
echo $id;
?>
It submits or reloads the page. You need to prevent the default action. Change the first two lines:
$("#display").click(function(e) { // Add e (event) parameter.
e.preventDefault(); // Prevent the default action for this event.
You may change to type="button", but not sure if it will be effective.
solved your issue please
replace
<input type="submit" value="Submit" name="display" id="display">
by
<button type="button" name="display" id="display">Submit</button>

jQuery AJAX POST to current page with attribute

This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>

Append a div without refreshing jquery

I want to add a div without refreshing the page.
Here is my Javascript:
<input class="btnsubmit" type="button" value="+Add Trivia" id="add_triviamodal">
function add_trivia()
{
var PHOTO_TRIVIA = CKEDITOR.instances.Trivia_Photo.getData();
var TITLE_TRIVIA = $('#TRIVIA_TITLE').val();
var CAPTION_TRIVIA = CKEDITOR.instances.triviacap.getData();
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
location.reload(); \\what i do is just refresh the page
});
}
This is how i output the the data that will be added using the ajax above
echo "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
}
You can use append() in jQuery to append elements to the DOM. If the div is returned by your PHP. Then append it to a DOM element by using i.e. $('#trivias').append(data);
EDIT (using the question authors code as an example):
I've replaced the location.reload() part with the code to append the returning div.
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
$('#trivias').append(data);
}
Here I assume you've got a element with the trivias id. For example <div id="trivias">...</div> somewhere in your code already.
just put your response data into whatever you want it in
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
$('#idOfTheDivYouwantToPutResponseIn').html(data);
});
Change your $.post() callback to also append the HTML response from insert_home.php into the DIV.
$.post('insert_home.php',{
TRIVIA_TITLE: TITLE_TRIVIA,
TRIVIA_PHOTO: PHOTO_TRIVIA,
TRIVIA_CAP: CAPTION_TRIVIA
}).done(function(data){
alert ("Trivia Successfully Added");
$('#trivias').html(data);
});
in PHP use json_encode
$str = "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
echo json_encode($str);
then use he post request like this
$.ajax({
type: "POST",
url: 'insert_home.php',
data: {TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA},
dataType:'json',
success: function (data) {
$('#your_id').html(data);
}
});

How to pass textbox value to another script on link click event

I have a form like this:
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php'>Show Value</a>
</form>
Question:
I want to pass 'myTextField' textbox value to two.php and want to echo it on screen. I can't use submit button and also can't submit the form. Is there any trick ?
Thanks
You could start by giving the anchor an unique id:
<a id="mylink" href="two.php">Show Value</a>
and then register for the click event handler and send an AJAX request:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
data: { myTextField: $('#myFormId input[name=myTextField]').val() },
success: function(result) {
// TODO: use the resulting value
alert(result);
}
});
return false;
});
});
one.php
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php?value=myTextField'>Show Value</a>
</form>
two.php
echo $_GET['value'];
<form id='myFormId' name='myFormName'>
<input type='text' name='myTextField'>
<a href='two.php' id='myLink'>Show Value</a>
</form>
jQuery('#myLink').live('click',function() {
$.ajax({
url: this.href,
type: 'POST',
data: $('#myFormId').serialize(),
success: function( data ) {
// TODO: use the resulting value
alert(data);
}
});
return false;
});

Categories