not pass my json arrays to php, I dont know why - ajax

My code is not working in browser, and not send datas to process.php. I don't know where is the problem.
My original js data structure - data-today.php (which daily updated and I open after the head)
var football = new Array(); football[0] = new Array('Argentina','Primera Division','Boca Juniors'); football[1] = new Array('Argentina','Primera Division','Lanús'); football[2] = new Array('England','Premier League','Arsenal'); football[3] = new Array('England','Premier League','Liverpool');
And here is my code, and I would like to pass all datas to a simple html dom parser. I don't know where is the problem.
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="json2.js">
</script>
<script src="data-today.php" type="text/javascript" language="javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
$(document).ready(function () {
var json = JSON.stringify(football);
for (var i = 0; i < json.length; i++) {
alert(json);
$.ajax ({
type:"POST",
url:"process.php",
contentType: "application/json",
dataType: "json",
async: true,
data: {
country: $("json[i][0]"),
competition: $("json[i][1]"),
team: $("json[i][2]")},
success: function(){ alert("data")},
error: function(){ alert("error")}
});
}
});
</script>
<table>
</table>
</body>
</html>

You have the data already nicely in javascript array and if you really want to post the data in the for loop you can use something like below.
$(document).ready(function ()
{
// scrap that line, you have the values in array (of arrays)
//var json = JSON.stringify(football);
for (var i = 0; i < football.length; i++)
{
//alert(json);
$.ajax ({
type:"POST",
url:"process.php",
contentType: "application/json",
dataType: "json",
async: true,
data: {
country: football[i][0],
competition: football[i][1],
team: football[i][2],
success: function(){ alert("data")},
error: function(){ alert("error")}
});
}
});
You probably should also rename your data-today.php to data-today.js as it seems to be a javascript file instead of php one...

(1) var football is an array, so when you do var json = JSON.stringify(football); it turns it into a string, so when you do for (var i = 0; i < json.length; i++) { it is looping over the string chars, and not an array.
(2) if json is an array, then there is no need to make it an object - $("json[i][0]"). just access it directly - json[i][0].
So now your code should look like
<script language="javascript" type="text/javascript">
var football = new Array();
football[0] = new Array('Argentina','Primera Division','Boca Juniors');
football[1] = new Array('Argentina','Primera Division','Lanús');
football[2] = new Array('England','Premier League','Arsenal');
football[3] = new Array('England','Premier League','Liverpool');
$(document).ready(function () {
var json = football;
for (var i = 0; i < json.length; i++) {
$.ajax({
type:"POST",
url:"process.php",
contentType: "application/json",
dataType: "json",
async: true,
data: {
country: json[i][0],
competition: json[i][1],
team: json[i][2]},
success: function(){ alert("data")},
error: function(){ alert("error")}
});
}
});
</script>
jsFiddle example - http://jsfiddle.net/pdrw4r73/1/ (I commented out the alert("error") in error: function(){ alert("error")}, but you can expand the POST in the Firebug Lite to see the $.ajax() posts.)

Thanks for the answers for everybody. If I try to update my code I got this error at firefox console: SyntaxError: expected expression, got '}' , somwhere before the </script> tag. I tried both version, but the result is the same if I try to open my process.php.
my process.php:
<?php
include ("auto3.php");
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>

Related

Ajax Request with Googlemap API

I'm building a page that will display a Googlemap with markers. Since I have about 50000 markers, I decided not to load them all at once.
Therefore I tried building an JSON request to my server (see code below) but here is my problem:
When I use the code as it is presented here, the Map is blank (no Map shows up).
When I remove the $.ajax and leave the function getMarkers emtpy, the map shows properly (whitout marker of course).
Can anyone tell me what I'm doing wrong please?!
Thank you!
(If that is any help, I'm using Django)
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init_map() {
var mapOptions = {
center: new google.maps.LatLng(48.853,2.35),
zoom: 6,
streetViewControl: false,
};
var myMap = new google.maps.Map(document.getElementById("map-container"),mapOptions);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(myMap, 'idle', getMarkers);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
}
google.maps.event.addDomListener(window, 'load', init_map);
function getMarkers() {
$.ajax({
type: 'POST',
url: {%url 'pointslink'%},
async: "true",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(
coords: myMap.getBounds(),
zoom: myMmap.getZoom()
),
success: updateMarkers
});
}
function updateMarkers(data) {
{% for city in data %}
var pos = new google.maps.LatLng({{city.latitude}},{{city.longitude}});
var marker = new google.maps.Marker({
position: pos,
map: myMap,
title:'{{city.name}}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('Name: {{city.name}}<br/>Population: {{city.population}}');
infowindow.open(myMap, this);
});
{%endfor%}
}
</script>

Display Ajax loader before load data

Hello friends i want to show Ajax loader before Data load in particular div but problem is the data is coming dynamically on same page but my script calling data from another file Script.php please see my code below
Script
<script>
function loadingAjax(div_id)
{
$("#"+div_id).html('<img src="ajax-loader.gif"> saving...');
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
HTML
<body onload="loadingAjax('myDiv');">
<div id="myDiv"></div>
<div id="xyz"><img src="ss/image/abc.jpg" /></div>
</body>
Its working fine but i want to load data in same page please help me
Thanks in advance ....
EDIT
I want to show loader before load data #xyz into #myDiv
you can try with following html -
<body onload="loadingAjax('myDiv');">
<div id="myDiv">
<img id="loading-image" src="ajax-loader.gif" style="display:none;"/>
</div>
</body>
and the script -
<script>
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
beforeSend: function() {
$("#loading-image").show();
},
success: function(msg) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
}
});
}
</script>
you can try with following script
<script>
function ajax()
{
var options = {};
options.url = '';
options.type = 'post';
options.data = '';
options.dataType = 'JSON'; // type data get from sever
options.contentType = 'application/json';// type data post to sever
options.async = false;
options.beforeSend = function () {
};
options.success = function (data)
{
};
options.error = function (xhr, status, err) {
console.log(xhr.responseText);
};
$.ajax(options);
}
</script>

