Getting $_POST not working after Ajax successful submit in same page - php

I create a Form after user click on a div, and I submit on same page using Ajax without reloading page.
I see that the form is submitted successfully with data when I check the network tab in dev tools but when I print $_POST or check if isset($_POST["data"]), I get $_POST is empty and the if condition is false, is there any way to get the data in PHP ($_POST) without refreshing the page.
I get no errors in console or php
When using:
form.submit();
The form is submitted and I get $_POST but the page reload, this is why I need to use Ajax
My code on Js page :
function post(path, parameters) {
var form = $('<form id="form"></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", JSON.stringify(value));
form.append(field);
form.append(data);
});
$(document.body).append(form);
$.ajax({
type: "POST",
url: path,
data: $("#form").serialize(),
success: function(data) {
$('.before').hide();
$('.next').show();
}
});
return false;
}
$('.card-container').on('click',function(e){
e.preventDefault();
var page = window.location.href;
var object = {
'array': [
['string1', 'string2'],
['string3', 'string4']
]
};
post(page, object);
});
My code on PHP page :
var_dump($_POST);
if (isset($_POST['array'])) {
$array = json_decode($_POST['array'], true);
print_r("ok");
}
The full code is too long to include it here.

Related

Laravel 5.8 Redirecting after login

In my Laravel application there is the default login page aswell as a login form inside a dropdown. As I have it set up now, after a successfull login a user is redirected to the index page, however, If a user uses the login form in the dropdown I want him to stay on the page he is already.
Is there a better practice than adding a seperate method for logging in via the dropdown?
You can use axios or ajax to login and stay on the page.
Example for axios, in your script write something like this
$("body").on("submit", "#login-form", function (e) {
var action = $(this).attr("action"); // your login url
e.preventDefault();
axios.post(action, $(this).serialize())
.then(function (response) {
// do something from the response
// i.e. display error or update navbar to logged in view
})
.catch(function (error) {
// handle error here
});
});
Example for ajax, in your script write something like this
$("#login-form").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data,
beforeSend: function() {
// show loading or whatever
},
success: function(data) {
// do something from the response
// i.e. display error or update navbar to logged in view
},
error: function(xhr) { // if error occured
var status = xhr.statusText;
var response = JSON.parse(xhr.responseText);
// handle error here
}
});
});
In both examples, I assume that you will have a login form with an ID login-form

how to load another page when clicking a button in another page and pass values to the loaded page in jquery?

I have a button in a page. On clicking the button it should go to another page and that page should be viewed. Also I want to pass some values to the second page when the button is clicked and display the passed values in the second page.
I have written a code in ajax but it is not working.
<script>
$(document).ready(function(){
$(".chk").click(function(){
if($('input.checkin:checked').val()){
var apikey = '60CF3C2oh7D+Q+aHDoHt88aEdfdflIjFZdlmsgApfpvg8GXu+W8qr7bKM33cM3';
var password = 'fHdfvxk';
var endpoint = 1;
var method = 'ProcessPayment';
var dataString = 'APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
$.ajax({
type: "POST",
url: "responsive.php",
data: dataString,
cache: false,
success: function(result){
}
});
//window.location.href= 'http://localhost/m/responsive.php';
}
else{
alert("Please Accept the terms and conditions and continue further!!!!");
}
}); });
</script>
I have written a code in ajx when button click, but it will only pass the values to that page. But the page cannot be viewd. Can anyone suggest a solution for this ?
Instead of using ajax you can redirect to the page.
<script>
$(document).ready(function(){
$(".chk").click(function(){
if($('input.checkin:checked').val()){
var apikey = '60CF3C2oh7D+Q+aHDoHt88aEdfdflIjFZdlmsgApfpvg8GXu+W8qr7bKM33cM3';
var password = 'fHdfvxk';
var endpoint = 1;
var method = 'ProcessPayment';
//var dataString = 'APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
// use location href instead of ajax
window.location.href = "responsive.php?APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
}
else{
alert("Please Accept the terms and conditions and continue further!!!!");
}
});
});
</script>

Ajax/JQuery 2nd submit

