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);
}
});
Related
I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}
This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.
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.
I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.
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 ;)