Replace div after jquery post - javascript

I'm using an ajax post request to authenticate users, this script replies with a full webpage. Within the response if successful there is a div called #logged.
What I would like to do, is check if the requested result contains logged and then replace content within the corresponding #primary-content div. How can I do it?

I want to check if the response contains a div called logged, then get the content of a div called 'primary-content' contained in the response string.
Pretty simple really... Once your ajax object readyState has reached 4.
Just do this... presuming your ajax or data object is called ajax.
var logged = $("#logged", $(ajax.responseText)); //grab the logged element from the ajax obj
//check that the logged element exists
if(typeof logged !== "undefined"){
//replace the content
$("#primary-content").html(logged.contents());
}
Sources
Detecting an undefined object property
Grabbing Content from Other Pages with Ajax and jQuery
load a specific element from an ajax loaded page
parse html string with jquery

Do you want to check if ajaresult contains "logged " ?
var primaryContent = '';
$.ajax({
url: 'ajax/test.html',
success: function(data) {
var loggedDiv = null;
loggedDiv = $(data).find('div#logged');
if(loggedDiv != null && loggedDiv != undefined){
primaryContent = $(data).find('div#primary-content').html();
}
}
});

Related

how to adjust margin session flash in php?

I am trying to flash a success message when data store successfully. My database code and every other thing working fine but when I give $_SESSION success message it always come under navigation.
1) I want to know is there any way in php to set margin of $_SESSION['success_flash'] message
2) is there any way like /n/n type so that my flash message will show two line below
3)
My real code is:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried /n/n but not working:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried style="margin-top:200px;" but not working:
$_SESSION['success_flash'] = '<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
Kindly check the image below only green background is showing under the navigation bar and the text message "Data saved successfully!" not showing because it is hidden under the navigation.
One more thing I am using below code after the flash message and my code end.
echo "<script type='text/javascript'> document.location = 'index.php'; </script>";
Any idea or suggestion would be helpful.
Thanks you.
I am getting data and passing the data to database successfully. I just want to reload my page after php call and show sucess flash to the user.
My Ajax Call: top my php page.
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
PHP once loaded it does not change on the page, it is not dynamic. The way you do this is rather weird, but can be acomplished if you will set $_SESSION['success_flash'] just right after saving the data in the database, and reaload the page.
In my opinion the best way is to use ajax here, and the ajax response can change the container under the menu to "success".
But I don't know how do you send your data, is it by POST form or something?
Add display:inline-block; or display:block; in the styles of the span.
As long as dom elements behaviour can depend on outer dom objects (and you do not specify them): if it still does not work try using padding instead of margin, if it still does not work place two span tags one inside other both with inline-block.
All that stuff using $_SESSION is kinda weird, however XD... but from your description I assume that it shows already the span, but without the margin... but you should not use $_SESSION in that way.
OK, now we are getting somewhere. But now location.reload is unnecessary, because if you will receive 'passed' answer, you can set the communicate without reloading (and without using any code in session variable, get rid of $_SESSION['success_flash']), like below.
Please note that I do not know what is the CSS class or ID of your green DIV (if any), so for this specific example I will assume, that it has a class ".msg-response"
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
// this new line will change the content of your message div
$('div.msg-response').html('<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>');
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
there is also a security risk here: "if (data != 'passed')" - you will echo PHP errors (path, filename, variables, class, code row etc.) when something unpredictionary will happen, unless you will turn display_errors off on your server (display errors should be enabled only in development mode, that's a good practice).
To avoid it you can use JSON response here, handle the "error" status, "success" status, and do nothing if JSON response is different from "success" or "error".

Passing array through ajax

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

AJAX call not going to the server

i am using ajax to populate a drop down but the call is not going to the server. getting the following error in fire bug
POST 0
status 404 not found
my code is:
function selectChildCategory(parent,child){
var url = "<?php echo url::site('admin/video/showSubCategory/')?>";
if(parent != "")
{
if(child != 0){
url = url+parent+"/"+child;
}else{
url = url+parent+"/"+0;
}
$.ajax({
url: url,
type:"POST",
success: function(select)
{
//alert(select);
$("#sub_category").html(select);
}
});
}
}
the parammeters are showing correct values....but call is not going to the server. The URL is correct
please advise.
404 Error code means that the page your are trying to call does not exists.
You are buildng a HTTP path using your parent and child variables but if the formed url does not exists (or is not captured by any mod_rewrite) a 404 error is shown.
For example, for parent "0" and child "0" the url /admin/video/showSubCategory/0/0 exists?
Also if you are using something like mod_rewrite is really correctly configured?
Try first calling the URL manually to check if the url generated by javascript really exists.
Have you checked that the URL is available via a POST request?

How to parse string html from submitted iframe

I'm uploading a file in an iframe (with name and id=upload_target) to some server. As a response it creates a callback json style :
'result':'true'
So I'm trying the following. On onload action of my IFrame I've added an event listener, which should run function grabbing data :
function fileUploadFunction(){
(...)
$("#upload_target").onload = uploadDone;
(...)
};
function uploadDone() {
alert("uploadDone");
var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
var data = eval("("+ret+")");
if(data.result == 'true') {
alert("GREAT SUCCESS !!");
}
else {
alert("GREAT FAILURE :(");
}
}
But as a result I'm not getting anything at all. Should I return callback status in different form, or can it be solved differently ? Because even the first alert from uploadDone is not shown problem probably lies somewhere else.
Probably the reason nothing is happening is because of the funky way you have to detect an iFrame is loaded. Check the post jQuery .ready in a dynamically inserted iframe. I am assuming you are using jQuery.

Categories

Resources