$.ajax function() not working when form is being submitted - php

I am trying to write an ajax function such that when i click the submit button, name = "Add", it will call for a php file named "addtobucketlist.php" and run the functions in it.
This is the ajax function in my file called "script.js" which is not working, and I have no idea why.
(I have verified that the hideshow('loading',1); at line 2 is working.)
function Addtobucketlist(){
hideshow('loading',1); //line 2
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/addtobucketlist.php",
data: $('#addBucket').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
});
}
Below is my header.php
$(document).ready(function(){
$('#addBucket').submit(function(e) {
Addtobucketlist();
e.preventDefault();
});
});
Below is my form, this is being written such that when ajax is run, the form will be hidden and div class done will be shown.
echo '<div class=form>';
echo '<form id=addBucket action="http://utourpia.me/php/addtobucketlist.php" method=post>';
echo '<input type="submit" name="add" value="Add" /><img id=loading src="../../images/loading.gif" alt="working.." />';
echo '</form>';
echo '</div>';
echo '<div class="done"><p>Added successfully! <br /></p>';
echo '</div>';
below is addtobucketlist.php:
if (isset($_POST['Add']))
{
add_to_bucket_list($location_id, $username);
die(msg(1,"<p>Added!</p>"));
}
else
{
var_dump($location_id);
var_dump($username);
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
any help would be appreciated!

Try using
if (!empty($_POST['Add']))
{
instead of isset. Add the
error: function( jqXHR, textStatus, errorThrown )
function to your ajax call to see what the error being thrown is.
You use a capital 'A' in your php _POST variable 'Add', and in your html form it is a lowercase a.
The text you're outputting from your php script might not be identified as proper json. Use the php function json_encode() on an array of output values instead.

action is not required as you are doing it via ajax postremove action="http://utourpia.me/php/addtobucketlist.php remove msg.status checks from $.ajax as it is only going to execute on success

Related

How to transmit php data in ajax form

I have a problem with transmitting php data in ajax function.
What I want is to send a html form, in which i have php value from a mysqli_fetch_array. The value is the number of the post, which is my primary key.
Being new to javascript, I don't really know how to do this.
Here is my onclick function code :
<script>
function foo () {
$.ajax({
url:"vote.php?no_post=<?php $post ['no_post'] ?>", //what I'd like to do
type: "POST", //request type
success:function(result)
{
alert(result);
}
});
}
</script>
In the php page, I have this fetch array, here we focus on button named "up" :
if(!isset($_POST['more']))
{
while($post = mysqli_fetch_array($res))
{
echo
'<p>'.
'<center>'.
'<img src="image/'.$post['image_post'].'">'.
'</center>'.
'<br/>'.
'<label>'.$post['desc_post'].'</label>'.
'<p>'.
'<a id="darkBlue" href="account.php?no_post='.$post['no_post'].'">'.'#'.$post['login'].'</a>'.
'<p>'.
'<label>'.$post['time'].'</label>'.
'<p>'.
'<label>'.$post['vote_post'].' points'.'</label>'.
'<footer>';
if (isset($_SESSION['login']))
{
echo '<button class="btn btn-success" name="up" id="up" onclick="foo()">+</button>'.
'&nbsp'.
'<button class="btn btn-danger" name="down" id="down">-</button>'.
'&nbsp'.
'Comment'.
'<hr>';
}
EDIT***
And finally my php page where the sql request is executed :
<?php
if (isset($_POST['up'])) // 2 buttons on the first html FORM
{
$req="UPDATE post SET vote_post=vote_post+1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my url
$res=mysqli_query($con,$req);
}
else if (isset($_POST['down']))
{
$req2="UPDATE post SET vote_post=vote_post-1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my URL
$res2=mysqli_query($con,$req2);
}
else
echo 'Error';
?>
Thanks for you help.
You have missed echo in below line.
url:"vote.php?no_post=<?php echo $post['no_post'] ?>", //what I'd like to do
EDIT
As you have used POST method, it should be passed in data like:
$.ajax({
url:"vote.php",
type: "POST", //request type,
data: {
postCount : <?php echo $post['no_post']; ?>
}
success:function(result)
{
alert(result);
}
});
You can try something like that :
<script>
function foo () {
$.ajax({
url:"vote.php",
type: "POST", //request type
data: {no_post: <?php echo '$post['no_post']'?>}
success:function(result)
{
alert(result);
}
});
}
</script>
It's better to use data : [...] instead of using parameters in url

Ajax load PHP early

i insert a content of textarea in mysql and i fetch that with PHP .
with submit form havnt problem and i can insert new data .
i have different divs and Textarea that is why i cant use submit input .
i use Ajax, but Ajax load process.php earlier than click that is why get value earlier and insert old data .
How can i load process.php in ajax on click or anyway to get variable after enter new text in textarea with click.
Thank you
<script type="text/javascript">
function useradd()
{
var data=$("#user,#user2,#user3,#user4").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "html",
});
}
</script>
process.php
<?php
include'db.php';
$text1=$_POST['text1'];
$text2=$_POST['text2'];
$text3=$_POST['text3'];
$text4=$_POST['text4'];
$n=new db();
$n->connect();
$n->delete();
$n->insert($text1,$text2,$text3,$text4);
?>
insert
public function insert($text1,$text2,$text3,$text4)
{
$sql=mysql_query("REPLACE INTO strak(text1,text2,text3,text4) VALUES('$text1','$text2','$text3','$text4' )");
if(!$sql)
{
echo mysql_error();
}
}
fetch code in textarea
<textarea id="t1" name="text1" style="height:100%;">
<?php
$conn=mysql_connect("localhost","fach","hektar12","p-d");
if($conn)
{ $seldb=mysql_select_db("p-d",$conn);
if($seldb)
{ $retrive=mysql_query("select text1 from strak",$conn);
if($retrive)
{ $result=mysql_fetch_row($retrive);
echo ($result[0]);
}
}
}
mysql_close($conn);
?>
</textarea>
I think it will solve your problem, if your ajax function calls your PHP before getting value for
data. And add one button with "onclick" event of your function which contains ajax call.
here you can add, "async: false" into your ajax function
function useradd()
{
var data=$("#user,#user2,#user3,#user4").serialize();
$.ajax({
type: "POST",
url: "process.php",
async: false, // add this line ,it will make process synchronous
data: data,
dataType: "html",
});
}

submit form in ajax php mvc data not saved

I'm trying to submit a form with Ajax.
In my form, I have the followin submit button
<?php echo CHtml::Button('SUBMITAjax',array('onclick'=>'send();')); ?>
the send function is a jquery script
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("post/Ajax"); ?>',
data:data,
success:function(data){
alert("Data Saved");
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
the Ajax php function contains this code
$model=new Comment;
if(isset($_POST['CommentForm']))
{
$model->attributes=$_POST['CommentForm'];
if($model->validate())
{
// form inputs are valid, do something here
$model->save();
return;
}
}
Everything works fine but the data is not saved.
What is wrong?
Thank you in advance for your help.
why do not you simply create a form like this and submit it using ajax
<?php
echo CHtml::beginForm();
echo CHtml::textField('name');
echo CHtml::ajaxSubmitButton('submit form', Yii::app()->createAbsoluteUrl("post/Ajax"),array(
'success'=>new CJavaScriptExpression('function(data)
{
alert(data);
}
')
));
echo CHtml::endForm();
?>
Learn about ajaxUbmitButton here

Jquery ajax request echo html data

I'm making an ajax request to my PHP script which will echo out a certain # of tables ( different each time), that I want to include on my original page when a user clicks the submit_form button. My question is how can i get Jquery to display this table into the table_layout div?
HTML :
<div id="table_layout"> </div>
JQUERY
$( ".submit_form" ).click(function( e ) {
$.ajax({
type : 'GET',
url: 'draw_tables.php',
dataType : 'html',
data: dataString ,
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('error'); },
success : function(data) { //appendto.('#table_layout') }
});
return false;
})
PHP (draw_tables.php)
echo '<table>';
echo '<input type="text" name="ID">';
echo '<input type="text" name="CLASS">';
echo '</table>';
For example you could make an ajax request and fill the div with it
$.get("draw_tables.php", function(data) {
$("#table_layout").html(data);
});
This will fill your table_layout id with the data from the ajax request.
$('#table_layout').append(data);
Inside the success callback you should add:
$('#table_layout').append(data);

Simple jquery and php problem

Does anyone know why this doesn't work? any help would be appreciated.
This is the HTML
Enter Code:<br/><input type="text" name="code" id="code"/><br/>
<input type="button" id="confirm" value="Confirm" onClick="confirm()"/>
This is the PHP (basically gets the value of the user input and if it's equal to the variable a echo sucess)
$code = $_POST["code"];
$a = 105678;
if($code==$a){
echo "sucess";
} else {
echo "nosucces";
}
The JavaScript (simple ajax code to alert yay on PHP sucess or nay on no sucess)
function confirm () {
$.post(
"confirm.php",
{code:$(this).val() },
function(data) {
if(data=='sucess') {
alert("yay");
} else {
alert("nay");
}
}
);
}
basically on all occasions the ouput is nay on further debugging i tried an elseif statement on the javascript asking if data is equal to nosucces but it didn't even alert anything, meaning it's not getting the data from the php
$(document).ready(function() {
$('#confirm').click(function() {
$.post("",{code:$('#code').val() } ,function(data)
{
if(data=='sucess')
{
alert("yay");
}
else
{alert("nay");}
});
});
});
Give brackets at end, so that it does understand that you are calling a function, also don't use confirm as function name, its a native JS function, use my_confirm instead.
onClick="my_confirm()"
Also $(this).val() won't work in your case use $('#code').val() instead.
$(document).ready(function() {
$('#confirm').click(function() {
$.ajax({
url: "confirm.php",
type: "POST",
data: "code="+$('input[name="code"]').val(),
dataType: "text",
async:false,
success: function(msg){
if(msg=='sucess'){
alert('yay');
}else{
alert('nay');
}
}
});
});
});

Categories