ajax not append data on div? - ajax

I dont know what the problem is here, I try to append the content, but its not.
var InPro = false;
$(document).ready(function(){
var form = $('#form32');
var submit = $('#submit');
form.on('submit', function(e) {
if(InPro) return;
InPro = true;
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'post.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
InPro = false;
var item = $(data).hide().fadeIn(800);
$('#post-show').append(data);
$("#form32")[0].reset();
},
});
});
});
and here the post.php:
<?php
include_once("config.php");
include_once("verifica.php");
// No direct access to this file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
session_start();
$user = $_SESSION['user'];
$comment = $_POST['comment'];
if($comment==""){
die();
}
$ip = getenv("REMOTE_ADDR");
$data = date ("ymdHis");
$i=mysql_query("INSERT INTO posts (id, foto, user, titulo, youtube, button, data, ip) VALUES ('','0','$user','$comment','$youtube','$button','$data','$ip')");
$idpostfeed = mysql_insert_id();
echo"$comment";
?>
and my form:
<form id="form32" method="post"> <textarea name="comment" id="comment" class="comment" placeholder=""></textarea> <input type="submit" id="submit" class="button" value="Submit Comment"> </form> <div id=post-show></div>
so, I want to show result in #post-show div, but it is not working. what is wrong?
thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Related

Form AJAX submit symfony doesn't work

I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

cross-domain form post with ajax jsonp returns error: {"readyState":4,"status":200,"statusText":"success"}

I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});

I can't update status by use the checked box

Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}

unable to upload images in the folder while using ajax

I am supposed to upload images using using Ctrl keys for which I am using Ajax, but the problem is that while uploading the image names in the database successfully I am not able to upload them in the folder under the name images
I have the following code which is able to upload my images using ajax on database but unable to upload images in the folder
<script>
function showChar(e){
if(e.ctrlKey && e.charCode == 98){
e.preventDefault();
var j = $('#fl').click();
if(j){saveImage();}
}
}
function saveImage(){
//var abc = $('#form1').serialize();
//alert(abc);return false;
var fl = $('#fl').val();
if(fl != ''){
alert('t');
$.ajax({
type: 'post',
url: 'sent.php',
data: 'fl='+fl,
success:function(msg){
}
});
//$.ajaxFileUpload();
}
}
</script>
</head>
<body onkeypress="showChar(event);">
<form enctype="multipart/form-data" method="post" id="form1">
<input type="file" name="fl" id="fl" value=""/>
<input type="button" name="submit" id="submit" value="Submit" onclick="saveImage();"/>
</form>
and the query as
$fl = $_REQUEST['fl'];
$name = $_FILES['fl']['name'];
$temp = $_FILES['fl']['tmp_name'];
move_uploaded_file($temp, 'images/'.$fl);
$query = "INSERT INTO tbl_browse (fld_name) VALUES ('$fl')";
$res = mysql_query($query);
if(mysql_num_rows($res)>0){ return 'U'; }
Try this method
https://stackoverflow.com/a/24839628/1640577
check question and answer
$.ajax({
type: 'post',
url: 'sent.php',
data: 'fl='+fl,
processData: false,
contentType: false ,
success:function(msg){
}
});

Resources