PHP not running with ajax POST - javascript

I have a form in a modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" id="saveperson">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="">
<label for="description">Description</label>
<input type="text" name="description" value="">
<input type="submit" name="user" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
On submit I run the js:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
And then this should run in process.php
<?php
header ( "Content-Type: application/json");
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
// Category added successfully
die ( json_encode ( array ( "success" => 1)));
} else {
// Error while creating new category
die ( json_encode ( array ( "success" => 0)));
}
} else {
// That category already exists
die ( json_encode ( array ( "success" => 0)));
}
?>
But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db
<?php
header ( "Content-Type: application/json");
if( isset( $_POST['user'] ) ) {
if( !empty( $_REQUEST['newcat'] ) ) {
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
wp_insert_category( $my_cat );
}
}
}
?>

There is an error in the browser console:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
Notice the
else {
$('.modal-body').html("Error!");
}
Error:
Uncaught SyntaxError: Unexpected token else
Remove the else block, it should work
It should be:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
});
Here is the fiddle

Did u try this?
$( "#saveperson" ).submit(function( event ) {
let form = $( this );
let formData = new FormData(form[0]);
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : formData,
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});

The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use
function.php and wordpress ajax
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}

Related

Get json file result dynamically by url parameter

if have a json file like this example
market.json
{ topads:
[ { id: 114
, advert_type: 11
, cat_main_id: 5932
, cat_market: 1
, subcat1_id: 12
, endcat: 'Sneakers'
, description: 'Nike Air Jordan 1 '
} ] }
with php i will get the json file and show all entries with eg subcat1_id 12,15 and 23 (and max. 4 entries)
<?php
$url_json = $baseurl . 'json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
//subcat1_id
$ad_types = array( 12,15,23);
$Count = 0;
shuffle($obj[ 'topads' ]);
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $ad_types ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
//some html and php content to show the output eg. echo $result[ 'description' ]
</div>
<?php
$Count++;
if ($Count == 4){
break; //stop foreach loop after 4th loop
}
}
}
?>
ok this works perfectly in php but I want a url parameter (e.g. & subcat1 = 12), instead of the hard coded $ad_types.
So every time the URL parameter changes, the json file entries should also be displayed dynamically.
But how?
js/jquery
<script>
const subcat1= urlParams.get('subcat1')
</script>
to get the url parameter subcat1
and then? Result via Ajax to show the results dynamically?
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: subcat1,
success: function (data) {
// ...
}
});
}
Update getresults function with below:
function getresults() {
$.ajax({
url: "myphpfile.php",
method: "POST",
data: {subcat1: subcat1},
success: function (data) {
}
});
}
and get in php code like this-
$_POST["subcat1"];
Ajax data needs to contain key/value pairs, you are only sending a value
Try :
data: {subcat1 : subcat1 }
Then access it in php with:
$_POST['subcat1']
I have solved it.
Thanks for the hints on the solution!
The JS file to get the url parameter dynamically.
<script>
// get parameter from url
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var subcat = urlParams.get('subcat1');
//console.log(subcat);
getresult(subcat);
// ajax call
function getresult(subcat) {
$.ajax({
url: "myphpfile.php",
method: "post",
data: {
"subcat": subcat
},
success: function (data) {
$('#ad_content').html(data);
},
error: function () {
$('#ad_content').html('error');
}
});
}
</script>
and the php file to show the
myphpfile.php
<section class="mt-1 mb-1 d-none d-lg-block">
<div class="col-xl-12 col-lg-12 col-md-12 pl-0 pr-0">
<div class="row">
<?php
$url_json = '/json/market.json';
$response = file_get_contents( $url_json );
$obj = json_decode( $response, true );
if ( isset( $_POST[ 'subcat' ] ) && !empty( $_POST[ 'subcat' ] ) ) {
// this is the value from the url parameter
$adcat = array( $_POST[ 'subcat' ] );
$Count = 0;
shuffle( $obj[ 'topads' ] );
foreach ( $obj[ 'topads' ] as $result ) {
if ( in_array( $result[ 'subcat1_id' ], $adcat ) ) {
?>
<div class="col-xl-3 col-lg-3 col-md-4">
<div class="item">
<div class="card mb-0">
<?php echo $result[ 'description' ]; ?>
</div>
</div>
</div>
<?php
$Count++;
if ( $Count == 4 ) {
break; //stop foreach loop after 4th loop
}
}
}
}
?>
</div>
</div>
</section>
and of course the place to show the result
<div id="ad_content"></div>

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

codeigniter ajax form validation with submit

i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">&nbsp Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>&nbsp Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model

Symfony2 Ajax call to display a message on a specific condition

