Symfony2 Save Form Data via Ajax - javascript

I have a form in Symfony that needed to be submitted via ajax call. I worte the code but it's not saving any data in db but also doesn't give/show any error.
send_dict = {
type: 'POST',
url: $(this).attr('action'),
processData: true,
data: $('#Form').serialize(),
beforeSend: function(request) {alert('before send');},
success: function (data) {alert("success")},
error: function(xhr, textStatus, thrownError) {
alert('Some Thing Went Wrong, Please Refresh and Try Again...');
}
}
$.ajax(send_dict);
public function createAction(Request $request)
{
$user = $this->getUser();
$address = new Addresses();
if($request->isXmlHttpRequest()) {
// Do something...
if ($request->isMethod('POST')) {
$request = $this->get('request');
$permanent_is_present = $request->get('permanent_is_present');
$present_address = $request->get('present_address');
$present_address_country = $request->get('present_address_country');
// Persisting Objects to the Database
if($permanent_is_present==true){
$address->isIsPresent(true);
$address->isIsPermanent(true);
}else{
$address->isIsPresent(true);
}
$address->setUser($user);
$address->setStreet1($present_address);
$address->setCountry($present_address_country);
$address->setState($present_address_state);
$address->setCity($present_address_city);
//exit(\Doctrine\Common\Util\Debug::dump($address));
// Entity Manager To Get Connected with Doctrine
$em = $this->getDoctrine()->getManager();
// Persists the entire objects....
$em->persist($address);
// Flush queries into database
$em->flush();
$output = array();
$response = new Response();
$output[] = array('success' => true);
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}else{
return $this->render('AddressBundle:Addresses:new.html.twig');
}
} else {
return $this->redirect($this->generateUrl('address_new'));
}
}
both alerts in before send and success on ajax function are showing. but the data is not saved in the database? New to symfony, also don't know how to trace/debug this?
UPDATE:
One more thing i notice that there is no user login in the system, and em trying to made ajax calls. and it is sending to controller and because user id is not found so it is not saving into database

You need to serialize form data. Give your form an Id attribute then:
data: $('#Form').serialize(),

Related

if else statement in AJAX success

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}

Ajax form data not saved in database

I am trying to save user input into database using Ajax in Laravel-5.2.
This is my route.php
Route::get('xxxxx/{task_id?}',function($task_id){
$task = App\XXXXX::find($task_id);
return response()->json($task);
});
Route::put('xxxxx/{task_id?}',function(Request $request,$task_id){
$task = App\XXXXX::find($task_id);
$task->Name = $request->Name;//
$task->Email = $request->Email;
$task->Telephone = $request->Telephone;
$task->save();
return response()->json($task);
});
In my view, the save button is used as.
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" value="update">Save changes</button>
<input type="hidden" id="task_id" name="task_id" value="0">
</div>
my js file created using this tutorial..
I am getting the popup, Save button is not working.What is the wrong here? I m new for Ajax.
Thanks in advance.
This is route.php
Route::match(['get','post'], 'my/save-data','MyController#SaveData');
This is your html:
Save changes
This is your Controller file: MyController.php
public function SaveData( Request $request )
{
$input = $request->all();
try{
// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();
// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();
$otherModel = $input['Name'];
$otherModel = $input['Email'];
$otherModel = $input['Telephone'];
// save
$otherModel->save();
}
catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
\Log::error( $e->getMessage(), $context );
}
catch (Exception $e){
\Log::error( $e->getMessage(), $context);
}
return response()->json( ['status'=>'success', 'message'=>'Completed successfully'] );
}
This is your Js file:save.js
function save() {
getData = {
name: "value", // from get eliment
email: "value", // from get eliment
telephone: "value" // from get eliment
};
$.ajax({
type: 'post', // POST Request
url: 'localhost/my/save-data', // localhost/my/save-data // Url of the Route (in this case user/save not only save)
data: getData, // Serialized Data
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
}

Stop Symfony form from redirecting after submit

I have a form that is rendered in a pop-up. When the form is submitted and valid, the data is saved and I'm redirected to the route of the form. How could I stop that redirection? I don't want to render another page, my goal is closing the pop-up after a valid submit.
public function addFeedbackAction(Request $request)
{
$view = View::create();
$feedback = new Feedback();
$feedbackService = $this->get('main.feedback.service');
$form = $this->createForm(new FeedbackType(), null, ['action' => 'feedback']);
$form->handleRequest($request);
if ($form->isValid()) {
$formData = $form->getData();
$feedbackService->create($formData, $feedback);
return null;
}
$view
->setData($form)
->setTemplateData($form)
->setTemplate('MainBundle:Modals:feedback.html.twig');
return $view;
You can catch submit event with Javascript.
You can find an exemple using JQuery here:
https://api.jquery.com/submit/
Send data using AJAX
$.ajax({
type: "POST",
url: "yourControllerHere",
data: form.serialize(),
beforeSend: function() {
//TODO: Loading
},
error: function( xhr){
},
success: function( data ){
}
});
Then you can process what you gonna do in success: function (data)

JavaScript ajax post command error for localhost

I am new to Ajax & JavaScript. But i am stuck with this error. I am making post request using Ajax.
var sentdata = {"name":"gourav", "email":"email"};
var sentd = JSON.stringify(sentdata);
this.url = "http://localhost/Working/board.php";
$.ajax({
type: "POST",
url: $(this).url,
data: sentd,
contentType: "application/json",
//dataType : "json",
success: function (response) {
alert(response.message);
console.log( "Done with success: ");
},
error: function (xhr, thrownError) {
alert(thrownError);
}
});
I am calling this request to simple code where i am not even checking the $_POST variable and just trying to write some data in mysql table.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
// selecting database
mysql_select_db(DB_DATABASE, $con);
if(1)
{
$tb_name = "tb_appuser";
$name = "name1";
$email="email1";
$deviceId="0";
$platform="1";
$query = sprintf("INSERT INTO %s (user_name, email, device_regid, platform_type) VALUES ('%s', '%s', '%s', '%d')" , $tb_name, $name, $email, $deviceId, $platform);
echo "$query\n";
$res = mysql_query($query);
}
I already tested this board.php code and verified it is inserting the data in table.
But when i am doing this via $ajax i am getting "The page at localhost says: undefined" and nothing got written in my database also.
url: this.url, not $(this).url.
$(this) does not have a property called "url" in your context I think.

Catching data in controller

I have a question about javascript and cakephp, I need to send data via Post and recive it in the other side (the controller) and make the normal process that I already have. But I don't know how can I catch the data. I'm working with Ajax
function editFun(clicked_id){
var id = clicked_id;
$("#Content").empty();
$('#Content').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/Posts/edit',
data: (id)
})
.done(function(data){
console.log(data);
$('#Content').html(data);
})
.fail(function(data){
$('#Content').html(data);
});
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
In that case you should send your id in URL. So even GET method is enough, because you controller receive $id param from URL.
So all what you need to change are post arguments:
$.ajax({
type: 'POST',
url: '/Posts/edit/' + id
})

Categories