Post variable before redirect? - php

I am currently building on a CMS. I want to send a page-id or site-id to the next page on redirect. I tried doing it using the jQuery POST function:
$(document).ready(function(){
$('.sender').on('click','a',function(){
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: { siteid:siteid },
success: function(response){
console.log('check');
},
error: function(){
console.log('error');
}
});
});
});
But because the request is sent at the same time as the redirect, it does not seems to work.
Because I am using the apache rewrite_engine to redirect stuff, I cannot use GET.
Apart from session_variables, what are my options?
I want to keep it safe, so I don't want much info to be visible/available!

To achieve this you need to wait for the AJAX request to complete before the page is redirected. Try this:
$(document).ready(function(){
$('.sender').on('click', 'a', function(e){
e.preventDefault(); // stop the default redirect
var url = $(this).attr('href');
var n = url.indexOf('#') + 1;
var siteid = url.substr(n, url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: {
siteid: siteid
},
success: function(response){
console.log('check');
window.location.assign(url); // redirect once the AJAX has successfully completed
},
error: function(){
console.log('error');
}
});
});
});

I'm not sure to clearly understand why you need but I think this can answer your problem.
If what you need is to transfert informations using a real POST method, just create an hidden form with method="POST" and fill it on click event.
<script type="text/javascript">
$(document).ready(function(){
$('.sender').on('click','a',function(event){
event.preventDefault();
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$('input[name="siteid"]').val(siteid);
$('#redirectForm').submit();
});
});
</script>
<form id="redirectForm" action="pages.php" method="POST">
<input type="hidden" name="siteid" value=""/>
</form>

Related

loading url to bootstrap modal using ajax in Laravel not working

In Laravel -Controller name is ProductController, method is showproductinmodal .
I tried this, javascript code it worked.
Web Route:
Route::get('admin/product/show/{id}', 'Admin\ProductController#showproductinmodal');
JS:
<script>
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);
});
</script>
Url loaded and returned some text to modal.
But this Javascript code not worked, i want to use code below:
$(document).ready(function(){
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$.ajax({
url: '{{route('admin.showproductinmodal')}}',
type: 'post',
data: {id: productid},
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
My web route code
Route::post('admin/product/show/', 'Admin\ProductController#showproductinmodal')->name('admin.showproductinmodal');
My Controller code:
public function showproductinmodal(Request $id)
{
return "Your test id:" . $id;
}
My a tag
Any ID test
Modal works normal, pops up when I use first javascript code everything works ok data loading, but second javascript code is necessary for me. I inserted alert also in $.ajax request but it didn't work.
Might be you are missing crsf token in you case:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set csrf token for ajax call once then call N number of ajax:
$(document).ready(function () {
$('.showinfo').click(function () {
var productid = $(this).data('id');
let url = "{!! route('admin.showproductinmodal') !!}"
// AJAX request
$.ajax({
url: url,
type: 'post',
data: {
id: productid
},
success: function (response) {
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
And it will me more better, if you will use bootstrap model event, and use base url with javascript global variable.

PHP undefined Error while passing data from Ajax

Simply i want to pass Numeric id to Php page and Using $_POST['id'] i want use it, But Getting Undefined error. check screen shot https://imgur.com/a/M1v4mEX and check code below
===>edit.php
$('#update').click(function(){
var serialData = new FormData($("#regForm")[0]),
s = location.search.split('='),
searchId = s[s.length-1];
console.log(serialData);
console.log(searchId);
serialData.append('id',9);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: {id:9},
success:function(jsonObj){
console.log(jsonObj);
}
});
});
==>update.php
<?php
if(isset($_POST['submit'])){
var_dump($_POST['id']);
exit();
}
?>
You forgot to change the id value to send in parameter to the dynamic value from the location.search
Also think about adding e.preventDefault(); because you work on form submission.
I think that serialData can be removed cause it doesn't have affect the current code logic
Here is the working script
<script>
$('#update').click(function(e) {
e.preventDefault();
var s = location.search.split('=');
var searchId = s[s.length-1];
// Verify the current ID passed on search parameter
console.log(searchId);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: { 'id': searchId },
success:function(jsonObj){
console.log(jsonObj);
}
});
});
</script>

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Posting a sub-form with jQuery

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Rebind dymanically created forms after jQuery ajax response

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Categories