Jquery .ajax doesn't return useful data - php

I have a jquery script in my file that says this:
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
success: function(message){
console.log(message);
}
});
e.preventDefault();
})
});
Then I have a php script at testJSON that says this:
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
echo json_encode($data);
}
The place where console.log looks for message gives me {"name":"Alan-Sue","hobby":"boxing for donuts"}, which seems correct, except that it's immediately followed by the full html of my web page. And if I try console.log(message.name) it says 'undefined.'
What's going on here?

it sounds like your /testJSON/ page is outputting more than just whats written in your public function. if you are using an mvc or any kind of framework, you must immediately exit or die after that echo json_encode, otherwise the other part of the page will still render, probably.

You're on the right path, although as others have mentioned, it seems like you are using a MVC framework for your website and it is including the content of your webpage after displaying the JSON string. jQuery/JavaScript cannot parse JSON if there are other random text or characters in the response. You will need to use exit; or die(); after the JSON is echo'ed as the following example shows...
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
// Will halt the script and echo the json-encoded data.
die(json_encode($data));
}
Also, you will want to make sure that jQuery is parsing the response as JSON. By default it will attempt to make an intelligent guess of which type of data is being returned, but you cannot always rely on that. You should add the dataType option to the AJAX call like in the following example...
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
// It is best practice to "preventDefault" before any code is executed.
// It will not cause the ajax call to halt.
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
// This is the proper data type for JSON strings.
dataType: 'json',
success: function(message){
// JSON is parsed into an object, so you cannot just output
// "message" as it will just show "[object Object]".
console.log(message.name);
}
});
});
});
</script>
I've included some comments in the code to help better explain. Hopefully this will help you out a bit more. You also do not need to using the full $.ajax function unless you plan on using error handlers or any other of the more advanced options within that function. Alternatively, you can shorten your code by using $.post and accomplish the same as your original example with less code.
<script type="text/javascript">
$(document).ready(function() {
$('#myButton').click(function(e){
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.post(submiturl, formdata, function(message) {
console.log(message.name);
});
});
});
</script>
More options and usage information about $.ajax jQuery.ajax();
More information about $.post jQuery.post();

Parse the message variable as json before trying to log message.name.
data = $.parseJSON(message);
console.log(data.name);
Also do an exit in the php script after the echo statement and check..

Related

Why am I not receiving variable from JS to PHP?

I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call

Display HTML returned as JSON during AJAX call

My AJAX call previously returned an array of data as JSON using "echo jason_encode(array)" in my PHP code and I then looped through the result in my script and built the HTML using the returned data before displaying.
Now I changed the code to build the HTML in my PHP code and I want to return the HTML string to my script and display the HTML but I have no idea how to get it working and I have looked at over a dozen examples on this site and others but no luck.
PHP
$html = '<tr><td><div class="dummy">This is some text.</div></td></tr>';
$arr[] = array('html' => $html);
echo json_encode($arr);
Script
<script type="text/javascript">
$('.mashed_row a').click(function () {
var link_id = $(this).attr('link_id');
$.ajax({
type: 'POST',
url: 'explode',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if(data)
{
var txt = data['html'];
$("#xarticletab").html("");
$("#xarticletab").append(txt).removeClass("hidden");
$("#comments").removeClass("hidden");
}
}
});
return false;
});
</script>
First of all, I think there is an error on your JS code: link_id alone.
on JS, you should define key: value. So, maybe 'link_id': link_id ?
Correct typo: {key1: 'value1', 'key2': 'value2'}
After, use console editor of your browser to know if there is any Javascript error.
Alternatively, you can play with javascript functions: console.log(data); or event alert(data)

Ajax submit post data to a get url