I am beginner in javascript and ajax and I just cant figure out how to display a message on some condition.
Lets say a user can increase or decrease the quantity of the product he wants to buy. I have made that (not saying it was easy). But if the product is out of stock he cant increase the quantity anymore. How can I show that in the message. For example if a user tries to increase the quantity, but the product is out of stock I want to display the message below on the same ajax call.
This is the controller:
public function addQuantityAction( Request $request ) {
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];
$quantity = $requestData['quantity'];
/** logic*/
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStockAvailable();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$qtyAvailable = $qtyAvailable - 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased','amount' => $cart[ $productid ]));
$session->set('cart', $cart);
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}
The Ajax:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
And the twig:
<div class="input-append">
<input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
<i class="icon-minus"></i>
<i class="icon-plus"></i>
<button class="btn btn-danger" type="button"><i class="icon-remove icon-white" style="color:white"></i></button>
<p> display message here </p>
</div>
You can also add class depands on success or error status of operation.
Ajax
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
if(data.message != 'undefined') {
$('#ajax_response--message').html(data.message)
}
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
<div class="input-append">
Twig
<p id="ajax_response--message"> display message here </p>
</div>

Submit form laravel using AJAX

I am trying to add comment using AJAX technology but I have an error:
Failed to load resource: http://localhost:8888/blog/public/comment/add the server responded with a status of 500 (Internal Server Error)
Here is my code:
View:
{{ Form::open(array('method'=>'post','class'=> 'col-md-6','url' => '/comment/add', 'id'=>'comment')) }}
<input type="hidden" name="post_id" value="{{$id}}">
<div class="row">
<div class="inner col-xs-12 col-sm-12 col-md-11 form-group">
{{Form::label('name', 'Imię')}}
{{Form::text('username', null, array('class'=>'form-control', 'id'=>'name', 'name'=>'name'))}}
</div>
<div class="inner col-xs-12 col-sm-12 col-md-12 form-group">
{{Form::label('message', 'Wiadomość')}}
{{Form::textarea('message', null, array('class'=>'form-control', 'id'=>'message', 'name'=>'message', 'rows'=>'5'))}}
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12 submit form-group">
{{Form::submit('Wyślij', array('name'=>'submit', 'class'=>'btn btn-orange'))}}
</div>
</div>
{{ Form::close() }}
Controller:
public function addComment()
{
$this->layout = null;
//check if its our form
if(Request::ajax()){
$name = Input::get( 'name' );
$content = Input::get( 'message' );
$comment = new Comment();
$comment->author = $name;
$comment->comment_content = $content;
$comment->save();
$postComment = new CommentPost();
$postComment->post_id = Input::get('post_id');
$postComment->comment_id = Comment::max('id');
$postComment->save();
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return 'yea';
}else{
return 'no';
}
}
AJAX:
jQuery( document ).ready( function( $ ) {
$( '#comment' ).on( 'submit', function(e) {
e.preventDefault();
var name = $(this).find('input[name=name]').val();
$.ajax({
type: "POST",
url: host+'/comment/add',
}).done(function( msg ) {
alert( msg );
});
});
});
And the last one routes:
Route::post('comment/add', 'CommentController#addComment');
Anyone have an idea where is the problem and why I can't submit my form?
You are not posting any data,
$.ajax({
type: "POST",
url: host+'/comment/add',
}).done(function( msg ) {
alert( msg );
});
The error you are getting is that the columns in DB cannot be null.
Try to change your ajax call to this:
$.ajax({
type: "POST",
url: host+'/comment/add',
data: { name:name, message:message, post_id:postid },
success: function( msg ) {
alert( msg );
}
});
Change this
var name = $(this).find('input[name=name]').val();
to
var name = $('#name').val();
and fetch the message and the post id:
var message = $('#message').val();
var postid = $('#post_id').val();
Complete ajax block:
$('#comment').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
var message = $('#message').val();
var postid = $('#post_id').val();
$.ajax({
type: "POST",
url: host+'/comment/add',
data: {name:name, message:message, post_id:postid}
success: function( msg ) {
alert( msg );
}
});
});
And finally, add an ID to the hidden field:
<input type="hidden" name="post_id" id="post_id" value="{{$id}}">
Send data back from Laravel controller, eg.
// ........
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response); // <<<<<<<<< see this line
}else{
return 'no';
}
}
This will send the data in your response back to your ajax request.
Then, alter your ajax success function:
// .......
success: function( msg ) {
$("body").append("<div>"+msg+"</div>");
}
// ..........
You will now see that a new div was created in your <body> including the created response. If you want to show the newly created post, just create it as the ajax response and append it to any element in your page.
Just modifying the ajax block of baao's answer. You can pass data as serialized.
$('#comment').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: host+'/comment/add',
data: $(this).serialize(),
success: function(msg) {
alert(msg);
}
});
});
All the field values of the form can be passed using the serialize() function.

Categories