I am trying to write a page where there are 2 sets of forms submitted, one to search IMDB, and then the 2nd to submit the request from the returned results.
I have the pages working just fine with just regular old php. I am wanting to convert it over to ajax/jquery to make it have a better ux, when there are large searches and database calls. I am having issues with getting the 2nd Submit button to work. I have searched for quite a while and noticed some comments about not using event.preventDefault() because any button called there after would not work and to use return false; instead. I have tried multiple combinations, even tried having it load a 2nd set of code during the posting.done of the 1st one, all to no avail.
I am trying to really understand what is going on here and what the proper solution would be.
All of this sits inside a div #dynamic
The script:
// Attach a submit handler to the form
$( "#imdb_search" ).submit(function( event ) {
// Stop form from submitting normally
//event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
form_request = $form.find( "input[name='request']" ).val(),
form_user = $form.find( "input[name='user']" ).val(),
form_username = $form.find( "input[name='username']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post(url, {
request: form_request,
user: form_user,
username: form_username
});
// Put the results in a div
posting.done(function(data) {
// var content = $( data ).find( "#returned_result" );
$("#dynamic").empty().append(data);
});
return false;
});
So I have tried this as well from one of the comments to no avail:
$( "#imdb_search" ).submit(function(){
var $frm = $(this);
$.ajax({
url: $frm.attr( "action" ),
dataType: 'html',
type: 'POST',
data: $frm.serialize(),
success: function(r) {
$("#dynamic").empty().html(r);
},
error: function(){
//TODO: add error code
}
});
return false;
});
I have this script at the bottom of each of the new php pages that is loaded from the success return. Is that the correct place to have it for DOM? Both forms have the same id but submit different "inputs".
As I can get from your code you also overwrite html form when you get first result, if it is the case then you should use jquery "on" function
$(document).on("#imdb_search", "submit", function(){
var $frm = $(this);
$.ajax({
url: 'your_post_url',
dataType: 'html',
type: 'POST',
data: $frm.serialize(),
success: function(r) {
$("#dynamic").html(data);
},
error: function(){
//TODO: add error code
}
});
return false;
});
and be sure that you don't overwrite this code with other.

What does the php insert code look like when dealing with ajax and serialized data?

UPDATE II
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(),
ycor: $('#ycor').val(),
xwid: $('#xwid').val(),
yhei: $('#yhei').val(),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
UPDATE
This does not work... the alert('nice'); is not triggered
$("#form").submit(function(e){
var postData = $(this).seralizeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type : "POST",
data : postData
});
e.preventDefault();
e.unbind();
});
$("#form").submit();
alert('nice');
My goal is to send data with a form through ajax and the page does not refresh.
I am not using a button, the submit is triggered by a javascript function which triggers the ajax
The serialized data I had follows the format of
name=name$email=email etc...
I don't know what to do with this string
This is what I have on the sending page
var frm = $('#form');
var formData = $('#form').serialize();
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
data: formData,
url: frm.attr('action'),
success: function (data) {
alert('successful update');
}
});
ev.preventDefault();
});
Does the serialized data get appended to a URL? I mean I realize upon submission the current page does not go anywhere so how would that work as far as the action page "seeing the url and pulling it" so to speak...
My action page is the cliche design of a form being submitted by a button on the same page mostly it is a declaration of the variables and then an insert line
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['name'];
$email= $_POST['email'];
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$stmt = mysqli_prepare($link, "INSERT INTO table VALUES(?,?)");
$stmt->bind_param('ss',$name,$email);
$stmt->execute();
I apologize if this is clearly wrong, I haven't used serialized form data submission before
Assuming your form method frm.attr('method') is POST, the serialized data does not get put in the URL but instead in the HTTP request body.
http://en.wikipedia.org/wiki/HTTP_message_body
If the form method is GET then the data would be appended to the end of the URL like so:
http://yoursite.com/yourrequestpage?name=yourname&email=youremail
If you are using the GET method then on the PHP side, you would have to use $_GET['email'] instead of $_POST['email'].
I also see that var formData = $('#form').serialize(); is out of the form submission function body. This should be put in the body so that it is initialized when the form is submitted (when you have filled out the form), not when the page is loaded (when you haven't yet interacted with the form).

Ajax call with target div in another page

I don't know if what i'm asking is possible,but of course should match my needs
This is my ajax call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form1).serialize();
$.ajax({
type:'POST',
url:'db_query.php',
cache: false,
data: dataString1,
success: function(data){
$('#query_database').html(data);
}
});
return false;
}
The target div is on another page. So when I submit the form I should be redirected to www.mysite.com/response and then get the ajax request executed in #query_database.
I wanted to add window.location.href = "response.html" but this just redirect me after the call has been executed.
Any way to do that?

Categories