I have surfed a lot and i have also tried all the possibilities to get this done, but still it is not working. What I am doing is, trying to insert product category using XMLHttpRequest and if recorded inserted successfully it should return true as response else false as response.
front page:
<form id="form_validation" method="POST" onsubmit="InsertCategory()">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="category_name" id="category_name" required>
<label class="form-label">Category Name</label>
</div>
</div>
<button class="btn btn-primary waves-effect" type="submit" name="submit">SUBMIT</button>
</form>
<script>
function InsertCategory()
{
var category_name=document.getElementById("category_name").value;
var operation="insert";
var url = "includes/ajax/category_master/categoryOperations.php";
//var url = "includes/ajax/getDocuments.php";
var params = "category_name="+category_name+"&operation="+operation;
var http = new XMLHttpRequest();
http.onreadystatechange = function()
{
console.log("rs "+http.response);
console.log(http.readyState);
console.log(http.status);
if(http.readyState == 4 && http.status == 200)
{
}
}
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
}
</script>
here is categoryOperations page
<?php include_once("connection.php");
$operation=$_POST["operation"];
switch($operation)
{
case "insert":
$category_name=$_POST["category_name"];
$query="insert into product_category(category_name)values(:category_name)";
$stmt=$con->prepare($query);
$stmt->bindParam(":category_name",$category_name);
if($stmt->execute())
{
echo "true";
}
else
{
echo "false";
}
break;
case "update":
break;
case "delete":
break;
}
?>
What happens here is, all code work fine, category inserts in product_category table but i am not able to receive true as response.
if I comment $stmt->execute() in categoryOperations page and echo true then it works fine, on console I get true. but if query is executed it does not return anything.
I am not able to understand this behavior of the code.
Got Solution
The problem was, i have written
<form id="form_validation" method="POST" onsubmit="InsertCategory()">
that was sending two request. with form as well as from xmlhttprequest.
i just removed <form> tag and called InsertCateory() on submit button
<button class="btn btn-primary waves-effect" type="submit" onClick="InsertCategory()" name="submit">SUBMIT</button>
Related
I have a user settings page where the user changes their name via ajax and calls an update script that works great. The problem is I include a separate sidebar file which echos the current name in the database, but doesn't change until you reload the page because it's a separate sidebar.php include.
included sidebar.php within settings.php page
<h2 id="profile-name">
<?php
if(!$userRow['name']){
echo "You";
}else{
echo ucfirst($userRow['name']);
}
?>
</h2>
//form starts
<form id="my_form" onsubmit="submitForm(); return false;">
Name: <input id="name" type="text" class="form-control" placeholder= "<?php echo $userRow['name']; ?>" name="name" value="<?php echo $userRow['name']; ?>"><br>
<input class="btn btn-default" id="mybtn" type="submit" value="Submit Form"> <span id="status"></span>
</form>
//ajax works fine and updates database
function _(id){ return document.getElementById(id); }
function submitForm(){
var formdata = new FormData();
formdata.append( "name", _("name").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "update_name.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
} else {
// _("status").innerHTML = ajax.responseText;
alert("saved");
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
Just can't figure out how to get the sidebar to update without reloading the page. Thanks everyone!
I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>
I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>
I am trying to submit the form on my page upon page load if there are certain parameters set in the query string. The form submits using ajax and works fine and the pre-population of the form fields from the query string is fine aswell but no matter what I try to automatically submit the form, I end up in an infinite loop of page loads.
PHP
// top of page
<?php
if (isset($_GET['postcode'])) {
$postcode = trim($_GET['postcode']);
} else {
$postcode = '';
}
if (isset($_GET['phone_num'])) {
$phone_num = trim($_GET['phone_num']);
} else {
$phone_num = '';
}
?>
jQuery
/*
// causing infinite page loads
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
return false;
}
*/
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<button type="submit" class="btn btn-primary" id="check">Check</button>
</form>
Instead of using a click function for the auto form submit I've tried doing the same $('form').submit but I get the same problem. I was expecting the page to function as normal so that if the parameters were set then the ajax call would automatically be made but this is obviously not the case.
You're exiting your code before you bind the submit event. Remove the return false in your if statement, then move the if statement to after the submit binding.
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
//return false;
}
Try something like this:
if($('input[name="phone_num"]').val() && $('input[name="postcode"]').val()) {
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
}).submit();
}
use this line on your code.
$('form').trigger("submit");
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<input type="button" class="btn btn-primary" id="check">Check</button>
</form>
jQuery
$('#check').click(function(e) {
e.preventDefault();
$.get("script.php", $('form').serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
}
When using a submit button, you are performing the default event (submitting the form) as well as processing the handler of the .click() event. To avoid this, use e.preventDefault(); causing only the scripted portion of the event to process.
I am trying to follow a tutorial and demo. But when I press SUBMIT or ENTER button, it is not submitting, it is just refreshing the page :( and showing an error.
It shows an alert
There was a problem with the request.
And the page refreshes.
My form
<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo"> <div class="control-group">
<label class="control-label" for="book">Book</label>
<div class="controls">
<input type="text" id="book" onKeyUp="book_suggestion()">
<div id="suggestion"></div>
</div> </div> <div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
And my Javascript
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
book-suggestion.php
<?php
include('../includes/dbopen.php');
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
The submit button used there is not participating in the demo. The purpose of the demo is to show how to fetch data with ajax when user types data in the text box. It may, for sure be extended so that the submit button acts upon and adds some more functions, but for now, that has not been added to the demo.