Loading data from a server using jquery $.post - javascript

What im about to do is to send data to the server through a form and to a php-script. Then I want to get it back and place it in the right spot using Jquery. I don't know why, but this solution doesnt seem to work as im just getting the "No text in the textbox!". Does someone have any tips?
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event) {
$.post("target.php", {
melding: $("#input").val().
}, function(data){
$("#meldinger").after("<div>" + data + "</div>");
});
event.preventDefault();
});
});
document.getElementById('demo').innerHTML = date();
</script>
<title>Meldingssystem</title>
</head>
<body>
<h1>Meldingsutveksling</h1>
<form action="target.php" method="post">
<textarea id="input" name="input" cols="40" rows="2"></textarea>
<br/><input type="submit" name="submit" value="Send">
</form>
<h2>Meldinger</h2>
<div id="meldinger">
</div>
</body>
</html>
PHP
<?php
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
?>

This
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
Should be
if (!empty($_POST['melding'])) {
$melding = $_POST['melding'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
because there is no input POST parameter sent

first, please read https://api.jquery.com/jquery.post/
your php script expects data in the input field. but your jquery POST doesn't put anything in an input field.
instead try something like:
$.ajax({
data: {
input: $("#input").val()
},
datatype: "text",
method: "POST",
success: function(data, status, xhr) {
$("#meldinger").after("<div>" + data + "</div>");
},
error: function(xhr, status, error) {
alert("zog zog");
}
};
Notice that input is present in the data parameter.

Related

AJAX success function works, but file isn't running

I'm new to StackOverflow, web development, and I'm low on time for this assignment, so I apologize if I'm a bit slower at understanding web development vocabulary and any answers or tips. I'm having trouble with calling another php file through ajax.
index.php:
<!--------------------------- HTML STARTUP ----------------------------------->
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="finalproject.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="finalproject.js"></script>
<title>Final Project</title>
</head>
<body>
<!--------------------------- LOGIN ------------------------------------------>
<?php
require_once 'dbconnection.php';
//----------------------- CREATE USERS TABLE -----------------------------------
$userspass = "CREATE TABLE usersPass (
userID VARCHAR(60),
password VARCHAR(60)
);";
$connected->query($userspass);
$selectAllInfo = "SELECT * FROM usersPass;";
$connected->query($selectAllInfo);
//-------------------------- LOG IN OR REGISTER --------------------------------
?>
<form id="trial"><button onclick="OpenRegister()">Sign Up!</button>
<script>
$(document).on("click" , "#Register", function(e)
{
var datastring = $("#trial").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert('Sign Up function is a success!');
}
});
e.preventDefault();
});
</script></form>
<br/><br/>
<button onclick="InputInfo()">Login</button>
<?php
$connected->close();
?>
</body>
</html>
And here's the JavaScript when the function is called.
finalproject.js:
/*jslint browser: true*/
/*global $, jQuery, alert*/
function OpenRegister() {
'use strict';
$('form').append("<div id=SignInContainer>
<span style='font-size: 20px'>UserID</span>
<input type='text' name='UserID' value='Type userID here...'>
<span style='font-size: 20px'>Password</span>
<input type='text' name='UserID' value='Type password here...'>
<button id='Register'>Submit</button>
</div>");
}
$(document).ready(function () {
'use strict';
$(document).on('focus', 'input', function () {
$('input').focus(function () {
$(this).val('');
});
});
});
And this is the php file I'm trying to load. userlogin.php:
<?php echo "If this displays, you win." ?>
dbconnection.php
<?php
$connected = new mysqli('localhost', 'Username', 'Password', 'Username');
mysqli_select_db($connected, 'cferna50');
// Check connection
if ($connected->connect_error) {
die("Connection failed: " . $connected->connect_error);
}
I'm just trying to get the "userlogin.php"file to run through AJAX. I'm running this thing on Chrome. I've heard that there is a bit of a problem with using AJAX on local files, but I tried that --access-file-from-files thing and it didn't help. I tried running it on FireFox and Internet Explorer and it still doesn't help. I'm sure I have everything in the same directory. I'm using an online school server thing to do all this. I've been hurting my head over this for endless hours, any help would GREATLY be appreciated.
Simply because you are not passing (data) through the method, either you Serialize the data or pass them individually, and i suppose you will use the first method to save time
<script>
$(document).on("submit","#loginForm", function(e)
{
var datastring = $("#loginForm").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert(data);
//or
//alert('Sign Up function is a success!');
},
error: function(){
alert("error handling");
}
});
e.preventDefault();
});
</script>
HTML
<form id="loginForm" method="POST">
<input type="text" name="userid" id="userid" placeholder="user ID" />
<input type="text" name="password" id="password" placeholder="Password" />
<button type="submit" >Submit</button>
</form>
PHP
<?php
if(isset($_POST['userid'])){
$username = $_POST['userid'];
$pass = $_POST['password'];
//do your magic now
}
?>
Correct concatenation of html string at .append() remove if($("#Register").click())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function SignUp() {
if ($("[name=username]").val().length
&& $("[name=password]").val().length) {
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: {
username: $("[name=username]").val(),
password: $("[name=password]").val()
},
success: function(data) {
alert('Sign Up function is a success!');
},
error: function() {
alert("stacsnippets success")
}
});
}
}
</script>
<script>
function OpenRegister() {
'use strict';
$('body').append("<div id=SignInContainer>"
+ "<span style='font-size: 20px'>UserID</span>"
+ "<input type='text' name='username' placeholder='Type userID here...'>"
+ "<span style='font-size: 20px'>Password</span>"
+ "<input type='password' name='password' placeholder='Type password here...'>"
+ "<button onclick='SignUp()' id='Register'>Submit</button>"
+ "</div>");
}
</script>
<button onclick="OpenRegister()">Sign Up!</button>
php
if (isset($_POST["username"]) && isset($_POST["password"])) {
// do username, password validation stuff here
}
jsfiddle https://jsfiddle.net/qnrnn5b5/

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

