I am struggling with the post() method.
I've been reading several posts on here and the jquery forums, and just trying to get a simple piece of code working is proving difficult. My ultimate goal is to pass a div #exportData and all it's children to test.php.
I started with:
$.post("ajax/test.php", $("body").html());
To my mind this should return the entire contents of the current page to test.php (unless test.php requires a holding div or element to receive the content). Currently it only returns the blank page.
I then tried looking at the parameters for post() if I need to manipulate these:
$.ajax({
type: 'POST',
url: ajax/test.php,
data: data,
success: success,
dataType: dataType
});
Also declared a variable:
var data = {
html: #exportData
};
That bit failed of course. I don't know how to define the data in the parameters, or if this is the right place to do it.
Although I would have thought if:
$.post("ajax/test.php", $("body").html());
would have worked then presumably I can substitute "body" for any class, id or selector I like.
Also does the submit button need certain parameters to tie it to the post function. At the moment it is purely:
<input type="submit" id="submit" value="send" name="submit">
Sorry this is such a basic question.
You could do
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
as the second parameter of $.post() is an object wich contains the data you want to send to the server.
To send the data you could do:
<input type="submit" id="submit" value="send" name="submit">
js
$('input#submit').click(function(e){
//prevent submitting the form (if there is a form)
e.preventDefault();
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
});
server side you receive the data
$html = $_POST['html']
$.post() expects an object to be passed to transfert data along with the post request:
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
var content = $ ('body').html(),
data = { content: content };
$.post('ajax/test.php', data);
Sending html in the post doesn't sound like a good idea. All elements type of input or select will be empty in the Html. You would need to use .serialize in order to get the values.
$('#submit').submit(function () {
$.ajax({
type: 'POST',
url: 'ajax/test.php',
data: {
html: $('body').html()
}
});
});
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
I am using $.ajax to submit a form, I want to add a key-value pair to the submission that are not part of the form input and it is common for all my forms.
So i planned to move common part to ajaxsetup.
I want receive these in Action as two parameters like ModelData, TokenKey
My html code
<form id="frm">
#Html.TextBoxFor(m => m.Name)
<input type="button" value="Test" onclick="AjaxPost(); return false;" />
</form>
My Java Script
$(function () {
$.ajaxSetup({ data: { 'TokenId': 'TokenId Value'} });
});
function AjaxPost() {
var frm = $("#frm");
$.ajax({
url: '/Home/Index',
type: 'POST',
data: frm.serialize(),
success: function () { }
});
}
This is not working! If i removed data in AjaxPost function TokenId is posting,
Otherwise its not.
I think this would be a good solution:
$.ajaxPrefilter(function(options, originalData, xhr){
if (options.data)
options.data += "&TokenId=TokenValue";
});
this will affect all ajax calls. Check out the codepen DEMO
When you use the jQuery serialize() function, it simply turns your form into a string in the format a=1&b=2&c=3. So you can certainly apply this function to two forms and concatenate the result, with an & between them, and use the result in your ajax call. You'd want some checks to make sure neither string is empty when you do the concatenation.
$.post(url,{key:value,data:frm.serialize},function(){
//do somehting
})
i usually do this its simple and easy, and you can add as many key:value pairs you want...
You can add a hidden field to your form with the name of TokenId and required value. Or you can modify data like below.
data : fir.serialize()+"&TokenId=TokenId+Value";
Note: You have to Encode your data before append like above
I need to retrieve data from server using jQuery AJAX on HTML form then store the response data in a php string variable. So far my code is:
<form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe">
<input name="exec" value="viewproduct" type="hidden">
<input name="customer" value="customer_name" type="hidden">
<input name="sku" value="sku_number" type="hidden">
<input name="submit" type="button">
</form>
<div id="results"></div>
<script type="text/javascript">
jQuery("#myform").submit(function(e){
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
jQuery('#results').html(data.toString());
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('fail');
}
});
e.preventDefault();
});
jQuery(document).ready(function() {
jQuery("#myform").submit();
});
</script>
But I still haven't see any result. If I just use the form normally without any js code, then I'll get the raw response data from the server/database directly on the browser. How can I save that raw response data on the browser into a string variable in php?
Change your submit() handler to include this in the first line:
jQuery("#myform").submit(function(e){
e.preventDefault(); // <---
....
and/or add return false; to the end of it.
If that stops it from reloading but doesn't show anything in your #results div, troubleshoot by changing your success() in the AJAX to use this:
jQuery('#results').html(data.toString());
If that shows something, go to your server code and split up your data into individual properties that your Javascript can separate and use individually (or combine it all into one big string if you want).
.html() takes an input of String, not an object (which data is in this case).
You won't be able to store the Javascript value into a PHP variable because PHP runs on the server and returns a response to the browser where Javascript runs on the browser. What you could do is call your script with AJAX and then set your form values with jQuery using
$("input[name=customer]").val(data);
You could either have an AJAX call for each input or you could parse out the return string to get each value. The first may be more straight forward.
If the action is becoming an issue, remove the entirely and just add an onClick to the submit button that calls a function that makes the AJAX calls.
Hope this helps!
I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1 :
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
The same origin policy prevents you from using client side JavaScript to directly discover information about arbitrary URIs (URIs you control are a different story).
You'll need to get that information with another technology, such as your server side Ruby.
You could do this by simply submitting a form to the server and returning a new webpage to the browser.
If you don't want to leave the page, then you can pass the data using Ajax. There are no shortage of Ajax tutorials out there, here is a good one from MDN.
Here's an example of an AJAX call:
$(document).ready(function () {
$("#button_check").on("click", function () {
$.ajax({
type: "GET",
url: "Your URL",
data: {
input_url: $("#textbox_id").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
});
Where your HTML is something like:
<input type="text" id="textbox_id" />
<input type="button" id="button_check" value="Submit" />
And your Ruby code would be something like:
require 'open-uri'
class TestController < ApplicationController
def index
req = open(params[:input_url])
render :text => req.content_type
end
end
I have never used RoR before, so I have no idea if this is right or works in the slightest. But it's what I could quickly conjure up when scrambling through several tutorials. It's simply the concept you seem to be looking for. You'll need to figure out how to map a URL to this method, and then update the AJAX option url to use that.
So in the Javascript code - in the done method, that means the whole AJAX request was successful and the data variable should contain the result from the Ruby code req.content_type.
Atlast I could figure out the whole thing with the great help of #Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.
What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/