I need your help to try to sort out an issue with ajax callback.
What happen is that the php script is called without issues, the query works fine and it generate the json output, but the callback doesn't works.
No div is displayed on success and no changes on class happens.
This is my form
<form class="form-inline">
<input type="hidden" id="id_pro" value="1">
<input type="hidden" id="status" value="1">
<button id="submit" type="button" class="btn btn-link">
<span id="check" class="glyphicon glyphicon-check" title="my tytle"></span>
</button>
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
This is the js part
$(function() {
$("#submit").click(function() {
var id_pro = $("#id_pro").val();
var status = $("#status").val();
var dataString = 'id_pro='+ id_pro + '&status=' + status;
if(id_pro=='' || status=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "myphppage.php",
data: dataString,
datatype: 'json',
success: function(data)
{
if(data.result=='1')
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#check").attr('class', data.check);
}
}
});
}
return false;
});
});
And this is the php part
<?
if($_POST)
{
$id_pro=$_POST['id_pro'];
$status=$_POST['status'];
if($status==0){$status=1;}else{$status=0;}
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
header("Content-type: application/json");
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
print json_encode($data);
}
else
{
header("Content-type: application/json");
$data = array('result'=>'0');
print json_encode($data);
}
$result->close();
}else { }
?>
Any idea?
Thank you in advance
error 500 means error in php and in your php don't see defined $mysqli and $result i think here is your problem.
better PHP looks like this but must define connect to DB
<?php
header("Content-type: application/json");
$data = array('result'=>'0');
if ($_SERVER['REQUEST_METHOD'] == 'post' )
{
$id_pro = $_POST['id_pro'];
$status = ($_POST['status'] == 0) ? 1 : 0; // if($status==0){$status=1;}else{$status=0;}
// define $mysqli
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
}
// $result->close(); // ????
}
print json_encode($data);
Related
I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}
I am storing the unicode values in java script array but when I pass it to the ci controller it is not showing in proper language.
How to pass javascript unicode array to php using form post?
My code is:-
var myTableArray = [];
$("table#search_result_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var myJSON = JSON.stringify(myTableArray);
$.post("<?php echo base_url("Purchase/addnew"); ?>",{data:
myJSON},$("#purform").serialize(),function(data)
Santosh, to post Unicode Array through AJAX and JSON, you need 3 files i.e. Javascript file, html file and a php file. Below is the samle code,
JS file
// make the AJAX request
// #dataform : it is a html data form id
var dataString = $('#dataform').serialize();
$.ajax({
type: "POST",
url: 'php_file.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '';
if (data.err_msg != '')
alert('Error');
}
else if (data.success == 1) {
alert('Success');
}
},
error: function (x,e) {
alert('Error: '+x.status+','+x.responseText);
}
});
HTML file
<form id="dataform" name="dataform" method="post" action="" role="form">
<input type="text" name="field1" id="field1" />
<input type="text" name="field2" id="field2" />
<input type="text" name="field3" id="field3" />
<input type="text" name="field4" id="field4" />
<button type="button" name="submit" id="submit" onclick="return false;">Submit</button>
</form>
PHP file
$field1=$_REQUEST["field1"];
$field2=$_REQUEST["field2"];
$field3=$_REQUEST["field3"];
$field4=$_REQUEST["field4"];
//Your Validation Logic
$return_array = validate($field1);
if($return_array['success'] == '1') {
//Your SQL Query //
}
function validate($field1)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['err_msg'] = '';
//Validate Field Logic
if($field1=='')
{
$return_array['success'] = '0';
$return_array['err_msg'] = 'Field1 is required!';
}
return $return_array;
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];
I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.