codeigniter: I can't change view page - javascript

I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.

The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.

Related

Trying to pass error message from Controller to View without page reload (MVC)

I'm trying to get my View to display an error message when the ActionResult from my controller fails. (It's triggered when you press a button in the View.)
However, no matter what I try, the ActionResult always redirects to a different page. If I try to return View() it goes to the default yellow ASP.Net error page. If I try to return Content("Error message") it just opens a blank page with that text.
I've saved my canned error message in ViewBag.Error, but the javascript in my View never gets a chance to use it because as soon as you click my button, the ActionResult redirects me somewhere.
How do I get my View to stay put, but still pass a message if the ActionResult fails?
Here is the method I'm calling in the controller:
public ActionResult ElectrodeChecklist(int id)
{
var routeChecklist = _routeService.GetRouteChecklist(id);
// This is where I'm trying to catch this error.
if (routeChecklist.Count == 0)
{
ViewBag.Error = "This route has no checklist steps to print.";
return ???
}
...
blah blah stuff to download a PDF file when everything works
...
return new BinaryContentResult(buffer, "application/pdf", filename);
}
Edit: Here's the view:
... dropdown menu called #dd-route...
Generate PDF
<script type="text/javascript">
$(function () {
$('#dd-route').change(function () {
var $route = $(this).val();
var $url = '#Url.Action("electrodechecklist", "wip")?id=' + $route;
$('#btn-print').attr('href', $url);
});
$('#btn-print').click(function () {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
})
});
</script>
When the user chooses an item in the dropdown menu, the url to call my ActionResult is fed into the button's href attribute. Then when they click the button, it fires it off with the correct value from the dropdown.
The second part of the JavaScript is my attempt at displaying the error message if they hit that If statement in the Controller.
I'm only writing this because it won't fit comments.
OK so first thing to notice is that it WILL start navigating to the Action ElectrodeChecklist with the id and then do what ever BinaryContentResult does. I cannot see how var $error = ViewBag.Error; could possibly work, but then again I'm not sure how/what BinaryContentResult really does.
If you want the user to see the ViewBag.Error then you need to modify this part
if (routeChecklist.Count == 0)
{
TempData["Error"] = "This route has no checklist steps to print.";
return RedirectToAction("ACTION", "CONTROLLER");
}
as suggested by #StephenMuecke. The ACTION here is the page the user was on in the first place. You could redirect them to any error page and still access the TempData["Error"]. If this still doesn't do what you want let us know.
//What you are trying to do here is awesome
//but I'm not sure if it's even possible as you are moving away from the page when the user clicks the button/link
//I'd like other please comment on this. I could use it too
$('#btn-print').click(function () {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
})
Check below code for without refreshing you can show the error message on page :
$('#dd-route').change(function () {
var TestModel = {
"id": $("route").val()
}
$.ajax({
url: '/wip/electrodechecklist',
type: "Post",
async: false,
data: JSON.stringify(TestModel),
dataType: "html",
contentType: "application/json;charset=utf-8",
success: function (result) {
var $error = ViewBag.Error;
if ($error != "") {
$('#alertbar').show();
$('#alert').html($error);
}
}
});
});
Hope this will help you !!

Rails trouble sending AJAX data to controller

I'm a AJAX rookie, so bear with me. I'm trying to send data from a chat-message box to two places -- the actual chat box and to a rails method. That way I can display the meesage, and also store the message in my DB.
I have the following JS/HTML code
<button onclick="myFunction()" name="submitmsg" type="submit" id="submitmsg" value="Send">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("frm1");
console.log(x);
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("chatbox").innerHTML += text;
$.ajax({
url : "/messages/create",
type : "post",
data : { data_value: x }
dataType : "text" //this might be wrong?
});
}
</script>
I can successfully insert into the HTML DOM, but it isn't sending the data to the messages controller create action. My messages controllers is named messsages_controller.rb and the action is create.
I've added debugger in my create action in order to then view what params are, but it never even executes the code.
Some routes:
messages GET /messages(.:format) messages#index
POST /messages(.:format) messages#create
new_message GET /messages/new(.:format) messages#new
edit_message GET /messages/:id/edit(.:format) messages#edit
message GET /messages/:id(.:format) messages#show
PATCH /messages/:id(.:format) messages#update
PUT /messages/:id(.:format) messages#update
DELETE /messages/:id(.:format) messages#destroy
UPDATE
wait, something is wrong with my JS code. It was previously inserting HTML into the DOM, but somewhere along adjustments it stopped. Now the console is throwing the error new:110 Uncaught SyntaxError: Unexpected identifier line 110 is commented out.
When I the .ajax call out of the function, then it works fine. I have something syntactically wrong when I call the .ajax function inside myFunction()
$.ajax({
url : "/messages", //by rails convention doing a post simply to '/messages' should be handled by create action
method : "post",
data : { data_value: x },
dataType : "json", //this might be wrong?
success: function(response){
//do something,maybe notify user successfully posted their message
},
error: function(error){
console.log(error);
}
});
And in your create method you should handle json requests
def create
//save message
#message.save!
respond_to do |format|
format.json { json: #message.as_json }
end
end
This is how your code should look like. You can always do more creatively.
Please checkout this gist

Laravel 5 attach with Ajax?

I have this laravel code in my controller detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
This works fine, it deletes the tag realation from my pivot table. The only thing that bugs me it that I don't want to reload the page everytime I press the delete button on my view.
( Of course I could make a selection of all tags the user want to delete, but I want to to this live with Ajax )
My problem is, I couldn't find anything that helps me with detachment from laravel + Ajax. I'm quite okay with Javascript and Jquery but Ajax is still a new thing for me..
So can anybody help me there? I'm really stuck.
Thanks for taking your time :)
#Wiriya Rungruang
current controller code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
my button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
at the bottom of the code the JS:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
alert("success");
});
});
</script>
First : You should create function detach tag from product in your controller and return status success or failure(or nothing)
In your controller
function detachTag(){
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return "Some state for checking it a success or not";
}
Second : Create javascript function for checking when you click on delete button send request with parameter to function that we created in the first step and rerender or remove that tag from your HTML page
**Parameter is mean product_id and tag_id that your want to detach it
In your js
$(".delete-tag-btn").on('click', function(){
var url = "localhost/deletetag?"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
// Do what you want
});
});
So when you click on .delete-tag-btn It will send request for detach it
While you can right a simple ajax call, send data and return html and replace it with the old html
lets begin :)
first step is to write ajax, and send it when form is submit or any button is clicked (as per your code)
this one is sample ajax, just fill in your data in it.
var BASEURL = window.location.origin + "/your_domain_name/";
$.ajax({
url: BASEURL + "your_route",
type: "POST/GET", //any_one
data: {
// Your data comes here (object)
},
beforeSend: function () {
},
success: function (response) {
console.log(response); // your html in return
},
complete: function (response) {
}
});
now a call will be send with your data to controller respective to specified route you mentioned, processing will be normal.
It will return only html. You can do whatever you want with this html.
One important problem you might face if considering these instructions is, right now the view you are returning is probably of whole page (because the page is been refresh every time), but if you are thinking to replace it with new html, your will only have to return that part of the page may be a single row or something like that. So break your view in many sub views. Php #include(//path) (blade) might come handy. Thats how I use to work. :)

