Ajax submit post data to a get url - php

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.

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

passing variable in URL for ajax jquery

I am trying to understand a $.ajax call:
var url = "/api/followuser.php/" + userID ;
$.ajax(url, { 'success': function(data) {
/do something
}
});
Thia ajax call is required to pass the variable 'userID' to the file '/api/followuser.php' to make a database query(php/Mysql).
I don't have access to '/api/followuser.php' .
Can anyone help me figure out how to get the variable 'userID' from the URL in a php file to be used in a database query.( I know how to pass variable as 'data: userID,' in $.ajax and use it in a php file but i want to understand this particular example)
Maybe you mean followuser.php?user_id= instead? The slash is probably causing issues since that's interpreted as a directory by the server:
var url = "/api/followuser.php?user_id=" + userID;
you need to use GET method with ajax, to do this you can use next example
$.ajax({
url: "/api/followuser.php",
type: "GET",
data: {variable: "valueofvariable"},
success: function(data) {
console.log(data);
}
});
so in your php file you can read the variable like this
<?php
if(isset($_GET["variable"])){
echo $_GET["variable"];
// if this works you should see in console 'valueofvariable'
}
?>

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.

sending data through JSON(AJAX function) but not able to access the controller of respective page

This is my JavaScript function which I have included in HEAD tag:
function test()
{
//enter code here
$.ajax({
url: 'test?msgto='+document.getElementById('Select1').value,
dataType: 'json',
type : 'GET',
success: function(result)
{
// console.log(result);
alert('test1');
// alert(string(result[0]['Select1']) );
// alert(result[0]['TextArea1']);
//document.getElementById('Text1').Value = ;// string(result[0]['location']);
}
});
}
and I want to send data to my PHP controller using this function on Cilck event of a button. I have written the following code for GETACTION()
// TODO Auto-generated method stub
//echo('Get');
$msgfrom = 1; //$this->_getparam('usrid');
$msgto = $this->_getparam('msgto');
$sql = "call select_messages(".$msgfrom.",".$msgto.");";
$data = Zend_Db_Table::getDefaultAdapter()->query($sql)->fetchAll();
$this->_helper->json($data);
But while on clicking I am not getting any output or result....
Kindly Guide me as soon as possible..... :)
Several misuses there.
Firstly, are you sure GETACTION() retrieves the /test path?
Secondly, in your JS code, I'm not sure you are calling the right path.
You'd better use this :
$.ajax({
type: 'GET',
url: '/test', // Notice the '/' at the beginning
data: {
msgto: $('#Select1').val(), // Since you're using jQuery, do it all the way :)
}
success: function(result) {
alert(result);
}
});
Notice the slash at the beginning of the url parameter. It means: "starting after the domain name". Also, you don't need the use the verbose document.getElementById() when you're using jQuery :).
Lastly, see the data parameter. jQuery will automatically build the correct URL before sending the AJAX request. I think it keeps your code cleaner.

Can I access the href of my ajax request in the javascript of my request?

Here a sample use case:
I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?
Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.
I can't use location.href, b/c it refers to the window's location not the latest request.
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : '<?= $_SERVER['PHP_SELF'] ?>',
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});
If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?
You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:
jQuery.ajax({
url : frm.action,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : window.location.href,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});

Categories