How do I change the action on a form with javascript? - javascript

I use laravel 5.3
My form like this :
{!! Form::open(['route' => 'shop.process','id'=>'my-form']) !!}
...
{!! Form::close() !!}
If it meets certain conditions, I want to change the action
My condition in javascript like this :
if (true) {
$('#my-form').attr('action', '/shop/detail')
return true;
}
If the condition is met, it success to convert the url into this:
http://myshop.dev/shop/detail
But, the content is not display
Content from that page just appear when I click the url and enter
How can I solve this problem?

If you want to change the content of the form youll need to load that form with ajax into the form area.
Assuming that /shop/detail is another form. You should do it like this. Either using .load(), or .ajax()
if (true) {
$('#my-form').attr('action', '/shop/detail');
$('#my-form').load('/shop/detail');
return true;
}
Or..
if (true) {
$('#my-form').attr('action', '/shop/detail')
$.ajax({
url:'/shop/detail',
success:function(data){
$('#my-form').html(data);
}
})
return true;
}
However, the two methods above are unlikely to work, because I doubt your /shop/detail is only the inner form. Its most likely the entire form. Ie . So that means you need to fully replace the element. Not load the data into the old form.
if (true) {
$.ajax({
url:'/shop/detail',
success:function(data){
$('#my-form').replaceWith(data);
return true;
}
})
}

Related

show a div based on a conditional ajax result in php form

I have a PHP form`looks like this
<form>
<div id="inid">
National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" />
</div>
<hr />
name: <div id="individual_name_fetch"></div>
<hr />
<div id="other_inputs fields" style="display: none;">
more inputs fields...
</div>
</form>
In my PHP form I have an input textbox where the user inserts a number
<input id="individual_nid" oninput="getIndividualName(this.value)" />
this textbox fires on the fly the following ajax function
function getIndividualName(val)
{
$.ajax({
type: "POST",
url:"get_individual_name.php",
data: 'individual_nid='+val,
success: function(data){
$("#individual_name_fetch").html(data);
}
});
}
in this function, I pass the user's input to the get_individual_name.php page.
in the get_individual_name.php page, I have a PHP script that searches for the inserted number in the database and gets the corresponding individual name and fetches it to the id="individual_name_fetch" div.
the PHP script in the get_individual_name.php page looks like this:
$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
if(mysqli_num_rows($q) == 1)
{
while($r = mysqli_fetch_assoc($q))
{
echo $individual_name = $r['individual_name'];
}
}
else
{
echo $individual_name = 'Not in db';
}
up to here everything is fine
What I need to do now...
If the searched user founded in the db (mysqli_num_rows($q) == 1) then I want to display the other inputs div id="other_inputs fields" in the form. and if not, then the other_inputs fields div hides again
How can I accomplish this?
please be aware that the ajax function and the PHP script run on the fly
NOTE & UPDATE
the script's output will be HTML code, for example
if the result found the output will be:
<span style="color: green;"><i class="fa fa-check fa-fw fa-lg"></i> <?=$individual_name;?></span>
OR
in case no result found:
<span style="color: red;"><i class="fa fa-times fa-fw fa-lg"></i> No user found.</span>
What I am thinking about is to assign a variable e.g. $show_extra_fields = true or $show_extra_fields = false and pass it back to the ajax function and from there I check the value of the $show_extra_fields variable and based on the value I show/hide the other fields div.
is this possible?
To do what you're asking you would add show and hide functions to the AJAX callback:
function getIndividualName(val)
{
$.ajax({
type: "POST",
url:"get_individual_name.php",
data: 'individual_nid='+val,
dataType: 'json',
success: function(data){
$("#individual_name_fetch").html(data);
if(data[0] != 'Not in db') {
$('#other_inputs').show();
} else {
$('#other_inputs').hide();
}
}
});
}
Keep in mind that ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements. ID's must not have spaces in them.
EDIT: Return JSON with PHP (CAUTION: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!)
$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
$json = array();
if(mysqli_num_rows($q) == 1)
{
while($r = mysqli_fetch_assoc($q))
{
$json[] = $r['individual_name'];
}
}
else
{
$json[] = 'Not in db';
}
echo json_encode($json);
You can do that using JavaScript. Check the AJAX response then take an action depending on this response.
Note: Don't use spaces in the id in your html
success: function(data){
$("#individual_name_fetch").html(data);
if (data === 'Not in db') {
document.getElementById('other_inputs_fields').style.display = 'none';
} else {
document.getElementById('other_inputs_fields').style.display = 'block';
}
}
The quick fix: Don't produce any output in case there is no data. Just check for empty string in response.
success: function(data) {
if (data === "") {
$('#other_inputs_fields').hide();
$("#individual_name_fetch").html('No data available');
} else {
$('#other_inputs_fields').show();
$("#individual_name_fetch").html(data);
}
}
Long term solution: This code still looks OK for student's assignments work or hobby project. But in all other cases, you better look for some WEB framework, like Symfony https://symfony.com/. Frameworks will help you to build your application in a more structured way, offering the best practices our of the box, including the security issues pointed out in comments.

codeigniter: I can't change view page

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.

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. :)

Use jScript / AJAX to call PHP script but ONLY if form has been submitted?

This is kind of a follow up to this question.
I have this code:
var chpass = function()
{
var pass1 = encodeURIComponent($("#pass1").val());
var pass2 = encodeURIComponent($("#pass2").val());
$.ajax(
{
type: "POST",
url: "lib_ajax/somescript.php",
data: "pass1="+ pass1+"&pass2="+ pass2,
success: function(msg_pass)
{
$("#status_pass").ajaxComplete(function(event, request, settings)
{
if(msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
});
}
});
}
$("#signup").ready(chpass);
$("#signup").change(chpass);
And in the php script:
$pass1 = trim($_POST['pass1']);
if(!isset($pass1)||empty($pass1)) die('empty pass1');
My problem is that I don't want the form to be validated with ready() the first time the page is loaded but every time the page is loaded after a submit.
I have tried to figure out how to set a default event for the handler and then use preventDefault but I've been completely unsuccessful so far.
Could part of the problem be that when the page is submitted some additional validation happens on the server and in some cases I use header('Location: ') to reload the page?
Any tips how I can work this out? Is there a way to change it to something like:
if ( FORM IS SUBMITED ) $("#signup").ready(chpass);
Or maybe:
if ( FORM IS SUBMITED && msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
Can also add that I have tried to change ready() to submit() with no luck:
$("#signup").submit(chpass); // DO NOT WORK
I finally found a solution. Change the code:
$("#signup").ready(chpass);
to:
<?php if(isset($_POST['submit'])) { ?>$("#signup").ready(chpass);<?php } ?>
and that part of the jScript is left out unless the form is submitted!

click button execute php file then redirect

Good day to all,
Been searching all day on how to do this. What I want is to make every 'click' to go into one php file and determine what will be the action.
itemAction.php
include 'inc/database.php';
include 'inc/functions.php';
if ($_GET['action'] == 'delete') {
// do delete action <-- this one is working
} else if ($_GET['action'] == 'edit') {
// do edit action; NOW HERE I WANT TO REDIRECT TO ANOTHER PAGE
header("location: edit.php"); // I can't do something like this. Why?
}
html
<div class="action">
<a id="delete" href="itemAction.php" rel="<!--some_id-->"><img src="images/trash.ico" alt="delete"></a>
<a id="edit" href="itemAction.php" rel="<!--some_id-->"><img src="images/Pencil-icon.png" alt="edit"></a>
</div>
js
$("div.action a#delete").click(function (e) {
var decision = confirm("Are you sure you want to delete the item?");
if (decision) {
e.preventDefault();
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")}, function (data) {
location.reload();
alert("Succssfully deleted!");
});
}
return false;
});
$("div.action a#edit").click(function (e) {
e.preventDefault();
$.get('itemAction.php', {action : 'edit', id : $(this).attr("rel")});
});
The delete action seems to be working.. But I can't do I want in the edit action which is to redirect to other page. What better ways are there to do it that way? Any help would be much appreciated. Thanks
You can not do this because ajax will only send you response html, text, xml or json response but can not do redirection.
For redirecting you must return anything say "redirectme." and based on that response you need to add code in javascript to redirect at desired location.
what you can do is?
in php file add below code,
echo json_encode(array('status' => 'edit', 'url' => 'edit.php'));
based on above response modify your $.get response callback as below.
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")},
function (data)
{
if(response.status == 'edit'){
window.location = response.url;
}
});
it just a guide line you need set it according to your need.
Comment Response
if js is disabled then you need to code accordingly.
first of all you need to modify your html links as below,
<a id="delete" href="itemAction.php?action=delete&id=someid"
<a id="edit" href="itemAction.php?action=edit&id=someid"
and by clicking on above link use their href attribute to pass into $.get as below.
$.get( $(this).href()
by doing so it js is disabled your code will work too.
Have your button go somewhere
<form method="get" action="someScript.php">
<button>Do things</button>
</form>
Then in someScript.php
<?php
// do things
header("Location: redirectToHere.php");

Categories

Resources