Jquery ajax Post is not working? - javascript

I have used ajax post without form. When I click submit button it should get the values of other fields. Post request is not being sent and neither output is being shown. It is returning this error Unexpected identifier
Here are the input fields
<input type="text" name="name" id="name" class="center-block Ename" placeholder="Enter you name">
<textarea class="center-block" name="message" id="message" rows="1" placeholder="Enter your message"></textarea>
<input class="center-block sendBtn" type="submit" id="submit" name="submit" value="Submit">
This is the ajax request.
$(document).ready(function(){
var interval = setInterval($('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}),1000);
});
It is sending request to this php page
<?php
include 'db.php';
//Here post data is being assigned to variables
$name = $_POST['name'];
$message = $_POST['message'];
$queryInsert = "INSERT INTO chat(`name`, `message`) VALUES('$name', '$message')";
$queryInsertRun = mysqli_query($con, $queryInsert);
if(!$queryInsertRun){
echo mysqli_error($con);
}
//Here is the output which should be shown
$query = "SELECT * FROM `chat` ORDER BY `name` AND `message` DESC ";
$queryRun = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($queryRun)){
$name = $row['name'];
$message = $row['message'];
?>
<span class="name" style="font-weight: bold"><?php echo $name?>:</span>
<span class="message"><?php echo $message.'<br>'?></span>
<hr>
<?php
}
?>
I want to know that why is this not working.

try this code
function ajaxcall()
{
console.log('i am called');
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
}
$(document).ready(function(){
var id = setInterval(function() {
ajaxcall();
}, 1000);
});
http://jsfiddle.net/cod7ceho/116/

You want to display data if you clicked submit button , use simple click function . Using setInterval can't help you for clicking submit .
JS
$(document).ready(function(){
$('#submit').click(function(){
var values = {
'name': document.getElementById('name').value,
'message': document.getElementById('message').value
};
$.ajax({
type: "POST",
url: "chat.php",
data: values,
success: function(data){
$("#chat").html(data);
}
});
});
});

It sounds like your JSON Data is not valid.
var data = JSON.stringify(values);
var request = $.ajax({
url: "script.php",
method: "POST",
data: data,
dataType: "html" // read about dataType
});

Related

My server side php doesn't get the data from my client side AJAX requiest

Here is my AJAX code:
$("#loginbutton").click(function(){
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: { email:email, password:password},
success: function(data){
$("#samplediv").innerHTML ="Welcome";
}
});
});
And this is my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
if(isset($_POST['email'])){
echo $_POST['email'];
}
?>
As you can see it will be a login system, but the php doesn't write out the $_POST['email']
variable. I think it is probably a syntax mistake, just I am too blind. I would really appreciate it if somebody can help me.
UPDATE:
Here is my whole php code, i think it's not relevant, but this is ther reason, why i use dataType: json.
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
if(isset($_POST['email'])){
echo $_POST['email'];
}/*
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(!empty($_POST['email']) && !empty($_POST['password'])){
$email = $_POST['email'];
$password = md5($_POST['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'];
}
}
//echo json_encode($results);*/
?>
In your data object, your keys are not strings, but the variables that you have defined. Do it like that to have email and password taken literally:
data: { 'email':email, 'password':password},
i think this is a cross origin problem, but normaly this is shown in console. append a error ouput to your json and look for it, if it's a php error you will get noticed now.
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: { email:email, password:password},
success: function(data){
$("#samplediv").innerHTML ="Welcome";
},
error: function (jqXHR, textStatus, errorThrown) {{
console.error('ajax response failed');
console.log(jqXHR.responseText);
}
});
$("#samplediv").innerHTML ="Welcome"; is wrong
you have a jquery element here and try to access with vanilla functions.
$("#samplediv").text("Welcome");
// or
$("#samplediv")[0].innerHTML = "Welcome";
if you open your browsers dev tools it should show you the error:
innerHTML is not a function of ...
-> make sure you call jQuery though :)
-> added document ready
-> added prevent default
-> use input instead of button is only my convenience
<script type="text/javascript">
$(document).ready( function() { /* only when everything is set up */
$("#loginbutton").click(function(e){
e.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: "login.php",
method: "POST", /* changed to `method` */
data: "email="+email+"&password="+password, /* MODIFIED */
success: function(data){
alert(data);
$("#samplediv").html("Welcome !");
},
error: function (request, status, error) { /* added error handling */
alert(request.responseText);
}
});
});
});
</script>
<div id="samplediv"></div>
<form action="#" id="form" method="post">
<p><input type="text" name="email" id="email" value="" /> email</p>
<p><input type="text" name="password" id="password" value="" /> pwd</p>
<input type="submit" id="loginbutton" value="GO" />
</form>
of course, make the input password type !
As I don't know why you connect (possible select ?) with DB, I just made php file simple, as follows :
<?php
/* login.php */
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_POST['email'];
$pwd = $_POST['password'];
echo"[ email > $email / pwd : $pwd ]"; /* for example only, of course, not with real credentials */
?>
after edit of the original question, I saw php code and I would recommand
NOT using MD5 anymore but password_hash / password_verify
you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection

