AJAX call not sending - php

I am trying to create my first AJAX call. All I am trying to do is send a message to my database that will hold a user_id, message, and date.
As of now nothing is even happening when I hit the submit button. Why is this not submitting and I'm not sure if I am creating the ajax call correctly.
What am I doing wrong?
My ajax call
$(document).ready(function () {
$("#submit_announcement").on("click", function () {
$user = this.value;
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: "username=" + $user,
success: function (text) {
if (text == "Error!") {
alert("Unable to get user info!");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Payment Status Changed!');
$('.announcement_success').delay(5000).fadeOut(400);
alert(data);
} else {
var txtArr = text.split('|');
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
}
});
});
});
The Form
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<textarea rows="4" cols="50" id="announcement_message " name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<input type="button" class="contactButton" value="Add Announcement" id="submit">
</label>
</form>
PHP file insert_announcements.php
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('isi', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}

You have the jquery selector for your button wrong, change it to:
$("#submit").on("click", function(){

You are triggering the click for an element with id #submit_announcement which is different from the id of your form submit button. Change $("#submit_announcement").on("click", function(){
to
$("#submit").on("click", function(){

In your PHP you cannot echo between } and else
}
echo "Announcement was added successfully!";
else

Use one of below event bind method :
$(document).ready(function(){
$("#submit").on("click", function(){ console.log('reached'); /* code here */ });
$('#insert_announcements').on('submit',function(){ /* code here */ })
})
One of above approach should work . Your ajax code looks fine . just use one of above event bind wrapper and let the magic happen .
Update
check working fiddle here : https://jsfiddle.net/hfddcop0/
Mistakes you were making
1) specifying wrong submit button id . it is submit_announcement instead of #submit
2) Unknown variable defined called usermessage . I have replaced it with string value in fiddle .
payload should be like
data : {'message':message,'anothermessgae':another} , You were mentioning like data : {'message':message;} which is a syntax error .

Because you're not creating the function when the submit button is clicked. The button id is submit
So try:
$(document).ready(function(){
$("#submit").on("click", function(){
$user = this.value;
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: "username="+$user,
success: function(text){
if(text == "Error!"){
alert("Unable to get user info!");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Payment Status Changed!');
$('.announcement_success').delay(5000).fadeOut(400);
alert(data);
} else {
var txtArr = text.split('|');
}
},
error: function(xhr, textStatus, errorThrown){
alert(textStatus + "|" + errorThrown);
}
});
});
});

You are not sending user_id, message, and date to server to get the response.
first get inputted values and then send.Like below:
var announcement_message = $("#announcement_message).val();
and instead of type,it should be method.Type in ajax is to define data type.
In html, remove method="post",define method only once.

$("#submit").on("click", function(){
var usermessage = $("#announcement_message).val();
var username = "ralph"; // let say you get the username value;
var date_now = Date.now();
$.ajax({
url:"insert_announcements.php",
method:"POST",
data:{
"user_id":username,
"message":usermessage,
"date":date_now
}
success:function(data){
console.log(data); // data object will return the response when status code is 200
},
error:function(){
console.log("error");//otherwise error if status code is other than 200.
}
});
});

Related

AJAX seems to be sending entire web page script rather than data

I am having real trouble with my AJAX request and I am not sure why. The following code seems to send to the entire web page script (as seen in both my alert box and in the console) rather than my checkbox values. Can anyone explain to me what I am doing wrong?
Here is my PHP checkbox, which has values generated by SQL, and has no submit button so the code is set up to run on change from the user:
<form id="numberOrderForm" action="testdatabase.php" method="post">
<div class="wrappers" id="multi-select1Wrapper">
<h2>Area Code</h2>
<select class="dropDownMenus" id="multi-select1" name="multi_select1[]" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
?>
</select>
</div>
</form>
And here is my jQuery AJAX code:
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>
your data is incorrect for one.
replace:
data: "areacode=" + areaCode,
with:
data: {"areacode": areaCode},
you should also add: enctype='multipart/form-data' to your form element
Please add following line on jquery ajax call
dataType: 'json'
contentType: "application/json",
After add above code your code is like below
<script>
$('#multi-select1').on("change", function(){
var areaCode = $(this).val();
$.ajax({
type:"POST",
url: "testdatabase.php", //my PHP database
data: "areacode=" + areaCode,
dataType: 'json',
contentType: "application/json",
success: function(response){
//do stuff after the AJAX calls successfully completes
alert (response);
console.log(response);
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
</script>

AJAX POST to PHP script

I'm trying to POST from my program to a separate PHP file, then grab that data and store it into my SQL database. I've checked my code over and over and can't' find what I'm doing wrong. Any help would be appreciated.
AJAX
$(".btn btn-success last").click(function(){
$.post("go2.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
PHP file (go2.php) w/ SQL code
<?php
include 'connection.php';
$x = $_POST["name"];
$sql = "INSERT INTO users (Username) VALUES ('$x') ";
$query = mysql_query($sql);
?>
From your code ..
you need to learn a little bit more about selectors
$(".btn btn-success last") // what is btn-success ID or Class and
//What is last ID or Class for id use #btn-success for class use .btn-success
before you insert anything to php file check if this file already connected with js or not .. and with the next code you should get alert with 'file already connected'
$(".btn .btn-success .last").click(function(){
$.post("go2.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data){
alert(data);
});
});
and in php
<?php
echo('file already connected');
?>
Most important thing to know what is a (.last) is that a button or form or anchor
if .last is form
$(".btn .btn-success .last").on('submit',function(e){
e.preventDefault();
return false;
});
if .last is button or anchor
$(".btn .btn-success .last").on('click',function(e){
e.preventDefault();
return false;
});
hope it will help
Try the long version of ajax request
$(document).ready( function () {
$(".btn btn-success last").click(function(){
$.ajax({
type: "POST",
url: "go2.php",
data: {name:"Donald Duck", city:"Duckburg"},
success: function(data){
document.getElementById('divId').html(data);
}
});
});
});
For the echo data, you have to echo a message in your go2.php like "Success"

Post simple form with ajax and Json

I'm trying to get a form to work with Ajax and json but can't seem to work it out:(
If anyone can help out I'd really appreciate it! Been reading so many different tutorials but not getting it right.
In my index.php I have a form with only a image that works as a button.
Then in another file (allFunctions.php) I have a class. Within that class I have a function called
giveCandy() which is connected to the button.
Then I have a js file that I'm now trying to get working with this. But When I click the button the page still refreshes and I get the value true printed out.
UPDATE: Still problem with the page refreshing...
The index.php file:
<form action="index.php" method="POST">
<input type="hidden" name="candy" />
<input type="image" id="button_candy" class="four columns" src="views/img/candy.png"/>
</form>
Then in my functions file:
function giveCandy ()
{
if ( isset($_POST['candy']))
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$candyPiece = 10;
$query = $db->prepare("SELECT fullness, lastfed FROM userdata WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
$data = $query->fetch();
$newFullness = $candyPiece + $data['fullness'];
try
{
$query = $db->prepare("UPDATE userdata SET fullness = $newFullness, lastfed = CURRENT_TIMESTAMP WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
//$this->calculateFullness();
echo json_encode($query);
}
catch (PDOException $e)
{
echo 'Sorry iti could not eat at this time';
}
}
}
Then the js file:
$(document).ready(function () {
$('#button_candy').click(function (event) {
event.preventDefault();
$.ajax({
url: 'index.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#query').fadeOut(function () {
$('#query').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});
allFunctions.php:
if ($_POST['candy']) {
allFunctions::giveCandy();
}
class allFunctions {
static function giveCandy ()
{
$db = Database::getInstance();
// ....
Js:
$(document).ready(function () {
$('#button_candy').submit(function (event) {
event.preventDefault();
$.ajax({
url: '../model/allFunctions.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#result').fadeOut(function () {
$('#result').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});

jQuery serialized data not being inserted into the database

I have three things going on.
I am sending information to jQuery using the following HTML form.
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
This is the jQuery script that I am using to post such serialized information into the database.
$('button').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(){
alert("Done");
}
});
});
This is the PHP that inserts the information into the database.
$name = $_POST['name'];
$location = $_POST['location'];
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
This does not work. I click the button and nothing happens. The alert does not fire. Can anyone lead me the right direction as to why my code is not working?
This does not work. I click the button and nothing happens. The alert
does not fire
Are you totally sure that click handler works? You must ensure that it works firstly, like,
$('button').click(function () {
alert('It works');
});
If it works, then you can move on. Otherwise check if its inside DOMReady $(function(){ ... }) and that jquery.js is loaded.
Assuming that it works,
How do you know what your PHP script returns? You simply assume that it "should work", here:
success: function(){
alert("Done");
}
success() method actually holds a variable that is response that comes from the server side. It should be rewritten as,
success: function(serverResponse){
alert(serverResponse);
}
As for PHP script,
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
You only handling failure by 'echoing' error messages. You do not handle a situation when mysqli_query() returns TRUE. You should send something like 1 that indicates success.
And finally your code should look like this,
$('#submit_note').click(function() {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(serverResponse) {
if (serverResponse == "1") {
alert('Added. Thank you');
} else {
// A response wasn't "1", then its an error
alert('Server returned an error ' + serverResponse);
}
}
});
});
PHP:
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die(mysqli_error($connection));
} else {
die("1"); // That means success
}
/**
* Was it $connection or $link?! Jeez, you were using both.
*
*/
The callback function that you specified in your $.ajax call will only fire when a response is received from the server. Since you never send anything back to the client from the server after the data is inserted into the database, the client never calls alert("Done");. Add a line to your PHP file that sends a response to the client after a successful SQL insertion. The response can be as simple as a JSON object that says {'status': 'success'}.
You should apply a better way to handle your form. The serialize() helps, but it is better to work the data into a JSON string. When using JSO you will also need to set the dataType in the ajax call.
$('#note_add').submit(function (event) {
event.preventDefault();
var formdata = $('#note_add').serializeArray();
var formobject = {};
$(formdata).each(function (event) {
formobject[formdata[event].name] = formdata[event].value;
});
var data = {
action: "formsend",
json: JSON.stringify(formobject)
};
//* * send with ajax * *
function sendajax(data) {
var deferred = $.ajax({
method: "post",
url: "ajax.php",
dataType: "json",
data: data
});
return deferred.promise();
}
sendajax(formdata).done(function (response) {
console.log(response);
if (response.success == true) {
alert("Done!");
}
})
});
catch with PHP
if(isset($_POST['action']) && $_POST['action'] == 'formsend') {
$data = json_decode($_POST['json'];
// here you can now access the $data with the fieldnames
$name = $data->name;
$location = $data->location;
// Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: '.mysqli_error($link));
}
if (mysqli_affected_rows($connection) > 0) {
echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}
Add the following lines to your php file to send the response back:
HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');
HttpResponse::setData("<html>Success</html>");
HttpResponse::send();
flush();
change the ajax call as follows to see the result:
$('#submit_note').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(respData) {
console.log('Response:', respData)
alert("Done");
}
});
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<title></title>
</head>
<body>
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
<div id="response"> </div>
</body>
<script type="text/javascript">
$("#submit_note").click(function() {
var url = "post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#note_add").serialize(), // serializes the form's elements.
success: function(data)
{
$('#response').empty();
$('#response').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</html>
post.php
// Insert here your connection path
<?php
if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
{
$name = addslashes(trim($_REQUEST['name']));
$location = addslashes(trim($_REQUEST['location']));
$sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
echo "1 record added";
}
?>

ajax - check if a username exists + return message if it does

im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.
I'm having some trouble and have a few questions.
I have my input field plus js:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').on('blur', checkdb);
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: 'desiredUsername='+desiredUsername,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
});
</script>
<input type="text" name="username" id="username">
and my check-db.php file:
$mysqli = mysqli_connect("localhost","connection info");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$desiredUsername = $_POST['desiredUsername'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' ");
$stmt->bind_param('s', $desiredUsername);
$stmt->execute();
firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?
then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?
thanks!
On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :
echo json_encode($datas); //can be array or whatever
Then on the Client side :
$.ajax({
method: 'POST',
dataType:'json',
data: {'username' : desiredUsername}, //then getting $_POST['username']
success: function(datas) {
console.log(datas); //Your previous data from the server side
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
try
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: {
desiredUsername: desiredUsername
},
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
You have an error when sending the data, you should send a JS Object as data, like this:
data: { desiredUsername: desiredUsername },

Categories