I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!
Related
I am having an issue with saving a form. The form itself has about 40 rows with around 12 inputs for each row in this style:
On save, it should POST and then close the window. However, it never truly saves it. This makes me think that it is closing the window before it saves. Here's the code in question:
$('#save-btn').click(function() {
document.form.submit();
window.close();
};
If I remove the window.close() and use the inspector than I see in the parameters field that all the values save correctly. This is again what lead me to think that the window is closing to early.
I have tried using the following in the above #save-btn function:
setTimeout('window.close()',5000)
Yet this never seemed to execute the window.close() after the 5 seconds and all around seems like bad programming to force it to wait 5 seconds and then close when it could take any amount of time.
I then attempted to use an AJAX request like:
var _url = 'submit?nameParam="+nameParam+"&com=editlist&'+$('form').serialize();
console.log(_url); //just to see what its pushing out
$.ajax({
url: _url,
error: function(){
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
This resulted in 414 Request-URI Too Long. I know the case for this is it should be a POST to begin with, but I was just trying to make it work.
Just because, this is how our form is set up:
<form name="form" action="submit" method="post">
Our solution was to close the page from our action page
Remove the serialized data from your _url and instead pass it through the .ajax() request with the data setting:
var _url = 'submit?nameParam="+nameParam+"&com=editlist';
$.ajax({
url: _url,
method: "POST",
data: $('form').serialize(),
error: function() {
alert('Error submitting form.');
},
success: function() {
window.close();
}
});
Your ajax approach is correct because you can understand that form submit done correctly with code, on success post it is easy to close the window.
For sending a POST request, you have to make some small changes in your code...
Don't serialize your form and add URL, it is not safe (not working for your situation).
Post your values as "post data".
Here is documentation about it.
https://api.jquery.com/jquery.post/
Please try and update your question if you cannot understand how.
Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.
I am working on an instant search thing and when I submit the form search-form it is going to make an ajax post to PHP. It sends and everything but then the PHP page says that the variable has no value but the data is clearly being posted.
$('#search-form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "Search.php",
cache: false,
data: $("#search-form").serialize(),
success: function(data) {
alert($("#search-form").serialize());
$("#searched").fadeIn("fast");
$("#results").empty();
$("#results").append(data);
}
});
return false;
});
Make sure you have a console opened up in your browser, Firefox: bugzilla, Chrome and IE have a built-in. It shows you what is happening in asynchronous requests.
in your php file at the top do this:
var_dump($_POST);
//OR DO THIS:
// print_r($_POST);
Then look at your browser console to see what the response is. It should spit out an array. and you can see what the name of your data is. This is the quickest way to debug any ajax request.
Also, don't forget that you serialized the data with .serialize();