Using jquery ajax to serialize data and submit into mysql database - php

The problem i have is that whenever it inserts the data into the database it doesn't redirect the user to the invoice.php page. Please guys i really need your help.
This is the html code:
<form method="POST" action="">
<input type="text" name="resident_address" id="resident_address"/>
<input type="text" name="price" id="status"/>
<input type="hidden" name="status" id="status" value="0"/>
</form>
This is the jquery code:
var dataString = $('#applyform').serialize();
$.ajax({
type: "POST",
url: "applyform.php",
cache: false,
data: dataString,
beforeSend: function()
{
$(".apply_error").hide();
},
success: function(html) {
if (html == "true")
{
// You can redirect to other page here....
window.location.href = 'invoice.php';
}
else
{
//window.location.href = 'apply.php';
$("div.apply_error").html("Wrong details").show();
}
}
});
this is the php which is the applyform.php:
if(isset($_POST['Submit']))
{
$result = mysql_query("INSERT INTO mytable (resident_address, price, status) VALUES ('$addressfields', '$price', '$status')");
if($result){
echo "true";
}
}

you are not posting a POST var called "Submit" so your
if(isset($_POST['Submit']))
will always evaluate to false and your mysql query is never executed.

Related

Sending AJAX-Request to MySQL and getting JSON back via php/jQuery

im trying to send a AJAX request to my database and get the information in JSON format back, then i want to replace my div with those json information. But my div wont get changed and i dont know why..
Here is my code and thank you very much for helping:
index.php
<form class="login-form" method="post" action="">
<input type="text" name="lusername" placeholder="username"/>
<input type="password" name="lpassword" placeholder="password"/>
<input type="image" name="login" src="src/login.png" onClick="getLoginInfo()">
<p class="message">Not registered? <span id="tab">Create an account</span></p>
<div id="test">change me pls</div>
</form>
login.php
<?php
require_once("connection.php");
if(isset($_POST['login_x']) or isset($_POST['login_y'])) {
$lusername = $_POST['lusername'];
$lpassword = $_POST['lpassword'];
$select = mysqli_query($connection, "SELECT Username, Password FROM Account WHERE Username='".$lusername."' AND Password='".$lpassword."'");
if(mysqli_num_rows($select) == 0) {
echo '<script>cantFindAccount()</script>';
} else {
$array = mysqli_fetch_row($select);
echo json_encode($array);
}
}
?>
getLoginInfo.js
function getLoginInfo() {
$.ajax({
url: 'http://localhost/login.php',
data: "",
dataType: 'json',
success: function(data) {
var user = data[0];
var pass = data[1];
$('#test').html("<b>id: </b>"+user+"<b> name: </b>"+pass);
}
});
return false;
}
Try this, you have to post some data to your script so that it would process. Moreover you have to use method: 'POST' because you have used $_POST[]
$.ajax({
url: 'http://localhost/login.php',
data: $(this).serialize(),
method: 'POST',
dataType: 'json',
success: function(data) {
var user = data[0];
var pass = data[1];
$('#test').html("<b>id: </b>"+user+"<b> name: </b>"+pass);
}
});

ajax not returning to php index page