php ajax form submit ..nothing happens

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?
I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine
Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

How do I validate my form within PHP via JQuery Ajax call?

How do I validate my code in PHP without getting error messages defined in the ajax definition in main.js?
Note: Chrome console returning:
XMLHttpRequest cannot load file:///C:/Documents/Mini%20Revision%20Projects/Project%20Website%203/ajax.php. Received an invalid response. Origin 'null' is therefore not allowed access.
Below is my code:
main.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="C:\Documents\jQuery\jquery2.js"></script>
</head>
<body>
<ul id="info1">
<li>Put anything in the field below.</li>
</ul>
<form id="form1">
<input type="text" name="field1" id="field1">
<input type="submit" name="submit" id="submit" value="Submit Form">
</form>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
$(document).ready(function() {
$("#form1").submit(function( event ) {
event.preventDefault();
//alert("happy");
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$("#info1").html(data.msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});
});
ajax.php
<?php
class ajaxValidate {
function formValidate() {
//Put form elements into post variables (this is where you would sanitize your data)
$field1 = #$_POST['field1'];
//Establish values that will be returned via ajax
$return = array();
$return['msg'] = '';
$return['error'] = false;
//Begin form validation functionality
if (!isset($field1) || empty($field1)){
$return['error'] = true;
$return['msg'] .= '<li>Error: Field1 is empty.</li>';
}
//Begin form success functionality
if ($return['error'] === false){
$return['msg'] = '<li>Success Message</li>';
}
//Return json encoded results
return json_encode($return);
}
}
$ajaxValidate = new ajaxValidate;
echo $ajaxValidate->formValidate();
?>
First of all, verify if PHP is not returning a warning or critical error. Insert this code in top of your code. If PHP returns a hidden error, the success data value will be null.
ini_set("display_errors", "On");
error_reporting(E_ALL);
PHP Error reporting manual
PHP run-time display_error
I think that if you are returning a JSON array in php, you need to call an array.
$("#info1").html(data['msg']);
Try to return the post values to verify if $_POST is not empty:
return json_encode($_POST);
You don't need to define an empty array if you define directly a first row.
//$return = array();
$return['msg'] = '';
you need to have PHP server in order to PHP scripts to work. install something like XAMPP (windows) or MAMP (linux)

How to pass data to PHP page through AJAX and then display that page in another's DIV?

I have 2 pages with which I am working with: test1.php and test2.php. test1.php contains 2 <DIV> tags, one named "SubmitDiv" and the other named "DisplayDiv". In SubmitDiv, there is a check box and a submit button. When the check box is checked and the submit button is clicked, I would like it to display test2.php in the DisplayDiv div tag. I have figured that much already.
However, now I want test2.php to receive data from test1.php and process that data. In this case, it is receiving the checkbox's name, "chk" and will be printing that with an echo command. This is where I am a bit stumped as to how to go about this. After searching a bit for an answer, this is what I have written so far:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
function sendQuery() {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function() {
$('#DisplayDiv').load('test2.php');
}
});
return false;
}
</script>
<body>
<form id="SubmitForm" action="" method="post">
<div id="SubmitDiv" style="background-color:black;color:white;">
<input type="checkbox" id="chk" name="chk" form="SubmitForm" value="chk">CHECK</input><br>
<button name="submit" id="submit" type="submit" form="SubmitForm" onclick="return sendQuery();">Submit</button>
</div>
</form>
<div id="DisplayDiv"></div>
</body>
</html>
test2.php:
<html>
<meta charset="utf-8">
<?php
$chk = $_POST['chk'];
echo $chk;
?>
</html>
When the submit button is clicked, however, all it does is refresh the page, rather than display the test2.php in the DisplayDiv like it's supposed to. Any ideas on how to pass the data to test2.php and then also display it within the DisplayDiv section?
Instead of .load function use the following
success: function(response) {
$('#DisplayDiv').html(response);
}
If you want to use e.preventDefault(); you must pass the event to the function
function sendQuery(e) {
e.preventDefault();
//...
}
Otherwise I assume your form is simply submitted on click.
You must first remove e.preventDefault(); in the sendQuery function because that is failing to return false onclick.
Then change your AJAX call to as follows:
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function(data) {
$("#DisplayDiv").html(data);
}
});
This works:
$.ajax({
type: 'GET',
url: 'data.php',
data: {
"id": 123,
"name": "abc",
"email": "abc#gmail.com"
},
success: function (ccc) {
alert(ccc);
$("#result").html(ccc);
}
});
Include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
data.php
echo $id = $_GET['id'];
echo $name = $_GET['name'];
echo $email = $_GET['email'];

Categories

Resources