cannot send data by using ajax - php

i need in sert data by ajax , i have two pages, once is form that have icon that i click on it and send me to other page and insert new data
here the ajax code
<script type="text/javascript">
$(function() {
$("#dialog1").click(function() {
$('#welcome').slideToggle('#loginhandle');
$('#loginhandle').show("slow");
var name = $("input#ausers_ID").val();
var dataString = 'ausers_ID='+ ausers_ID ;
$.ajax({
type: "POST",
url: "OpenCashier.php",
data: dataString,
success: function(msg) {
$('#loginhandle').slideToggle('#msgreturn');
$('#msgreturn').show("slow");
$('#msgreturn').html(msg)
.hide()
.fadeIn(1500, function() {
});
}
});
return false;
});
});
</script>
when i click this bottom
<input type="submit" id="dialog1" name="dialog1" value="Insert" />
we must call this page
<? session_start();
include("sec.php");
include("../include/connect.php");
include("../include/safe.php");
if($_POST["dialog1"]){
// Every thing is OK
$ausers_ID=$_POST["ausers_ID"];
$cashiers_CashierOpenDate=date('Y/m/d');
$query="INSERT INTO `cashiers` ( `cashiers_CashierID` , `cashiers_CashierOpenDate` , `cashiers_User` , `cashiers_Status` , `cashiers_Delete` ) VALUES ('', '$cashiers_CashierOpenDate', '$ausers_ID', '0','0');";
mysql_query($query);
$num=mysql_affected_rows();
if($num==1)
$message="Account was added successfully";
else
$message=$_POST["dialog1"]." Account is already exists in database";
}
?>
but data cannot insert why !!!

You missed to include the "dialog1" parameter used in your PHP code.
I would suggest to change your data to sent to :
var dataString = {ausers_ID : ausers_ID, dialog1 : true}

Related

My Ajax code not refresh my favorite button

I tried different code to have a favorite button who will change (image) when you click on it - favorite/unfavorite without refresh the page but it doesn't work. with this code when i click on favorite button, the page not reload but nothing change, the image (empty heart) doesn't change and nothing record in the data base...
// ************************* AJAX
<script type="text/javascript" src="https://ajax.googleapis.com. /ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#refreshAjout").click(function(){
$.ajax({
type: "POST",
url: $("#refreshAjout").attr('action'),
success: function(retour){
}
});
return false;
});
});
$(function(){
$("#refreshSupp").click(function(){
$.ajax({
type: "POST",
url: $("#refreshSupp").attr('action'),
success: function(retour){
}
});
return false;
});
});
</script>
And this is my php code for the button and the function to add or remove data from DB
<?php
// If user not connected
if ($_SESSION['pseudo'] == NULL){
echo '<img src="../.. /images/empty-heart.jpg" class="ajouter"</img> ';
}
// If user connected
if (isset($_SESSION['pseudo']) && isset($_SESSION['pass'])){
// We check if the key exist in DB
$req="SELECT count(*) FROM favoris WHERE profil='".$test."'";
$res=mysql_query($req);
// if key not in DB we show empty heart button
if(mysql_result($res,0)==0 ) {
?>
<form method="post" action="">
<button type="image" id="refreshAjout" class="ajouter" value="" name="refreshAjout"></button>
</form>
<?php
// if key in DB we show pink heart
} else{ ?>
<form method="post" action="">
<button type="image" id="refreshSupp" class="supprimer" value="" name="refreshSupp"></button>
</form>
<?php
}
}
And finaly the function to put or remove the informations in DB
if (isset($_POST['refreshAjout']) ) {
$sql = "INSERT INTO favoris (id, client, profil, photo, prenom, reference, age, lien) VALUES('','$pseudo' ,'$pseudo$referenceBase','$photoBase','$prenomBase', '$referenceBase', '$ageBase','$lienBase')";
mysql_query($sql) or die('Erreur SQL ! '.$sql.'<br>'.mysql_error());
}
if (isset($_POST['refreshSupp']) ) {
$sql = "DELETE FROM favoris WHERE profil ='$pseudo$referenceBase'";
mysql_query($sql) or die('Erreur SQL ! '.$sql.'<br>'.mysql_error());
}
?>
You're not sending any parameters in your $.ajax calls, so $_POST will be empty. You need to use the data: option to send parameters.
You can combine both your submit buttons in a single call, since the can get the parameters from the element itself.
$(function() {
$("#refreshAjout, #refreshSupp").click(function() {
var newSrc = this.id == "refreshAjout" ? "../../images/pink-heart.jpg" : "../../images/empty-heart.jpg";
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: { [this.id]: this.value },
success: function(retour) {
$(".ajouter").attr("src", newSrc);
}
});
return false;
});
});

onClick Ajax data not working

As i'm building an website that needs Ajax for sending POST methods without refreshing the entire page.
I tried using ajax to send data from an onclick event on an LINK-tag, but the ajax code does seem to send an EMPTY post.
This is the php/jquery/ajax code:
<p id="school_content">
</p>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
contentType: "application/json; charset=utf-8",
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
},
});
$("#school_content").load("id_script.php");
});
});
</script>
The LINK-tag has the 'id' of the school of wich the information needs to be shown in the PARAGRAPH with 'id' "school_content" by this jquery part: $("#school_content").load("id_script.php"); .
The var Id = $(this).attr('id'); part works, because he's giving me the right school_name in an alert(); if I ask it to.
The id_script.php needs to get this POST in the usual way, but is does not..
The id_script.php code:
<?php
include('connect.php');
header('Content-Type: application/json');
if(isset($_POST['school_name'])){
$Id = $_POST['school_name'];
$extract = mysqli_query($con, "SELECT * FROM school_kaart WHERE school_name='$Id'");
$numro=mysqli_num_rows($extract);
if(mysqli_num_rows($extract) == '1'){
$row = mysqli_fetch_assoc($extract);
echo 'Yes it works!';
}
else{
echo 'Nope, didnt work!';
}
}
else{
echo 'Not posted!';
}
?>
I'm still getting "Not posted!" in the PARAGRAPH I mentioned earlier. What seems to be the problem?
.load is shorthand for an ajax request so you are actually doing 2 request.
The latter isn't sending any data and so it returns 'Not Posted!';
http://api.jquery.com/load/
try
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
$("#school_content").html(data);
},
});
//remove this
//$("#school_content").load("id_script.php");
});
});
</script>

Form not saving data to MySQL database

I am having trouble recording a single data (deckName) from this form to my MySQL database. I read and tried all the solutions I found over the web, but I cannot get it to work. Doing the MySQL command from the PHPMyAdmin work fine.
I need to save in the deck table of the db (id, name, cards) the values.
Jquery/Ajax script:
<script>
$(document).ready(function(){
$(document).on('submit','.save',function(){
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: console.log('worked')
});
});
});
</script>
Form:
<div class="decklist">
<form method="post" id="decklist">
<input class="deck" id="deckN" type="text" value="Deck name"/>
<input class="save" type="submit" value="Save Deck"/>
</form>
<div class="list">
<ul class="d_list">
<li class='added_card' id='list_0'></li>
</ul>
</div>
</div>
submit.php:
<?php
if(isset($_POST["name"])&& strlen($_POST["name"])>0){
$deckName = $_POST["name"];
$cards = 0;
echo $deckName;
$conn = new mysqli("localhost:8080","root","","ken");
if($conn -> connect_errno){
die("Failed to connect: (". $conn->connect_errno. ")".$conn->connect_error);
}
$insert = $conn->query ("INSERT INTO `deck` (deck, cards) VALUES ($deckName, $cards)");
if ($insert){
echo 'Successfully saved '. $deckName;
$conn -> close();
}
}
?>
Also once I hit Save Deck for submit, the div get refreshed while I assume it shouldn't with ajax.
I tried using click instead of submit, and the console.log returned everything correctly from the ajax function and the div wasn't refreshing every time, but with submit logs don't show up anymore in console.
I don't get anything from the echo in submit.php, never.
Try using preventDefault; like so
$(document).on('submit','.save',function(e){
e.preventDefault;
Hope it solves your problem !
You have to put quotes around string values:
"INSERT INTO `deck` (deck, cards) VALUES ('$deckName', $cards)"
how about change js like this:
$(".decklist").on("click", ".save", function(){
$.post("submit.php", { name: deckName }).success(function(){
console.log('worked');
});
});
You need to bind on the form submit event :
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('#deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
it works form me, change $('#deck').val();

Update Mysql records using Ajax/Json isn't working

What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});

Ajax on multi check PHP Codeigniter

i want use ajax for sent to saveKrs and save to database. i'm use codeigniter, when i click submit button, there's no event. please help me
form_checkbox('checkKrs[]',$row->id, FALSE, 'id=checkKrs')
<script type="text/javascript">
$('#save_krs').click(function(){
var id_student= $('#id_student').val();
var id_semester = $('#id_semester').val();
var checkKrs = new Array();
$("input:checked").each(function() {
data['checkKrs[]'].push($(this).val());
})
var data = {
checkKrs:checkKrs,
id_semester:id_semester,
id_mahasiswa:id_mahasiswa,
is_ajax: '1'
};
$.ajax({
url: "saveKrs",
type: 'POST',
data: data,
beforeSend : fnLoadStart,
complete : fnLoadStop,
success: function(msg) {
//$('#form_data').hide();
$('#form_data').html(msg);
//$('#report').show();
}
});
alert('Pengisian KRS tidak boleh kosong');
return false;
});
</script>
Make you sure that you have the right controler and if you form match it.

Categories