pleae note that i m trying jump to test.php page from index.php/html using ajax and mysql, simple if text-input not found in table so it should go to test.php else stay on index.php/html page with ajax alerts, but from index page everytime receiving NOT AVAILABLE and sometime submit button not functional, below code FYR...
//index.php $(document).ready(function() {
//default form not submitted
$("#submit").data("submitted",false);
//preventing enter key in input field from submitting form
$("#welcome").on("submit", function(e){
if($('#submit').data("submitted")===false) {
e.preventDefault();
}
});
//trigger form submission
$("#submit").on("click",function(){
validate();
});});
//default form not submitted
//$("#submit
function validate() {
var num = $('#invst_num').val();
$.ajax({
type: 'POST',
url: 'check_test.php',
data: num,
cache: false,
dataType: "json",
success: function(data) {
if(data){
alert("NOT AVAILABLE");
} else {
$("#submit").data("submitted", true);
$("#welcome").submit();
}
}}</script> <form action="check_test.php" method="post" name="welcome" id="welcome" /> <table width="550" border='0' align='center' cellpadding='0' cellspacing='0'> <tr>
<td align="center"><label>
Enter Inv. # *:
<input name="invst_num" type="text" id="invst_num" size="40" />
<input name="submit" type='submit' id='submit' /> </label></td> </tr></table> </form>
//check_test.php <?php
include ("config/config.php");
//get the username
if (isset($_POST['submit'])) {
$invst_num = $_POST['invst_num'];
//mysql query to select field username if it's equal to the username that we check '
$sql = mysql_query("select invst_num_ar from shareholders_ar where invst_num_ar = '$invst_num' ");
if ($result = mysql_num_rows($sql)>0) {
echo ($result);
}
}
?>
// if not found...test.php should load
<html>
<form
...
Register Data
/form>
</html>
Your conditional is backwards
if(data){
Should be
if(!data){
Or the alert should be flipped with the listener adding logic.
var num = $('#invst_num').val();
$.ajax({
type: 'POST',
url: 'check_test.php',
data: num,
ajax call is sending value frome data key, so you send only the text field content.
You probably should send sth like this:
$.ajax({
type: 'POST',
url: 'check_test.php',
data: { 'invst_num': num },
...
Open Dev tools in your browser and check what content is being sent during ajax call.

Posting data with Fancybox 2

I'm using a form within a fancybox window post (Ajax) data to a php page.
If I run the form outside of the Fancybox it works perfectly. Insert - Check. Response - Check. That said, if I run the same page through the Fancybox I get a loading wheel (which persists after I close the overlay).
Form (form_test.php):
<form id="form" method="post" action="">
<input type="text" id="name" name="name" value="Test Name" />
<input type="text" id="email" name="email" value="email#test.com" />
<input type="submit" value="Login" />
</form>
<script type"text/javascript">
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
</script>
PHP (test.php):
$name=$_POST['name'];
$email=$_POST['email'];
$query=mysql_query("INSERT INTO members (firstName,email) VALUES('$name','$email')");
if($query){
echo "Data for $name inserted successfully!";
}
else{
echo "An error occurred!";
}
Ideas?
Try
$("#form").bind("submit", function () {
$.fancybox.showLoading(); // it was $.fancybox.showActivity(); for v1.3.4
$.ajax({
type: "POST",
cache: false,
url: "test.php", // make sure your path is correct
data: $(this).serializeArray(), // your were using $(form).serialize(),
success: function (data) {
$.fancybox(data);
}
});
return false;
}); // bind
Now, $.fancybox(data); will return (inside fancybox) whatever you sent from the text.php file so you could return the <div id="message"> from within that file like :
if($query){
echo "<div id='message'>Data for $name inserted successfully!</div>";
} else {
echo "<div id='message'>An error occurred!</div>";
}

Passing Data from form with Ajax

Wondering if someone could help me. I have next to no knowledge with Ajax, and after many attempts at trying to pass my User1_id and Text through to my insert.php I've had no luck with inserting the data I want to my database.
As my profile.php and insert.php stands, the form submits to the database, but when the user submits the form it navigates to the insert.php and would rather have the Ajax send the data and stay on the Profile.php at all times, I feel this is a much better approach when creating such functions.
I'm wondering if someone can guide me in the right direction on how I'd go about doing this.
Profile.php Form
<form id="FormId" action="" method="get">
<input type="hidden" value="<? echo $user1_id ?>">
<textarea placeholder="Whats New??" id="FormId" name="status"></textarea>
<input type="submit" name="Submit" value="Submit">
</form>
Insert.php
<?
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
include "db_connect.php";
if (isset($_GET['status'])) {
$status = $_GET['status'];
}
$user1_id=$_SESSION['id'];
if ($_GET['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I know I need something similiar to this.. But I think I'm stuck more on the var/data part.
$("form#myFormId").submit(function() {
var mydata = $("form#myFormId").serialize();
alert(mydata); // it's only for test
$.ajax({
type: "GET",
url: "insert.php",
data: mydata,
success: function(response, textStatus, xhr) {
alert("success");
},
error: function(xhr, textStatus, errorThrown) {
alert("error");
}
});
return false;
});
But don't know how to go about it.
Any guidence is appreciated. Not asking anyone to write the code out for me. But good direction is welcomed.
Thanks.
Change your ajax part to:
$("form#myFormId").submit(function(e) {
e.preventDefault(); //prevent default submit
........
Your hidden input should have name
<input name="userId" type="hidden" value="<? echo $user1_id ?>">
And in php,
$userId = $_GET["userId"];
Change id of textarea, its same to your formid and ids need to be unique,
so change your textarea id, and You can try passing data as:
$.ajax({
type: "GET",
url: "insert.php",
data:"status="+$("#yourTextareaId").val()+"&userId="+$("#yourHiddenInputId").val(),
......
Just like to say thank you to both of you for your time and help. I re-wrote the code and have now got it working.
Here is the final code
PROFILE.PHP/JS
<script type="text/javascript">
function createstatus(content){
$.post("insert.php", { user1_id: content } );
refreshstream();
}
function createwallpost(content,user1_id){
$.ajax({
type: "POST",
url: "insert.php",
data: "status="+content+"&user1_id="+user1_id,
success: function(){
document.location = document.location;
}
});
}
</script>
<form action="insert.php" method="POST" target="ifr1" class="form_statusinput">
<input type="hidden" name="user1_id" value="<?php echo $user1_id ?>">
<input type="text" name="status" id="status" class="homescreen_status_input" placeholder="Say something">
<iframe name="ifr1" id="ifr1" style="display:none;"></iframe>
</form>
INSERT.PHP
<?
session_start();
include "db_connect.php";
if (isset($_POST['status'])) {
$status = $_POST['status'];
}
$user1_id = $_POST['user1_id'];
if ($_POST['status']) {
$query = mysql_query("INSERT INTO feed (status,user1_id) VALUES ('$status', '$user1_id')") or die (mysql_error());
if($query){
echo "Posted Into Database";
}
exit();
}
?>
I decided to go with post instead of the GET method, as I feel its securer and passes more information through smoothly.
Thanks again.

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories