click button execute php file then redirect - javascript

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");

Related

How do I change the action on a form with 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;
}
})
}

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

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

jQuery Validation Plugin: same form, different validation submitHandler

I am using a single form in two different scenarios - Create and Edit.
I do something like
<?php
if($status == 'new')
echo '<button id="btnSubmit" type="submit" class="btn">Submit!</button>';
else
echo '<button id="btnEdit" type="submit" class="btn">Edit!</button>';
?>
What I want to achieve on my javascript end is to validate the form and call the correct web service according to which button is pressed. I am using the jQuery Validation Plugin found here.
Javascript
$('#myForm').validate({
submitHandler: function(data) {
$.ajax({
url: "service1.php"
...... other AJAX stuff ..........
});
}
}
$('#btnSubmit').click(function() {
// call service1.php
});
$('#btnEdit').click(function() {
// call service2.php
});
The method for validate can be a single function and you can set a flag(For example you will get an id in the edit page) to identify edit page or add page. So that you can check the flag in submit handler and submit the form to where it needs to be submitted. I'm not familiar with PHP and i hope this might help you.
Based on Marikkani's suggestion, I have implemented the below and it works. Hope it helps someone with a similar problem using Javascript and PHP.
In my form file I used a hidden div to store the type (new or edit).
<input type="hidden" id="type" value="<?php echo $type; ?>" />
Thereafter, in my javascript file I retrieve this value and check before calling the respective ajax.
$('#resForm').validate({
submitHandler: function(form) {
var type = $('#type').val();
if(type == 'new') {
$.ajax({
url: "service1.php"
.... other AJAX stuff
});
} else { // type is edit
$.ajax({
url: "service2.php"
.... other AJAX stuff
});
}
}
});

Categories

Resources