PHP json_encode unread by jQuery AJAX Post - php

I'm posting from a form to a URL like so:
$.post('?class=articles&method=submit', $(this).serialize(), function(msg)
{
alert(msg);
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
},'json');
And in the 'submit' method the last line is:
print json_encode( array('html'=>$content) );
Yet I'm not even getting to the alert portion in the jQuery.
I have a feeling it is because the 'submit' method is in a class file that is part of a template system (similar to phpBB). I know that creating a seperate .php file for submitting would work, but was curious if there was any other way.

Looks like you don't even have a specific url:
$.post('?class=articles&method=submit', $(this).serialize(), function(msg)
Should be I think
$.post('thePlaceIsubmitTo.php?class=articles&method=submit', $(this).serialize(), function(msg)
I believe that the serialize data will be appended to the url with and &, Be sure that this refers to the form tag

try using the $.ajax method, instead of the shorthand. I believe the problem is that you're using the POST shortcut method, while specifying GET variables appended to the URL.
Let me know if this helps, if not, We'll be able to help you :-)
I'm on vacation, on a netbook, so I can't exactly write a whole new method at the moment.

Related

Jquery / Ajax form submission won't forward POST data

I have a PHP script that generates identical forms with different values (ie. lines of a database)
When one form is submitted, I want it to trigger an AJAX request that will update just that line of the database without reloading the page.
I have this AJAX script in my header:
function ajaxCall() {
$.ajax({
url:"database_quickupdate.php",
type: "POST",
success:function(result){
alert(result);
}
});
And obviously all forms have onsubmit="ajaxCall()" attributes set
But when I try to return the $_POST array from database_quickupdate.php, it comes back empty (meaning no data is passed to the script)
I tried various versions of serializing the data, including this here:
$.ajax({
type: "POST",
url: 'database_quickupdate.php',
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
but this didn't work either.
Of course I can assign unique ID-s to each of the forms, but then how can I tell ajaxCall in the header that I want the values from the form that_has_just_been_submitted?
It must be something very basic, still, I'm lost. I think I'm missing something on the jQuery side, but I'm not even sure about that.
Thanks for your help
onsubmit="ajaxCall()"
You're calling ajaxCall() by itself, so inside it this is the default object (window in a browser).
So then:
$(this).serialize()
You are trying to serialize the window and not the form.
You need to pass the form.
Don't use on... attributes. They come with a host of issues.
Bind your event handlers with JavaScript instead.
jQuery("form").on("submit", ajaxCall);
That will pass the form as the value of this.

AJAX data not displayed in page

To sum up what I'm trying to achieve here:
Inside of index.php, when selecting an option in a dropdown list, a function is called with the onchange="displayData(this) event inside of <select>
This function performs an AJAX POST request to a PHP page (target.php) with the value of the selected option inside of data
The PHP page is displayed inside a div on the page
Here is the function, using jQuery:
function displayData(str){
$.ajax({
url: "target.php",
type: "POST",
data: {"value": str.value},
success: function(data){
console.log(data);
}
});
$('#my-div').load('target.php');
}
To make things easier, here is what the PHP page looks like: <?php echo $_POST['value']; ?>
When logging data on success, everything seems to work fine, the value of $_POST['value'] is displayed in the console correctly. In the page itself though, I get an error:
Notice: Undefined index: value
Sorry if it seems kind of dumb, but I can't figure out what I'm doing wrong... So I thought of asking the community. Thank you for your help guys! Cheers.
Please try this.
and you need to return the result from target.php page
function displayData(str){
$.ajax({
url: "target.php",
type: "POST",
data: {"value": str.value},
success: function(data){
$('#my-div').html(data);
}
});
}
If you use .load() your browser will make another GET request to target.php and display it, so your $_POST will be empty.
You can use $('#my-div').html(data) inside success: of ajax or you can use $_GET instead of $_POST in your php and pass variable in url like this
$('#my-div').load('target.php?value='str.value);
hey the problem is quite simple, if you are posting the data value getting from ajax to target.php then the $('#my-div').load('target.php') should be inside the ajax success function and you have to put the data using html function like this $("#my-div").html(data). it will directly load the data in html format inside the div.

Calling a function in php with link in html

I'm trying to call a function with a link in html. I found the following example:
click to run function!
if(isset($_POST['runfunction'])){
}
This works perfectly fine, the problem is that when I click the link, "?runfunction" keeps standing in my url bar. So when I submit a form on my page it goes totally wrong (it's way to long to upload here). I do some SQL queries and I'm getting weird values in my SQL database. When I type in just my normal url it works fine. So I'm pretty sure that's the problem. I found another example with ajax :
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
I don't fully understand this example (because I never use AJAX) but my php script is included in the html page "include("")". So I can't type in url because it has to be the same page. Can someone give a little bit of info about this, or give an example of how I can fix this? Thanks in advance!
You can add a callback method then remove it from the url by javascript
function successCallback () {
url = window.location.href;
window.location = url.replace("runfunction", "");
}

Php AJAX not working in conjunction with my php script and mysql

So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.
My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.
My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.
What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.
Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.
Summary: How do I fix this ajax so that it always updates my numbers?
Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.
JQUERY / AJAX CODE
function vote() {
var request = $.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html'
});
request.done(function(vote_sum) {
$("#votes").html(vote_sum);
});
}
HTML CODE:
<div id='votes'></div>
<form id="good" action="" method="post">
<input type="submit" name="good" onclick="vote()" value="+">
</form>
<form id="bad" action="" method="post">
<input type="submit" name="bad" onclick="vote()" value="-">
</form>
In HTML you don't need <form>, you are doing it with AJAX, right?
<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>
In JavaScript, it is easier to use post rather than ajax function
function vote(gb) {
$.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
$("#votes").html(vote_sum);
});
}
In PHP, extract the vote and use it as needed (add validation/sanitation):
$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
TL;DR version:
You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.
The long version
When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:
$.ajax({
method: 'POST',
dataType: 'json',
data: ...someJSONData...
});
Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.
Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().
function vote(e) {
// e.target.id stores the id of the button that was clicked
var data = {vote: e.target.id}
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
... callbacks and other properties ...
});
}
document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);
This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:
[
'data' => 'good',
]
I hope this illustrates how easy it is to pass data around in this format.
Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.
Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.
function vote(event) {
event.preventDefault();
$.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html',
data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
success: function(data){
var votes = $("#votes").val().empty();
$("#votes").html(data+votes);
}
]);
}

Load respond of php document into a textfield - jQuery/Ajax

i do have a litte problem with my actual project.
My .HTML document gives via post some data to a php document wich is only echoing some numbers and letters but no spaces. So now id like to load that respond directly into a textbox, without showing the "ugly" respond php doc or reloading the site.
thanks for help
$.ajax({
url: "/mydoc.php",
type: 'POST',
data: {tb1: "arbitrary"}, // this could be anything
success: function(data) {
$("#myTextBox").val(data);
}});
Hope this helps!
You can accomplish this with jquery.
You will need to capture your response and set the textfield value attribute.
If you are getting data perhaps you should use GET method instead of post.
$.get('your_php_url?some_data=here&some_more_data=here', function(response, status) {
if (status === 'success') {
$('#your_textbox').val(response);
}
});
Or even better encode your data in JSON instead of passing plain text.
$.getJSON and set your textbox to the json response
you can use submit to attach a submit handler to your form. Make sure to return false so the form doesn't go to the action page.

Categories