How to send variables with GET without reloading page - javascript

What I'm trying to accomplish is the following. I have a php page which loads some variables from an mysql db. Then I want to send these variables using GET to another page without opening the page where the variables are being send to.
At first I really didn't know how to do this until I came across the following:
$( document ).ready(function()
{
$.ajax({
url: 'the_url',
type: 'GET',
data: {Gender:Male,DateOfBirth:1968-07-21},
success: function(data) {
//called when successful
alert("Succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("Failed");
}
});
}
The $test and $test1 are php variables which I would like to send to the other page. But apparently i'm doing something wrong. Not even the alerts are being triggered so there is probaly something wrong with my syntax.
I'm using the following jquery version: jquery-2.1.4.min.js
If there is something wrong in the way I asked this question please let me know and give me the help to update the question.

Just assign PHP variables to JS variables and also change the data sending part as well there is no need of ' for data sending.
$( document ).ready(function()
{
var test = '<?php echo $test; ?>';
var test1 = '<?php echo $test1; ?>';
$.ajax({
url: 'the_url',
type: 'POST', //change type to POST rather than GET because this POST method of sending data
data: {test:test,test1:test1},
success: function(data) {
//called when successful
$('#ajaxphp-results').html(data);
alert("succes");
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert("failed");
}
});
}

Related

How to merge two ajax requests into one

I'm editing the form-edit-account.php template. This template contains a form that allows users to change account settings (name, surname, age etc ..). Originally the form had no ajax requests, so I added them to save data without page refresh. Everything works fine but I have some doubts about how I could refine the code.
When click on submit button of my form, in google console network tab I see that there are two requests, one belongs to Ajax Handling Error, while the other belongs to Ajax Save settings.
Ajax Handling Error allows me to view messages when form fields are not respected or success messages if all goes well.
Ajax save settings
actually saves the data without reloading the page.
What I would like to do is get a single request (saves settings and shows error messages). It's possible merge ajax hanling error code and ajax save settings code in a single request instead of two ?
Js at the end of the form
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
$.post($form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json');
//Ajax Save settings
jQuery.ajax({
type: "POST",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
wc_add_notice("<b>Nome</b> รจ un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else{
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}
I found a solution, I don't know how right it can be, I'm just a fan and not a programmer. With this solution I only see a request in google console network card. Also everything works fine, the data is saved and the messages are ok. I post the solution below for anyone who is in the same situation as me.
I just changed the script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.woocommerce-notices-wrapper').html(data);
}, 'json'
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});

Ajax success not working for me

follow code is supposed to show alert msg. It is doing nothing. Can anyone tell me where I am wrong. Everything is working nicely execpt alert().
<script>
$(document).ready(function(){
var baseUrl = document.location.origin;
$(".ProductRemove").click(function(){
var row_id = $(this).attr('id');
$.ajax({
type:"POST",
cache:false,
url:baseUrl+"/shop/api/cart",
data:"row_id="+row_id+"&action=remove", // multiple data sent using ajax
success: function () {
alert('success');
},
error: function(){
alert('failure');
}
});
});
});
Thanks to all,
I got the solution. It is calling error function instead of success because I am returning in nothing from the server.
In ajax empty is not considered as JSON data. So to fix that I have to echo "json_encode(NULL);" in my server.

Parsing Javascript variable to AS3

I'm trying to write a simple 2 way chat but got a problem. I'm sure it's very basic but couldn't figure out since I'm new to this.
Below is my JS code to pass a streamID to AS3:
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: 'action=sd_chat_code&chat_code='+chat_code,
success: function(data){
object.streamCompanion(data);
},
error: function(data) {
console.log(data);
}
});
and in AS file, I got the streamID passed through as below:
public function streamCompanion(data):void {
var netStreamObj:NetStream = new NetStream(_nc);
netStreamObj.play(data);
_client.attachNetStream(netStreamObj);
}
Here's my code so you can check https://codepen.io/adamboy_1802/pen/MpqyML
The variable data above returns "12345" correctly. I tried to output is via JS and there's nothing wrong:
ExternalInterface.call("function() { console.log("+data+") }")
Any advice would be greatly appreciated.
(Solved)
So after trying to create a text box and output the variable data in Flash instead of alert it out via jQuery, the problem relied in my ajax call, where I use echo json_encode(my_var), simply change it to echo my_var fixed the problem.

submit form without refresh page and load output into html [duplicate]

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I want to submit a form information to another php script without leaving the page and show the output in that same page.
Here's my ajax function to load php output in html without leaving the page. It doesn't do that if my form has a submit button. It only works with a normal clickable button.
$('#btnLoad').click(function(){
$.ajax({
type: 'POST',
url: 'page1.php',
success: function(data){
if(data != null) $('#content').text(data);
}
});
});
The problem is that I need to send POST variables to my PHP script but when I do, it goes to my PHP script page. I just want the script to receive the POST variables, run the script and then show the output in my HTML page.
Here's the script that doesn't go to PHP script page. I don't know if the PHP script runs with this function.
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('page1.php', $(this).serialize(), function (data) {
}).error(function() {
});
e.preventDefault();
});
});
How can I combine these two scripts into one, to submit my variables via POST, run the script and show the output in my HTML page?
Combining both Ajax
$("#btnLoad").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "page1.php",
data: $('#myForm').serialize(),
success: function (msg) {
$("#thanks").html(msg);
},
error: function (msg) {
$("#error").html(msg);
}
});
});
HTML to show success message
<div id="thanks"></div>
HTML to show error message
<div id="error"></div>
PHP Server Side
<?php
if (isset($_POST['submit'])) { //assuming you have input with name="submit"
//Do what ever you like to do next
//If everything good
echo "<strong>Success!</strong> This Is Success Thanks Message. If everything go exactly as Planned.";
} else {
echo "<strong>Error!</strong> This Is Error Message. If anything goes south.</div>";
}
?>
Edited: OP asked to show messages in jQuery modal dialog
In Ajax after success call, try like this
success: function(msg) {
$("#thanks").html(msg);
$("#modalId").dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
},
And same for error function
Note: I haven't test this so not sure it will work out of the box or need any debugging.
Why do you not replace the submit buttons with normal buttons then?
What you could do in jQuery is:
$(formSelector).on('submit',function (e) {
e.preventDefault()
//Place your ajax here.
})
you can do something like
$('#btnLoad').click(function(){
$.ajax(url,
{
data: { variable1: $("#variable1").val(), variable2: $("#variable2").val() },
type: "POST",
success: function(data) {
if(data != null) $('#content').text(data);
}
});
});
And normally I don't use a form if I need to send data via ajax, I use just JS.

Jquery form ajax call trouble

I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?

Categories