Is it possible to mix post and get in ajax? Specifically have a form POST data to a url with get variables?
In html and PHP I would normally do this:
<form action="script.php?foo=bar" method="POST">
...insert inputs and buttons here...
</form>
And the PHP script would handle it based on logic/classes.
I have tried the following and several variations to no avail:
$(document).ready(function() {
$('#formSubmitButton').click(function() {
var data = $('#valueToBePassed').val();
$.ajax({
type: "POST",
//contentType: 'application/json',
url: "script.php?foo=bar",
data: data,
processData: false,
success: function(returnData) {
$('#content').html( returnData );
}
});
});
});
Is this even possible? If so what am I doing wrong. I do not feel as if I am trying to reinvent the wheel as it is already possible and used regularly (whether or not if it is recommended) by plenty of scripts (granted they are php based).
Please check out the below jsfiddle URL and
https://jsfiddle.net/cnhd4cjn/
url: "script.php?data="+data, //to get it in the URL as query param
data:"data="+data, // to get it in the payload data
Also check the network tab in dev tools to inspect the URL pattern on click of the submit button
You can, here's what I do.
$(document).ready(function() {
$('#formSubmitButton').click(function() {
// My GET variable that I will be passing to my URL
getVariable = $('#valueToBePassed').val();
// Making an example object to use in my POST and putting it into a JSON string
var obj = {
'testKey': 'someTestData'
}
postData = JSON.stringify(obj);
// Jquery's AJAX shorthand POST function, I'm just concatenating the GET variable to the URL
$.post('myurl.com?action=' + getVariable, postData, function(data) {
JSONparsedData = $.parseJSON(data);
nonparsedData = data;
});
});
});
I can see 1 syntax error in you code .
use
data: {data:data},
instead of
data: data,
and then try to access like
$_POST['data']; and $_GET['foo'];
But i have never tried the GET params inside a POST request :) , this is only a suggestion.

Get div content with jQuery for PHP

UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.

jquery: calling invisible php-mailer? ajax?

hey guys,
i know how to create a simple php file that mails some information to me.
However what I don't know is how to call that php-file with jquery and hand over a variable.
Handing over a variable might work with isset()...
How can I call this PHP mailer from jquery and do that HIDDEN from the user. So there should not pop up a new window and shouldn't be a page refresh or anything like that.
$('a.report').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
//call mail script and pass along the "id" variable
//change text (maybe in a callback function IF THE MAILING WAS A SUCCESS.
$(this).parent().text('Thank you for reporting.');
})
So I have this a.report Link which should trigger the email script. In my email script I need to access the "id" variable set in jquery. And it would even be nice to have a callback function if the php script did it's thing so I could output "Thank you for reporting".
How to do that?
Thank you guys.
I would use $.post():
<script type='text/javascript'>
$(function(){
function onReportPosted(data) {
// data.status - either 'error' or 'success', from mailer.php
// data.message - some text, from mailer.php
$('.result').text(data.message);
}
$('a.report').click(function(e) {
$('.result').text('sending report...');
var data = {
text: $('textarea[name=text]').val()
};
$.post(
'mailer.php',
data,
onReportPosted,
'json'
);
return false;
});
});
</script>
And in mailer.php:
<?php
if ( isset($_POST['text']) ) {
// mail()...
$result = array(
'status' => 'success',
'message' => 'thank you for reporting',
);
} else {
$result = array(
'status' => 'error',
'message' => 'some error occurred',
);
}
header('Content-Type: application/json');
echo json_encode($result);
exit;
Update: here's a way how to "tie" callback to a specific element:
<script type='text/javascript'>
$(function(){
$('a.report').click(function(){
var htmlElement = $(this).parent();
var data = {
// ...
};
$.post(
document.location.toString(),
data,
function(data) {
htmlElement.html(data.message);
},
'json'
);
return false;
});
});
</script>
see $.post to know how to call and pass the id to the php script (http://api.jquery.com/jQuery.post/)
It will be somthing like
$.ajax({
context: $(this),
type: 'POST',
url: 'script.php',
data: {id: id },
success: function() {
$(this).parent().text('Thank you for reporting.');
}
});
And in the php script, $id = $_POST['id'];
try:
$.post('script.php', {variableName: value, variable2Name: value2});
in php: $value = $_REQUEST['variableName']; $value2 = $_REQUEST['variable2Name'];
jQuery provides some great AJAX methods for us under the AJAX API catagory. I think $.post would be what you're looking for. This is how I send JSON data to a simple PHP script in my Grooveshark userscript:
$.ajax({
type: 'POST',
url: 'http://path/to/script.php',
data: JSON.stringify({key: 'value', array: ['one', 'two', 'three']),
dataType: 'json',
success: function(data){
console.log('Mailer returned with object ', JSON.parse(data) );
}
});
And here's how I parse it in PHP:
$incoming = json_decode(file_get_contents("php://input"), true);
This returns nested associative arrays for the JSON content, very easy to parse! I highly recommend using JSON as your data interchange format. Much better than XML.

Categories