I am pretty new to JavaScript and PHP.
I'd like to create a JavaScript function that contains a variable, passes this on to PHP on another page and opens that page.
Here is what I got so far (not working):
My JS:
function test()
{
$.ajax(
{
url: "my-new-page.php",
type: "POST",
data:
{
varJS: "XXX"
},
error:function(err)
{
alert(err.statusText);
},
success: function(data)
{
window.open("my-new-page.php");
}
});
}
My PHP (on the new page):
$varPHP = $_POST['varJS'];
As I understand your question, you just want a simple javascript function that redirects to another page / PHP-script with some params?
my-new-page.php
<?
$varPHP = $_GET['varJS'];
echo $varPHP;
?>
javascript
function reDirect(varJS) {
var page='my-new-page.php?varJS='+varJS;
document.location.href=page;
}
reDirect('test')
To just open a new window passing it a variable, you can do that within a query string.
Simply call
window.open("my-new-page.php?varJS=XXX);
And Handle Query String on my-new-page.php
-Shakir
The entire point of using Ajax is that it doesn't take the user to a new page. Don't use Ajax.
If you need to make a POST request then generate a form and hidden inputs with document.createElement and friends, append it to the current document, and then call its submit() method.
Related
When i click the button,am calling a function it will return some values.I need to get those values and send through AJAX using Jquery.
Give below the click button function.Inside this function am calling another function(here returning values i need to pass through ajax)
The problem is i cant able to send those values inside ajax.
Can anyone plz help me to do this?I dont know where am doing mistakes.
Here is the function am calling inside button click
in this eaxample i have send with the ajax request the name of the function that i want to use
let fd = new FormData();
fd.append('function_name', 'activity_submitted');
$.ajax({
url: "activity_submitted.php",
type: "POST",
data: fd,
complete: function (results) {
try {
var str = JSON.parse(results.responseText);
}
catch (e) {
}});
in the PHP file (according to the $_REQUETS['function_name']) go to your function, the function will echo a JSON with the values that you want to send back
$_REQUEST is a super global variable which is widely used to collect data after submitting html forms.
function activity_submitted() {
.
.
.
$res = array('articleid'=>$articleid);
$resBack = (json_encode($res, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
echo ($resBack);
}
?>
Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}
I' m using cms ModX and want to send Ajax request to server using post method. The problem is that the post data of the second, the third and so one requests doesn't change and remains the same as in the first request.
To clarify the situation I provide the following example.
The javascript is the following:
var reqCount = 0;
$(document).ready(function () {
$(window).scroll(function() {
var dataToPost = {'reqCount' :reqCount};
$.ajax({
url: 'http://example.com/ajaxTest',
method: 'POST',
data: dataToPost,
dataType:"json",
success: function(data){
ajaxCountFromServer = data['ajaxCount'];
reqCount=reqCount+1;
}
});
}
}
Also I created resource with address http://example.com/ajaxTest in Modx with the code, running the snippet:
[[getAJAX]]
getAJAX snippet is the following:
<?php
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$reqCount = $_REQUEST['reqCount'];
$json_obj = array("ajaxCount" =>$reqCount);
return json_encode($json_obj);
}
?>
So, after the first scroll reqCount=0, it's passed to server and after the server responses(success callback) ajaxCountFromServer=0 and reqCount=1. There all works well.
However, after the second scroll reqCount=1 and after the server response ajaxCountFromServer=0,but it should be 1.
How to fix it?
The solution is quite simple. In the page customizing of the resource http://example.com/ajaxTest, where snippet getAJAX is called, I just unchecked the checkbox "Cacheable".
The correct way to do it is
[[!getAJAX]]
The snippet is not cached now
I am writing a javascript which will post hostname of the site to a php page and get back response from it, but I don't know how to assign the hostname to adrs in url and not sure that code is correct or not.And this needs to done across server
javascript:
function ursl()
{
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
success: function (response)
if (response)=='yes';
{
alert("yes");
}
});
}
track.php
$url=$_GET['adrs'];
$sql="SELECT * FROM website_ad where site='$url'";
$res=mysqli_query($link,$sql);
if(mysqli_num_rows($res)==0)
{
echo"no";
}
else
{
echo"yes";
}
Your ajax function should be written thusly:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=' + window.location.hostname,
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
window.location.hostname will give you the host name. You are passing it to the ajax url by concatenating it. Alternatively, as katana314 points out, you could pass the data in a separate parameter. Your ajax call would then look like this:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
data: {adrs: window.location.hostname},
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
I'm not sure what you intend response to be, but this code assumes it is a string and will match true if the string is 'yes'. If response is meant to be something else, you need to set your test accordingly.
$.getScript() will load your external script, but since it's asynchronous you'll have to put any code that is dependent on that in the callback.
In this type of GET request, the variable simply comes after the equals sign in the URL. The most basic way is to write this:
url: 'http://example.com/en/member/track.php?adrs=' + valueToAdd,
Alternatively, JQuery has a more intuitive way of including it.
$.ajax({
url: 'http://example.com/en/member/track.php',
data: { adrs: valueToAdd }
// the rest of the parameters as you had them.
Also note that you can't put a script tag inside a script. You will need some other way to run the Javascript function mentioned; for instance, wrap its contents in a function, load that function first (with a script tag earlier in the HTML), and then call it on success.
And for the final puzzle piece, you can retrieve the current host with window.location.host
You'll need to change this line to look like so:
url: 'http://example.com/en/member/track.php?adrs='+encodeURIComponent(document.URL)
The full success function should look like so:
success: function (response){
if (response==="yes"){
//do your thing here
}
}
That should solve it...
I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.
You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.
Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});