How to redirect URL in CodeIgniter after form submission back to the previous page only when the user comes from that page?

I've tried several ways to redirect the URL back to the page where the user came from after submitting a form or just refresh the form page to allow the user to make a new entry if the user came directly to it. So far, I've been unsuccessful. The following method is the closest I've got but I'm not sure what's going wrong -
The user clicks this link which takes them to the page where the form is -
<a target="_blank" class="sampleredirect" href="<?php echo base_url();?>sample/controller/add">Add User</a>
Upon clicking, the following jQuery script links the click to a function -
<script>
$('#sampleredirect').click(function(){
$.ajax({
type: "POST",
url: "sample/controller/redfunc",
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
</script>
The function gets the URL where the click was initiated -
public function redfunc(){
$referred_from = $this->session->set_userdata('referred_from',current_url());
return $referred_from;
}
Inside sample/controller/add where the form logic is located, after the submission, I'm calling the function to redirect the user back to the previous URL -
public function adduser(){
//sample code
$this->redfunc();
redirect($referred_from, 'refresh');
}
This isn't working and I keep getting redirected to the default page that shows up if a URL can't be found. When I do vardump($referred_from) after calling the function $this->redfunc();, I'm getting NULL.
I'm kinda lost here and would love some help with this. Thanks!
$referred_from will return nothing. It is just setting a session. It will not return session value. Try below code
<script>
$('#sampleredirect').click(function(){
$.ajax({
type: "POST",
url: "sample/controller/redfunc",
data: {current_url:<?=current_url()?>}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
public function redfunc(){
$this->session->set_userdata('referred_from',$this->input->post('current_url');
}
public function adduser(){
//sample code
$referred_from = $this->session->referred_from;
redirect($referred_from, 'refresh');
}
You need to assign the $referred_from in your adduser function.
$this->redfunc();
You need assign a variable there. Because you want to receive result from redfunc() right?
so, Try it.
public function adduser(){
//sample code
$referred_from = $this->redfunc();
redirect($referred_from, 'refresh');
}
or you can do this
public function adduser(){
//sample code
redirect($this->redfunc(), 'refresh');
}
sorry. bad english
$referred_from = $this->session->userdata('referred_from');
use session->userdata to get current_url which you have stored in the session
set url in session
$this->session->set_userdata('referred_from',current_url());
Retrieve from session
$this->session->userdata('referred_from');

checking instantly php arrays using jquery / ajax

I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax.
when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div.
I was following a tutorial from youtube, however it queried against a mysql database.
I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code.
the code is as follows:
<?php
$car = array()
$car["vw"] = array( "name" => "volkswagen");
$car["tyta"] = array( "name => "toyota");
?>
the html code is as follows:
<label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" />
<div id="carnamestatus"></div>
the checkcar()
function checkcar(){
var u = _("carname").value;
if(u != ""){
_("carname").innerHTML = 'checking ...';
var B = new XMLHttpRequest();
B.open("POST","check.php",true); /
B.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
B.onreadystatechange = function() {
if(B.readyState==4 && B.status== 200) {
_("carnamestatus").innerHTML = B.responseText;
}
}
var v = "carnamecheck="+u;
B.send(v);
}
}
</script>
Use Javascript keyboard event and then, send the value of the input into your php function.
For example:
$("#youInput").keyup(
function() {
$.ajax(
{
type: "post",
url: "your_url.php",
data: {params: $(this).val()},
success: function(data) {
console.log(data)
}
}
);
}
);
And in you php code, just retrieve the params value, $_POST['params']
Explain
When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side.
Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with.
Hope it helps you!

Categories

Resources