Jquery post... doesnt post anything

I had a form that sent an email via ajax, which had been running smoothly for years. Suddenly, nothing is posted, and I do not understand why.
THE JS:
var name = $("input#name").val();
var email = $("input#email").val();
var telephone = $("input#telephone").val();
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
}
});
Process.php:
<?php
if ($_POST) {
$name = $_POST['name'];
echo : $name;
}
else {
echo 'Nothing is posted';
}
?>
Everytime i use the form, the ajax "works", but "Nothing is posted" appears. I can't find an explanation...
For information, I use Jquery 3.1.1, and PHP 7.0
the correct way of implementing jQuery ajax is:
var name = $("input#name").val();
var email = $("input#email").val();
var telephone = $("input#telephone").val();
var message = $("textarea#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name:name,
email:email,
phone:phone,
message:message
},
});
And the php should be:
<?php
if ($_POST) {
$name = $_POST['name'];
echo $name;
}
else {
echo 'Nothing is posted';
}
?>
jQuery changed type to method in version 1.9. Try changing the ajax call to this:
$.ajax({
method: "POST",
url: "process.php",
data: ...
});
Try this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// POST
} else {
// GET
}

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?

Insert record into mysql using json

I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?
Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.

The data entered in the fields doesn't go to database, but I get a success message

I have this form in a modal with only two fields. I used JavaScript function for PHP script. When I click on Submit, I get a Success Message, but the my database is blank.
<?php
require "database_connection.php";
$error = array();
if (isset($_POST['aid'], $_POST['eventList']))
{
if (empty($_POST['aid']))
$error[] = 'Please Enter a name';
else
{
$query = "INSERT INTO event (Memberid, events) VALUES (?, ?)";
if ($stmt = mysqli_prepare($dbc, $query))
{
mysqli_stmt_bind_param($stmt, 'is', $_POST['aid'], $_POST['eventList']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo 'Success';
}
}
}
?>
JavaScript Submit code:
<script type="text/javascript" >
$(function() {
$(".submit").click(function(e) {
var aid = $("#aid").val();
var eventList = $("#eventList").val();
var dataString = 'aid='+ aid + '&eventList=' + eventList;
var data=$('#regPost').serialize()
if(aid=='' || eventList=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
console.log("ERROR");
}
else
{
console.log(dataString);
$.ajax({
type: "POST",
url: "ureg.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Code for forms:
<form method="post" id="regPost" class="registration_form">
<center>Event Name: <select style="width:200px;" name="eventList" tabindex="5"><br>
<option value="select">Select Event</option>
<optgroup label="X Y Z">
<option value="B Bs">Bas</option>
<option value="Ea">Eas</option>
<option value="So">So</option>
</optgroup>
</select> <br>
ID:<input type="text" name="aid"><br/>
<input type="submit" value="SUBMIT" class="submit"></center>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</form>
you have written the following code
var data=$('#regPost').serialize();
pass this data in the ajax request instead of datastring as
$.ajax({
type: "POST",
url: "ureg.php",
data: data,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
Your code does not take into account if the query was successful. First, your PHP returns "success" after it attempts to query the database regardless of if it succeeds. You should look into mysqli_errno.
Secondly, your AJAX call assumes a success no matter what the response is. You could return "fail" or even an empty string "" and as long as it comes back with a 200 status header, the success function will fire. Consider adding a failure function on your AJAX call and returning a 400 status code from PHP in the event of failure.
http_response_code(400);
-- Edit --
This is not something I actually tested, but should get you going in the right direction.
Server-side:
if (isset($_POST['aid'], $_POST['eventList']))
{
if (empty($_POST['aid']))
$error[] = 'Please Enter a name';
else
{
$query = "INSERT INTO event (Memberid, events) VALUES (?, ?)";
if ($stmt = mysqli_prepare($dbc, $query))
{
mysqli_stmt_bind_param($stmt, 'is', $_POST['aid'], $_POST['eventList']);
mysqli_stmt_execute($stmt);
$error = mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
if ( $error ){
http_response_code(400);
echo json_encode(array('error' => $error));
}else{
http_response_code(200);
}
}
}
}
?>
JavaScript:
<script type="text/javascript" >
$(function() {
$(".submit").click(function(e) {
var aid = $("#aid").val();
var eventList = $("#eventList").val();
var dataString = 'aid='+ aid + '&eventList=' + eventList;
var data=$('#regPost').serialize()
if(aid=='' || eventList=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
console.log("ERROR");
}
else
{
console.log(dataString);
$.ajax({
type: "POST",
url: "ureg.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function(){
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
}
return false;
});
});
</script>

Categories