below is an ajax but it wont work, what seems be the problem? assume that I have requestparser.php and inside it i have "echo "yes ajax work!";".
$(document).ready(function(){
// start ajax form submission
$.ajax({
url: "requestparser.php",
type:"POST",
data: ({ "pulldata" : "oy" }),
success:function(e){
if(($.trim(e)=="success")){
alert("yes");
}else{
alert("no");
}
},error:function(){
alert("error");
}
});
});
as above ajax function ,the process should be, on load it will send first a post request to requestparser.php with a post name of "pulldata" and post content of "oy" and when the requestparser receive that post request from the ajax so then respond with "yes ajax work!" and since the respond from requestparser.php is not equal to success then it should display "no".
any help would be greatly appreciated
I tried to debug your code and it worked fine for me. So can you try this code and say what error it shows ?
$(document).ready(function () {
$.ajax({
url: "test.php",
type: "POST",
data: ({
"pulldata": "oy"
}),
success: function (e) {
console.log(e);
},
error: function (e) {
console.error(e);
}
});
});
test.php
<?php
var_dump($_POST);
One more thing, just for confirmation, you have included jQuery in your page before using ajax right ?
Related
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
i want to post an input and select to an php site using ajax and get the result displayed in a span using the success function.
After searching, I can't get it really done, below is my code so far:
<span id="span_to_post_response"></span>
$(document).on("click", "#btn_to_click", function () {
var form_to_send_in_var = $("#form_to_serialize").serialize();
$.post('<?php echo base_url();?>api/mySite',form_to_send_in_var);
});
Where do I put my success function?
Instead of using .post function,Try using something like this
jQuery.ajax({
url: '<?php echo base_url();?>api/mySite',
type: 'POST',
data: {
// Send the data you want
// email: jQuery('.address').val()
},
success: function(data){
jQuery('#span_to_post_response').text(data);
},
error: function() {
jQuery('#span_to_post_response').text('Sorry, an error occurred.');
}
});
I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];
I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid)
{
alert("test");
$.post('login.php', this.$form.serialize(), function(response) {
// asdasd
}, 'json');
}
}
I get the alert box but the post doesn't seem to work. Is there anything clearly wrong in the above code?
I am using IdealForms.
The request works, there must be an issue in your server side code. Make sure that:
1) login.php exists and it's in the right path.
2) Your PHP script echos JSON. Try a simple test script:
<?php
// login.php
echo json_encode(array('value' => true)); // send as JSON
Then in JavaScript log the response to the console (press F12 or Cmd+Shift+I):
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid) {
$.post('login.php', this.$form.serialize(), function(response) {
console.log(response);
}, 'json'); // read as JSON
}
}
The console should output an object {value: true}.
PS: I'm the developer of Ideal Forms.
All you need to do is call JQuery, and use code like this:
$.ajax({
type: "POST",
url: "login.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});