Passing values from ajax page to calling page javascript function - php

One part of my page is being loaded via ajax using jquery. For example this initial page has a name first.php. It has a div with it's innerHTML generated from ajax called script (for example ajax is calling second.php). Is it possible to pass some values from ajax executed script (second.php) to original site. I need to access this value from original site (the one calling second script via ajax) javascript function, and I don't want to use hidden fields.
For example, my site has some captcha that is being displayed and processed through ajax. I don't want to write captcha result to some hidden field and access it with original site javascript function because of possible javascript injection attack...

Since you call your secound.php script via ajax, you surely could read the result.
$.ajax({
url: 'secound.php',
success: function(data) {
// now data contains the code returned by secound.php
}
});
Now the most common way to return data from your secound.php script is returning it in JSon format. Then you could do someting like:
var obj = jQuery.parseJSON(data);
alert(obj.name);
For this example your secound.php needs to return
{"name":"John"}

Related

should jquery ajax go to the same page or another php file?

My Current Setup
my sites home page (rankings.php) shows a list of users with a search form at the top to filter users by their gender or city.
I want to use jquery ajax to update the results without reloading the page.
My Question:
with either method (load,post,get) you need to enter the url to send the request to but I'm not sure if the url should be the rankings.php page itself or another php file that holds the mysql query to get new results from the database. Which is best? should ajax requests go to another php and then the results sent back to the main php file where the content will be reloaded or should the ajax request go to the same php file it came from and then jquery to replace the content with the returned html data?
shorter version of question: should ajax url point to the page the ajax request comes from or point to another php file and then the data returned back?
It should point to the URL of the script that performs whatever function you need the AJAX request to do. It can be the same or a different URL from the page that contains the caller. If it's the same page, you'll need to put conditionals in the script that detects whether it's being used to process an AJAX request or to display the regular page, usually by checking the parameters.
For instance, you might send the AJAX request with:
$.ajax({
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
type: 'post',
data: { action: 'dosomething', ... },
...
});
Then in the PHP script, you would do:
if (isset($_POST['action']) {
// code to process AJAX request
} else {
// code to display the page HTML
}
I generally find it simpler to put the AJAX code in a separate script, so I don't have to do that.

Use AJAX call to update a php session variable

I have a PHP script that reads PDF files in a specified folder. I have each file split by page. I have stored these file names in an array and have created an index variable called $count. There are left (page down) and right (page up) arrows. I need $count to increment on page down and decrement on page up. I know I need to use AJAX to do this, but the only data I have to send is the onclick event.
Perform an ajax request sending your action as a parameter :
JQuery.ajax({
url: 'my_script.php?action=increment'
});
Then in my_script.php, update your session variable according to the parameter action.
I used jQuery for my example but any other library will do just fine.
jQuery's $.ajax() function is used to perform an asynchronous HTTP request.
here is a demo code to interact with php file
$.ajax({
type:'POST',
url:'contact_form.php',
data:'details='+Message,
success:function(msg){
$('#show-msg').html('<span >'+msg+'</span>');
}
});
The onclick event should be enough to send.
Technicly you just need to send to your server what button has been pressed and from there your variable in your session will go down or up according to whats the php logic receiving the ajax call.
So just make a simple php page that does something like this
if(isset($_REQUEST['Down']))
$count --;
if(isset($_REQUEST['Up']))
$count ++;
And on your page were you actually click the buttons
Just have a regular ajax call like so,
$("#UpButton").click(function(){
$.post('linkToYourPage.php',{Up:true});
});
$("#DownButton").click(function(){
$.post('linkToYourPage.php',{Down:true});
});

jQuery AJAX vs PHP in HTML attribute

If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Dom Value After Ajax Call

I have a table where one field is titled a secure password. In this field, there is an input button that calls an AJAX function. The AJAX function on return updates the password in the secured password field. This updates the DOM value for that field.
On this same page I have another function which uses Javascript to parse all the elements in the table into an array. The problem is the Javascript function is writing what was originally in the secure password field rather than what the AJAX function has updated it to.
It seems as though Javascript does not pull the current DOM value but the DOM value when the page was loaded. Is this the default nature of Javascript and if so how can I get around this so I can get the current values for all fields in the table, not just the page load values.
This script is written in PHP/Javascript, thanks in advance for the assistance.
Your Javascript function that parse all elements in the table into an array uses
the document.ready function or is loaded only once when the Page is loaded.
In Vanilla JS
document.addEventListener('DOMContentLoaded', (event) => {
//Where you wrote your function
})
Jquery
$(document).ready(function() {
// where you have your function if you are using Jquery
});
And AJAX calls do not reload the page. That means your Javascript function does not get executed so it does not update the array with the new data from the calls.
You need your Javascript as a callback function to the success or complete property of the AJAX call.
jQuery.ajax({
type: 'POST',
url: ajaxurl,
success: function() {
parsingFunction();
},
error: function() {
alert(errorThrown);
}
});
Did you try using a hidden input field for storing the data instead of updating the text input? Or may be you can try using the data-xxx attributes
bests,

Categories