AJAX Crashes Chrome

Umm.. my problem is that i want to use ajax for my chatbox but whenever i try to put ajax for no-reload refresh Chrome/Firefox Crashes down.. HERE's my code:
/chatlog.php/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
//<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$.ajaxSetup({ datatype: "html" });
$('#loaddiv').load('chatlog.php');
}, 10000);
</script>
/submit.php/
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".submit").click(function(){
var message = $("#message").val();
var dataString = 'message'+message;
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
async: false,
});
/*$message=$_POST['message'];
$name = $_SESSION['username'];
$room = $_SESSION['room'];
$user = $_SESSION['user'];*/
});
});
</script>
$.ajax({
type: "POST",
url: "submit.php",
data: { message : message },
async: false
});
Also put your ajaxSetup outside of the setInterval function.
$.ajaxSetup({ datatype: "html" });
Pass your data properly, like:
var dataString = 'message'+message;
//Should Be
var dataString = 'message='+message;
//OR
var dataString = {'message' : message };

$.submit form and replace div using ajax has strange jquery behaviour on the new partialview

I think the problem is with jQuery, i don't know for sure.
Let me explain the situation.
Screenshot 1
I fill in the partialView and click on submit.
The submit is a jQuery event handler with the following code:
_CreateOrEdit.cshtml
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
$.post(action, serializedForm, function (data) {
$("#main-content").html(data);
});
return false;
});
</script>
This all works fine on the first-run.
Then when i submit the form when it is invalid (Screenshot 1),
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
context.Clients.Add(client);
context.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(client);
}
Then it tries to redisplay the same form again (Controller Client, Action Create), but something isn't triggered right (Screenshot 2). The layout is wrong (buttons still hidden), the tabs aren't working (javascript), ...
Worst of all, i don't get any error in Firebug, Chrome Console, ...
Does anyone have an idea what could be the problem, because i really haven't got a clue what's happening. It seems to me that nothing has changed, but it did :s
Fyi, an equivalant for the post function is :
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
request.done(function (msg) {
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Before submit, everything loads fine
After submit, same form is called. jQuery isn't working anymore and form is getting bricked (i think this is "side" behaviour from the jQuery breaking)
Edit: (on request)
Here is the partialView in full
_CreateOrEdit.cshtml doesn't contain any javascript for now, the result is the same, so i only posted Create.cshtml.
Create.shtml
#model BillingSoftwareOnline.Domain.Entities.Client
<div class="container_12 clearfix leading">
<div class="grid_12">
#using (Html.BeginForm("Create", "Client", FormMethod.Post, new { #class="form has-validation", id="CreateOrEditSubmit"}))
{
#Html.Partial("_CreateOrEdit", Model)
<div class="form-action clearfix">
<button class="button" type="submit">
OK</button>
<button class="button" type="reset">
Reset</button>
</div>
}
</div>
</div>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.itextclear.js")"> </script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.uniform.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.tools.min.js")"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
</script>
Since this markup is returned as a partial, you need to reinitialize your javascript.
This is hacky, but try putting your script in the partial view, instead of _CreateOrEdit.cshtml, and see if that works.
Update
After seeing the cshtml, it looks like it is not working because $(document).ready() has already executed, before the ajax load. Try this instead:
$(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
});
Add the following instructions to the end of your ajax callback, so that the styling is applied after the form has been injected to the DOM:
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(".tabs > ul").tabs("section > section");

How to pass variable from jquery to code in c#

in my page i have an int variable name mySerial and i want to pass a value from a script
mySerial =ui.item.Serial is not working
You could pass this variable as query string parameter to some controller action:
<script type="text/javascript">
var mySerial = '12345';
$.ajax({
url: '#Url.Action("Foo", "Home")',
type: 'POST',
data: { mySerial: mySerial },
success: function(result) {
alert('success');
}
});
</script>
and the Foo action:
[HttpPost]
public ActionResult Foo(string mySerial)
{
... do something with the serial here
}
Another possibility is to perform a redirect if you don't want to use AJAX:
<script type="text/javascript">
var mySerial = '12345';
var fooUrl = '#Url.Action("Foo", "Home")';
window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial);
</script>
Or maybe I misunderstood your question and you want to assign your javascript variable to some value coming from the view model? In this case:
<script type="text/javascript">
var mySerial = #Html.Raw(Json.Encode(Model.MySerial));
</script>
you could pass value from your jquery to controller action like this ...
$(document).ready(function()
{
var postdata = { name: "your name", Age: "your age" };// you can pass control values
$.ajax({
ur: /home/index,
data: postdata,
success: function(returndata)
{
// do something here for the return data...
}
});
});
in your controller
public ActionResult PostedDAta(string myname, string myage)
{
// do somethign here and return Json back to Jquery code
return Json(data,JsonRequestBehaviour.AllowGet);
}

Resources