Saving form value to database through ajax wordpress - javascript

How can I save data to database using ajax and form. I have working this for one day but still no luck I don't know what's wrong with this code I came up right now. This is one is wordpress
Here is the code:
This javascript was in the header.php
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {"action": "savedata", "MyUrlName":name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});
Here is the code in function.php
function savedata(){
$name = $_POST['MyUrlName'];
global $wpdb;
$table_name = $wpdb -> prefix . "save_url";
$wpdb->insert(
$table_name, array(
'name' => $_POST['MyUrlName']
),
array(
'%s'
)
);
return true;
exit();
}
add_action('wp_ajax_nopriv_savedata', 'savedata');
add_action('wp_ajax_savedata', 'savedata');
I'm implementing it in frontend
Thank you in advance

use this code
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {action: "savedata", MyUrlName:name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});

Related

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

Getting undefined value while submitting form through ajax

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),

Web development. Ajax

Can someone please guide me through where am I going wrong in this piece of code below
index.php :-
<script type="text/javascript">
function fun(){
alert("H");
$.ajax({
type: "POST",
url: 'test.php',
data: {name: 'Wayne', age: 27},
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
alert("HE");
}
</script>
<input type="button" value="submit" onclick="fun()" />
test.php :-
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo $name.$age;
?>
I'm not getting any output nor any error.
The problem is in the javascript code, specifically in how you're calling the function. Try this instead:
// javascript
document.getElementById('do-fun').addEventListener('click',function(){
fun();
});
// html
<input type="button" value="submit" id="do-fun" />

Sending data to php file AJAX

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 );

Ajax does not return any result

My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}
The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});
I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.
javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.

Categories

Resources