I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()
Related
when submitting the form using ajax codeigniter validation not working please resolve this issue i am facing this problem from last week
jQuery code that i am using for submitting form
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
data: contactForm.serialize(),
success: function(response){
}
});
});
});
Controller
public function add_account() {
if($this->form_validation->run('add_account')) {
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
} else {
$this->login();
}
}
Here is just the concept. I have not tried codeigniter but am php professional.
You will need to retrieve records as json and pass it to ajax. At codeigniter
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'Account Created Successfully !');
echo json_encode($result);
hence the code might look like below
public function add_account(){
if($this->form_validation->run('add_account')){
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post)){
header('Content-Type: application/x-json; charset=utf-8');
$result = array("message" =>'ok');
echo json_encode($result);
//$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
}
return redirect('Frontend/login');
}else{
$this->login();
}
}
in ajax you can set datatype to json to ensure that you can get response from the server and then let ajax handle the response....
$(function() {
$("#registratiom_form").on('submit', function(e) {
e.preventDefault();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function(response){
alert(response.message);
console.log(response.message);
//display success message if submission is successful
if(response.message =='ok'){
alert('message submited successfully');
}
}
});
});
});
You have a misunderstanding about what an ajax responder can and cannot do. One thing it cannot do is use PHP to make the browser redirect to a new page. You will have to send a clue back to the success function and then react appropriately.
A few minor changes to the answer from #Nancy and you should be good.
public function add_account()
{
if($this->form_validation->run('add_account'))
{
$post = $this->input->post();
unset($post['create_account_submit']);
$this->load->model('Frontendmodel', 'front');
if($this->front->add_user($post))
{
$this->session->set_flashdata('message', 'Account Created Successfully !');
$this->session->set_flashdata('message_class', 'green');
echo json_encode(array("result" => 'ok'));
return;
}
$message = '<span class="error">Account Not Created!</span>';
}
else
{
$message = validation_errors('<span class="error">', '</span>');
}
echo json_encode(array("result" => 'invalid', 'message' => $message));
}
In the Javascript, handle the various responses in the success function of $.ajax
$(function () {
$("#registratiom_form").on('submit', function (e) {
var contactForm = $(this);
e.preventDefault();
$.ajax({
url: contactForm.attr('action'),
type: 'POST',
dataType: 'json',
data: contactForm.serialize(),
success: function (response) {
console.log(response); // so you can examine what was "echo"ed from the server
if (response.message=='ok') {
// Simulate an HTTP redirect: to the right page after successful login
window.location.replace( "https://example.com/frontend/somepage");
} else {
//stay on the same page but show the message in some predefined spot
$('#message').html(response.message);
}
}
});
});
});
I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
I am using jQuery ajax to submit a form. I have written php code in a different file to insert the form-data into a database table. How can I do the server side validation and show corresponding error message (e.g. this field cannot be empty)? I have no idea about how to solve this problem. jQuery function that does the submission is as follows
$('#form-add-button').click(function () {
$.ajax({
type: "POST",
url: 'addemployee.php',
data: $("#employee-form").serialize(),
success: function (response) {
showEmployeesData();
initInputValues();
},
error: function (response) {
alert('Error:' + response);
}
});
return false;
});
Before inserting the data into the database validate the data using php if you have errors in validation you can encode the error message as json and return back to the ajax function and show the message
AJAX FUNCTION
$.ajax({
type: 'post',
url: 'lettersubscribe/subscribe',
dataType: 'html',
data:$("#subscribenewsletter").serialize(),
success: function (html) {
var result = jQuery.parseJSON(html);
if(result.success == true){
$("#subscribeBox").html('<span id="blacktext">TACK / THANKS FOR</span><span id="bluetext"> SIGNING UP!</span>');
}else{
$("#subscribe_result").html(result.error);
}
}
});
//PHP FUNCTION
function subscribe(){
$msg = array();
$msg['success'] = TRUE;
if($_POST['emailid']){
// Validate email id
}else{
$msg['email'] ="Invalid Email";
$msg['success'] = false;
}
echo json_encode($msg);
}
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.