I have crated a sample web service to store and retrieve data. The PHP web service has 2 scripts called getData.php and saveData.php, getData returns a json response and saveData saves the json object to database.
getData.php
<?php
require_once ('../database.php');
mysqli_select_db($conn, $database);
$query = "SELECT * FROM user ORDER BY id ASC";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$rows = array();
while($packages = mysqli_fetch_assoc($result)) {
array_push($rows, $packages);
}
header('Content-type: application/json');
echo json_encode($rows);
?>
saveData.php
<?php
require_once ('../database.php');
mysqli_select_db($conn, $database);
if (isset($_POST['json'])) {
$jsonObj = $_POST['json'];
$jsonObj = json_decode($jsonObj);
$query = "INSERT INTO user (first_name, last_name, description)"
. " VALUES ('".$jsonObj->{'first_name'}."', '".$jsonObj->{'last_name'}."', '".$jsonObj->{'description'}."')";
mysqli_query($conn, $query);
header('Content-type: application/json');
echo json_encode($_POST['json']);
}
?>
this is inside my wamp/www folder in a folder called testService. Then i have another folder called testConsume where it has the html page with a simple form that sends the data to the testService/saveData.php file.
HTML
<form role="form">
<div class="form-group">
<input name="first_name" id="txtFirstName" class="form-control" placeholder="First Name" type="text" />
</div>
<div class="form-group">
<input name="last_name" id="txtLastName" class="form-control" placeholder="Last Name" type="text" />
</div>
<div class="form-group">
<input name="description" id="txtDescription" class="form-control" placeholder="Description" type="text" />
</div>
<a id="submit" class="btn btn-success" onclick="sendData()">Submit</a>
</form>
in the script the sendData() function takes the data and send it as a json object
function sendData() {
var firstName = $('#txtFirstName').val();
var lastName = $('#txtLastName').val();
var description = $('#txtDescription').val();
var jqxhr = $.ajax({
url: 'http://localhost:8080/testService/json/saveData.php',
type: 'POST',
contentType: 'application/json',
data: { json: JSON.stringify({
first_name: firstName,
last_name: lastName,
description: description
})},
dataType: 'json'
});
jqxhr.done(function() {
alert("Success! " + firstName + " " + lastName + " is a " + description);
});
jqxhr.fail(function() {
alert("Failed");
});
}
When i run the testConsume/index.html and click on submit, the alert message Failed shows. And when i check the database there is no data added. What am i doing wrong?
Remove contentType: 'application/json'.
You are sending JSON embedded in application/x-www-form-urlencoded data, not plain JSON.
Alternatively. Send and parse actual plain JSON:
contentType: 'application/json',
data: JSON.stringify({
first_name: firstName,
last_name: lastName,
description: description
}),
And in your PHP:
if (stripos($_SERVER["HTTP_CONTENT_TYPE"], "application/json")===0) {
$jsonObj = json_decode(file_get_contents("php://input"));
}
Related
I've been searching for weeks a solution to my trouble within the community and tutorials but I can't find answers.
I've created a form to register subscribers for a newsletter to my WordPress database. Using PHP only, POST datas were send to the database. However, I wanted to use that form with ajax, to stop the page from refreshing. Now, no datas are send to the database anymore and I don't understand why.
With the code below, I get the following informations in console :
first_name=Claire&last_name=Lavigne&email=lavigneclaire81%40gmail.com®ister=newsletter
POST http://localhost//wp/wp-admin/admin-ajax.php 400 (Bad Request)
error [object Object] Bad Request
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="col s12 m6 newsletter">
<div id="form_output"></div>
<form id="newsletter" class="newsletter__form">
<div>
<input value="" type="text" name="first_name" id="first_name" placeholder="Prénom" autocomplete="given-name">
<input value="" type="text" name="last_name" id="last_name" placeholder="Nom" autocomplete="family-name">
<input value="" type="email" name="email" id="email" placeholder="Email">
</div>
<button class="newsletter__button" type="submit">Je m'abonne</button>
<input type="hidden" name="register" value="newsletter" />
</form>
</div>
$('#newsletter').on('submit', function(event) {
event.preventDefault();
var datas = $(this).serialize();
console.log(datas);
$.ajax({
type: "POST",
url: ajaxurl,
data: datas,
// data: {
// action: 'ajax_newsletter'
// },
success: function(data, result) {
console.log(result + ' ' + data);
$("#form_output").html('Ok');
},
error: function(data, result, error) {
console.log(result + ' ' + data + ' ' + error);
$("#form_output").html('Erreur');
},
});
});
<?php
function eglise_scripts()
{
wp_enqueue_style(
'eglise-style-css',
get_theme_file_uri('/public/css/style.css'),
[],
'1.0.0'
);
wp_enqueue_script(
'eglise-js',
get_theme_file_uri('/public/js/app.js'),
[],
'1.0.0',
true
);
wp_localize_script(
'eglise-js',
'ajaxurl',
admin_url( 'admin-ajax.php' )
);
}
add_action('wp_enqueue_scripts', 'eglise_scripts');
add_action('wp_ajax_nopriv_ajax_newsletter', 'ajax_newsletter');
add_action('wp_ajax_ajax_newsletter', 'ajax_newsletter');
function ajax_newsletter()
{
global $wpdb;
$users = $wpdb->prefix . 'users';
if (isset($_POST['register']) && $_POST['register'] == 'newsletter') {
$first_name = $wpdb->escape(trim($_POST['first_name']));
$last_name = $wpdb->escape(trim($_POST['last_name']));
$email = $wpdb->escape(trim($_POST['email']));
if (empty($email) || empty($first_name) || empty($last_name)) {
echo 'Merci de compléter les champs.';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Addresse email invalide.';
} else if (email_exists($email)) {
echo 'Email déjà existant. ';
} else {
// create columns firstname and lastname
$row_firstname = $wpdb->get_results("SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'wp_users'
AND column_name = 'first_name'
");
$row_lastname = $wpdb->get_results("SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'wp_users'
AND column_name = 'last_name'
");
if (empty($row_firstname)) {
$wpdb->query("ALTER TABLE $users ADD first_name VARCHAR(255) NOT NULL");
} elseif (empty($row_lastname)) {
$wpdb->query("ALTER TABLE $users ADD last_name VARCHAR(255) NOT NULL");
}
// insert user
$newUser = $wpdb->INSERT($users, [
'first_name' => apply_filters('pre_user_first_name', $first_name),
'last_name' => apply_filters('pre_user_last_name', $last_name),
'user_email' => apply_filters('pre_user_user_email', $email),
'user_registered' => current_time('mysql')
]);
if (is_wp_error($newUser)) {
echo 'Une erreur s\'est produite.';
} else {
echo 'Vous êtes désormais inscrit';
}
}
}
wp_die();
}
If I change in my js file data: datas into data: { action: 'ajax_newsletter'}, I get the following informations in console :
first_name=Claire&last_name=Lavigne&email=lavigneclaire81%40gmail.com®ister=newsletter
success
In my wp_users database, nothing has been added.
If then, I comment the following conditions in my function ajax_newsletter() :
//if (isset($_POST['register']) && $_POST['register'] == 'newsletter') {
// if (empty($email) || empty($first_name) || empty($last_name)) {
// echo 'Merci de compléter les champs.';
// } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// echo 'Addresse email invalide.';
// } else if (email_exists($email)) {
// echo 'Email déjà existant. ';
// } else {
The console tells :
first_name=Claire&last_name=Lavigne&email=lavigneclaire81%40gmail.com®ister=newsletter
success
Vous êtes désormais inscrit
In my wp_users db a new empty line is added, with only the "id" and "current date and time of creation" completed.
--
Do you have any idea of what I'm doing wrong ? Thanks in advance for any help !
You need an "action" field to make WordPress AJAX work.
But you also need individual fields for your function.
Make a "newsletter" action, like wp_ajax example
Example:
$('#newsletter').on('submit', function(event) {
event.preventDefault();
var first_name = jQuery('#first_name').val();
var last_name = jQuery('#last_name').val();
var email = jQuery('#email').val();
var newsletter = jQuery("input[name=newsletter]").val();
$.ajax({
type: "POST",
url: ajaxurl,
data: {
name: name,
action: 'newsletter',
first_name: first_name,
last_name: last_name,
email: email,
newsletter : newsletter },
success: function(data, result) {
console.log(result + ' ' + data);
$("#form_output").html('Ok');
},
error: function(data, result, error) {
console.log(result + ' ' + data + ' ' + error);
$("#form_output").html('Erreur');
},
});
});
Then it should work.
I have a form from the front end that I am trying to submit to backend using ajax.
<form method="post" enctype="multipart/form-data" id="form_post">
<input type="hidden" name="name" id="name" class="name" value="ABC">
<input type="hidden" name="location" id="location" class="location" value="XYZ">
<textarea class="c-textarea desc" name="desc" id="desc" placeholder="Type your description"></textarea>
<input type="file" id="file" class="file" name="file" >
</form>
<script type="text/javascript">
$("#form_post").submit(function()
{
var formData = new FormData();
$f2 = $('#file');
formData.append('file', $f2.get(0).files[0]);
formData.append('name', name.value);
formData.append('location', location.value);
formData.append('desc', desc.value);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "class/send_data",
data: formData,
processData: false,
contentType: false,
success: function(res)
{
alert(res);
console.log(res);
},
error: function(errResponse)
{
console.log(errResponse);
}
});
return false;
});
</script>
In alert i am getting the value for desc but for name and location it is getting as undefined.
On backend i am fetching the values using following code
$data = array(
'name' = $this->input->post('name')
'location'->input->post('location')
'desc'->input->post('desc')
);
Can anyone please tell how i can fetch the values
As per my comment, you need to access the values sent via ajax using $_POST
<?php
$name = $_POST['name'];
$location = $_POST['location'];
echo $name.''.$location;
?>
EDIT
Change your data key in ajax call to
data: new FormData(this),
I'm making a login system to my website, but the browser says it is not secured: the browser's message
Heres is my html:
<div id="loginform">
Bejelentkezés
<input type="text" placeholder="E-mail" id="email"></input>
<input type="password" placeholder="Jelszó" id="password"></input>
<button id="loginbutton">Bejelentkezés</button>
<div id="errormsg"></div>
</div>
Here is my Ajax:
$("#loginbutton").click(function(){
var user ={
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
data: {"user": JSON.stringify(user)},
success: function(data){
if(data.success){
alert(data.user_id);
}
else{
document.getElementById("errormsg").innerHTML = "A bejelentkezés sikertelen";
}
}
});
});
And my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(isset($_POST['user'])){
$user = json_decode($_POST['user']);
$email = $user->email;
$password = md5($user->password);
$sql= "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."'";
$rowsql = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rowsql, MYSQLI_BOTH);
if(mysqli_num_rows($rowsql) == "1"){
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['fname'] = $row['fname'];
$_SESSION['lname'] = $row['lname'];
$results['success'] = true;
$results['user_id'] = $row['user_id'];
$results['fname'] = $row['fname'];
$results['lname'] = $row['lname'];
}
}
else{
$results['user_id']= "VAnbaj";
}
echo json_encode($results);
?>
It works, but i don't know how to make it safe.
I'd be glad if somebody can help me.
I you want to get rid of that warning message, you have to serve your site over https with a valid certificate.
This question already has answers here:
Why jQuery consider an 200 response Ajax request with empty content as fail()?
(2 answers)
Closed 6 years ago.
the following code returns a response to the error part of the ajax. What am I doing wrong?
JS code:
var firstName = $('input[name=first]').val(),
lastName = $('input[name=last]').val();
$.ajax({
url: "add-user.php",
type: "POST",
data: {
first: firstName,
last: lastName
},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err)
}
});
PHP code:
<?php
$dbConnect = mysqli_connect("localhost", "root", "password", "db");
$stmt = $dbConnect->prepare("INSERT INTO pokemon (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param('ss', $firstName, $lastName);
$firstName = $_POST['first'];
$lastName = $_POST['last'];
$stmt->execute();
?>
HTML:
<form action="" method="POST" name="addUser" class="user-input">
<label>First Name: <input type="text" name="first"></label> <br>
<label>Last Name: <input type="text" name="last"></label> <br>
<input type="submit" value="Submit" class="user-submit">
</form>
Submits to the database fine but the response comes back as an error:
Object {readyState: 0, status: 0, statusText: "error"}
You are assuming that php understands JSON out of the box -- it doesn't.
You will need to either convert your ajax to send "url-encoded" data, or get php to parse the body (that contains the JSON string).
you have to initialize the variables first.
<?php
$firstName = $_POST['first'];
$lastName = $_POST['last'];
$dbConnect = mysqli_connect("localhost", "root", "password", "db");
$stmt = $dbConnect->prepare("INSERT INTO pokemon (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param('ss', $firstName, $lastName);
$stmt->execute();
?>
make ajax like this
$("#userForm").submit(function(e){
url: "add-user.php",
type: "POST",
data: $(this).serialize(),
success:function(data){console.log(data);}
});
html
<form action="" method="POST" name="addUser" id="userForm" class="user-input">
<label>First Name: <input type="text" name="first"></label> <br>
<label>Last Name: <input type="text" name="last"></label> <br>
<input type="submit" value="Submit" class="user-submit">
</form>
So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );