Post simple form with ajax and Json - php

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

Related

set name to widget's attribute in Twig

I have a field (called name), Every time i write in this field, an ajax script (live search sends data from twig to the controller without reloading) checks if the data already exist or not showing a message. My problem is that i could't set a name for this field, i tried this but it does not work
{{ form_label(form.name) }}
{{ form_widget(form.name,{'id':'name','attr':{'name':'name'}}) }}
{{ form_errors(form.name) }}
and here my function in the controller which i'm sure it works properly,
public function searchBackTeamAction(Request $request)
{
if($request->isXmlHttpRequest())
{
$serializer = new Serializer(array(new ObjectNormalizer()));
$em = $this->getDoctrine()->getManager();
$teams= $em->getRepository('TeamBundle:Team')->findOneBy(['name'=>$request->get('name') ]);
$data = $serializer->normalize($teams);
return new JsonResponse($data);
}
}
and here is my script i'm also sure that it works properly
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: $("#name").serialize(),
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
</script>
Could you please help me ?
Use following javascript
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: {"name": $("#name").val()},
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);

AJAX call not sending

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

jQuery AJAX call to Slim Framework PHP function pass parameter as null

I'm trying to use slim framework and when I do a POST to enter a record does absolutely nothing. I'm afraid I pass the parameter identified as null because if I allow it in the database, enter a null record.
this is mi Slim PHP.
$app-> post("/banda/", function() use($app){
$nombre=$app->request->post("nombre");
try{
$connection = getConnection();
$dbh = $connection->prepare("INSERT INTO banda VALUES(null, ?)");
$dbh->bindParam(1, $nombre);
$dbh->execute();
$banda = $connection->lastInsertId();
$connection= null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($banda));
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
});
And this is my JS
var API_URI = "http://localhost/banda/";
function limpiar() {
$("#form-band input:first-child").val("");
}
function nombreBandaEsVacia() {
return ($("#form-band input:first-child").val().length == 0);
}
function getBandaJSON() {
return JSON.stringify({
nombre: getBandaNombre()
});
}
function getBandaNombre() {
return $("#form-band input:first-child").val();
}
$("#form-band input:last-child").on("click", function createBanda() {
if (nombreBandaEsVacia()){
alert("Oops! Completa el formulario!");
}else{
// 1.2 JSON.Stringify
var banda = getBandaJSON();
};
$.ajax({
type:'POST',
crossDomain: true,
url:API_URI,
data:banda,
dataType:"json",
beforeSend: function() {
console.log(banda);
},
success:function(response, banda) {
limpiar();
},
error:function(jqXHR, data, textStatus, errorThrown) {
console.log(data);
console.log(errorThrown);
console.log(jqXHR);
console.log(textStatus);
}
});
});
My navigator say this:
http://s2.subirimagenes.com/imagen/previo/thump_91447311.png
By the look of it, you are sending a string to your php script instead of key-value pairs.
You can either use something like:
data: {'my_banda_json': banda},
and parse it at the server-side before you try to insert it.
Or you can just send what you need in a way that the back-end is now expecting it:
data: {'nombre': value_of_the_banda_name_field},

Ajax timed update issue

Simply I have a menu bar with an animated notification badge made by CSS and implemented by SPAN class on the HTML. this badge should show the count of new messages and disappear if that count is 0. I need to check that every 1 second but with no luck.
my js:
<script type="text/javascript">
function removeAnimation(){
setTimeout(function() {
$('.bubble').removeClass('animating')
}, 200);
}
setInterval(function() {
$.ajax({
type: 'GET',
url: 'models/bubble.php',
data: 'html',
success: function(response){
document.getElementById("bub").innerHTML=response;
document.getElementById("bub").className = "bubble";
}
error: function(response) {
document.getElementById("bub").className = "hidden";
});
}
}, 1000);
</script>
my php (working and tested):
<?php
require_once("db.php");
$receiver = $this_user
$isnew = 1;
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT * FROM messenger
WHERE receiver = ? AND isnew = ? ORDER BY timestamp")) {
$stmt->bind_param("si", $receiver,$isnew);
$stmt->execute();
$stmt->store_result();
$ttlrows = $stmt->num_rows;
$stmt->close();
}
echo $ttlrows;
?>
any help?
Below works for me. You need to call the function inside success again as setTimeout/setInterval will call the function only once after the delay you mentioned
setTimeout('pullNewMessageCount()', 100);
function pullNewMessageCount() {
var url = 'PHP Url';
$.ajax({
url: url,
dataType: 'html',
data:{
"whatever data you want to send, skip it if not require",
},
type: 'POST',
success: function(latestCount) {
setTimeout('pullNewMessageCount()', 100);// Important comment (this what you need to do)
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}

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