All,
I have a Jquery ajax request calling out a URL. The ajax response I receive is an HTML form with one hidden variable in it. As soon as my ajax request is successful, I would like to retrieve the value of the hidden variabl. How do I do that?
Example:
html_response for the AJAX call is :
<html><head></head><body><form name="frmValues"><input type="hidden"
name="priceValue" value="100"></form></body></html>
$.ajax({
type: 'GET',
url: "/abc/xyz/getName?id="+101,
cache: false,
dataType: "html",
success: function(html_response)
{
//Extract form variable "priceValue" from html_response
//Alert the variable data.
}
});
Thanks
The html_response you get will be a string. As such, if you happen to know exactly what the page will look like, you can just search the text using indexOf.
...But that solution is messy and error prone. Alternatively, you could create a new HTML element (like a div), put your response html in there, and then obtain the hidden variable as you would access any normal html element.
For example:
var tempDiv = $("<div/>");
tempDiv.append(html_response);
var myValue = tempDiv.find("input[name='priceValue']").val();
You can create JQuery object:
var form = $(html_response);
Then get your input PriceValue using JQuery selectors & traversal.
You can read it with $(html_response).find("input[name='priceValue']").val();
Related
I have an ajax call to a PHP module which returns some HTML. I want to examine this HTML and extract the data from some custom attributes before considering whether to upload the HTML into the DOM.
I can see the data from the network activity as well as via console.log. I want to extract the values for the data-pk attribute and test them before deciding whether to upload the HTML or just bypass it.
$.ajax({
url: "./modules/get_recent.php",
method: "POST",
data: {chat_id:chat_id, chat_name:chat_name, host_id:host_id, host_name:host_name}, // received as a $_POST array
success: function(data)
{
console.log(data);
},
})
and some of the console log data are:
class="the_pks" data-pk="11"
class="the_pks" data-pk="10"
etc.
In the above data I want to extract and 'have a look at' the numbers 11 and 10.
I just do not know how to extract these data-pk values from the returned data from the ajax call. Doing an each on class 'the_pks' does not work as at the time I am looking at the data they have not been loaded into the DOM.
I have searched SO for this but have not come up with an answer.
Any advice will be most appreciated.
I hope I understand your question.
If you get a HTML as a response, you can always create an element and insert that html inside it, without adding it to the DOM. And after that you can search it as you do with a DOM element.
const node = document.createElement("div");
//then you can do
node.appendChild(data);
// or
node.innerHTML = data;
And after that you can search inside the node:
node.querySelectorAll("[data-pk]")
I will re-engineer this - it was probably a clumsy way to try and achieve what I wanted anyway. Thanks to those who tried to help.
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
My ASP.NET MVC4 controller returns an XML string, when we pass it a SERIAL. Now when I send a request using C#, it works fine, XML string comes back , and looks like
<CalculatedCode> 12312312 </CalculatedCode>
I need to also do it via jquery like below. Query is working but it is returning an XMLDocumentObject , instead of an xml string. I looked at Jquery documentation to try to parse it, but I'm a jquery noob and I'm sure I'm making an error in the code.
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
dataType: 'xml',
data: { SERIAL: serial}, //SERIAL comes from a textbox
success: function (responseData) {
//Code below is messed up, it simply needs to find the CalculatedCode tag
//and extract the value within this tag
xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
$thecode = $xml.find("CalculatedCode");
// ToDo: Bug stackoverflow members with this noob question
}
});
Thank you very much :)
It's already parsed when you set the dataType to XML, so no need for $.parseXML, but if the element is a root element, find() doesn't work, as it only finds children, you'll need filter()
$xml = $(responseData);
$thecode = $xml.filter("CalculatedCode").text();
an trick that gets the element either way is to append the xml to another element :
$xml = $('<div />').append(responseData);
$thecode = $xml.find("CalculatedCode").text();
I'm using CakePHP and since several days I try to store a java script variable with the help of ajax (jQuery) in a mysql database.
I'm using the following code to do this:
<!-- document javascripts -->
<script type="text/javascript">
$(document).ready(function () {
$('#saveForm').submit(function(){
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
success: function(data,textStatus,xhr){
alert(data);
},
error: function(xhr,textStatus,error){
alert(textStatus);
}
});
return false;
});
});
</script>
But when I click on the submit button, Ajax will post the whole sourcode of my webpage. =(
What I need is a function to store a java script variable to my database but without reloading the page.
I am grateful for any help =)
You told jQuery to serialise a form element. That is, convert the form element to a text string. In other words, you are telling it to get the form's HTML code and send that to your server.
I don't know (or want to know) what the correct way of sending a form's data by AJAX is, but I do know that you need to actually do something like access the form's fields to get their values.
My js is a bit rusty but try changing:
var formData = $(this).serialize();
To:
var formData = $('#saveForm').serialize();
Or:
var formData = $('#saveForm').val().serialize();
That's assuming you want to serialize and store the html of the whole form.
To pull just a value from the form (I don't think you need serialize) try:
var formData = $('#saveForm #someInputName').val();
Of course changing someInputName to whatever the actual name of the field you want to save is.
The problem could be in data parameter.. $('#saveForm').serialize();
should be ok
I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.