submit form in ajax php mvc data not saved - php

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

Related

Problem to get data from ajax call to php

Did simple test pages for sending data via ajax call to php where I'm trying to check field (failing in here), from some reason don't get this working so where is my error ?
$.ajax({
url: "checkAJAX.php",
data: {"test" : " Sending string from ajaxToPHP file"},
success: function(data){
alert(data);
$("#content").val(data);
}
});
<?php
if(isset($_GET["test"])){
$checkField = $_GET["test"];
echo $checkField;
}
else {
echo "<br>not working...";
}
?>

In my ajax form request is not working properly

I want to give some alert message in my page but it working
This is my view code:
$.ajax({
url :"<?php echo base_url();?
>booking/dispatch_challan/DispatchChallanController/createDispatchChallan",
type:"POST",
dataType: "json",
data:$("#dispatch_challan_form").serialize(),
data:$("#dispatch_challan_form").serialize()+'&disp_ch_ids='+allVals,
success: function(data)
{
if(data.create_dispatch_challan.form_status=='false')
{
alertify.error('you may occured some server side errors');
}else if(data.create_dispatch_challan.form_status=='true')
{
alertify.success(data.create_dispatch_challan.form_message);
if (confirm())
{
alert("print");
}else{
alert("Do not print");
}
}
}
});
please give me same solution in this.
Its not OK to have a new line here
url :"<?php echo base_url();?
>booking/dispatch_challan/DispatchChallanController/createDispatchChallan",
Try this code: pastebin

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

How to send "response" back to submitted Ajax form?

I am submitting a form using ajax. Then it is processed in PHP, and in the response i get the whole PHP/HTML code back. What is the right method to send back a "response" as variables from the PHP?
My JS
$.ajax({
url: 'index.php',
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
and my PHP simply accepts the posted Input value and manipulates it:
if (isset($_POST["myInput"])) {
// doing something - and I want to send something back
}
Just echo and exit:
if (isset($_POST["myInput"]))
{
// doing something - and I want to send something back
exit('Success');
}
Then in your JS:
success: function(response) {
if (response == 'Success') {
// do something?
}
}
For example:
test.php single page html + php post handler
<?php
// Post Handler
if (count($_POST))
{
// do something with posted data
echo "You Posted: \r\n";
print_r($_POST);
exit();
}
// dummy data outside of the post handler, which will never be sent in response
echo "Test Page";
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.post('test.php', { "hello": "world" }, function(result) {
alert(result);
});
});
</script>
Outputs:
$.ajax({
url: 'index.php', // change your url or give conditional statement to print needed code
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});

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

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

Categories